diff --git a/Tron protobuf protocol document.md b/Tron protobuf protocol document.md index ecc52b1b70c..9e5e5ec7de9 100644 --- a/Tron protobuf protocol document.md +++ b/Tron protobuf protocol document.md @@ -1537,6 +1537,7 @@ message `SmartContract` has mutiple attributes and nested message `ABI` Function = 2; Event = 3; Fallback = 4; + Receive = 5; } ``` @@ -1617,6 +1618,7 @@ message `SmartContract` has mutiple attributes and nested message `ABI` Function = 2; Event = 3; Fallback = 4; + Receive = 5; } message Param { bool indexed = 1; diff --git a/actuator/src/main/java/org/tron/core/actuator/AccountPermissionUpdateActuator.java b/actuator/src/main/java/org/tron/core/actuator/AccountPermissionUpdateActuator.java index 27be61bfff4..cdbdbedc24e 100644 --- a/actuator/src/main/java/org/tron/core/actuator/AccountPermissionUpdateActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/AccountPermissionUpdateActuator.java @@ -53,7 +53,11 @@ public boolean execute(Object object) throws ContractExeException { accountStore.put(ownerAddress, account); Commons.adjustBalance(accountStore, ownerAddress, -fee); - Commons.adjustBalance(accountStore, accountStore.getBlackhole().createDbKey(), fee); + if (chainBaseManager.getDynamicPropertiesStore().supportBlackHoleOptimization()) { + chainBaseManager.getDynamicPropertiesStore().burnTrx(fee); + } else { + Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee); + } result.setStatus(fee, code.SUCESS); } catch (BalanceInsufficientException | InvalidProtocolBufferException e) { diff --git a/actuator/src/main/java/org/tron/core/actuator/AssetIssueActuator.java b/actuator/src/main/java/org/tron/core/actuator/AssetIssueActuator.java index 50ee44e2449..55218897c5d 100644 --- a/actuator/src/main/java/org/tron/core/actuator/AssetIssueActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/AssetIssueActuator.java @@ -85,9 +85,11 @@ public boolean execute(Object result) throws ContractExeException { } Commons.adjustBalance(accountStore, ownerAddress, -fee); - Commons.adjustBalance(accountStore, accountStore.getBlackhole().getAddress().toByteArray(), - fee);//send to blackhole - + if (dynamicStore.supportBlackHoleOptimization()) { + dynamicStore.burnTrx(fee); + } else { + Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee);//send to blackhole + } AccountCapsule accountCapsule = accountStore.get(ownerAddress); List frozenSupplyList = assetIssueContract.getFrozenSupplyList(); Iterator iterator = frozenSupplyList.iterator(); diff --git a/actuator/src/main/java/org/tron/core/actuator/ClearABIContractActuator.java b/actuator/src/main/java/org/tron/core/actuator/ClearABIContractActuator.java index 834d08d21a2..0b842b830a1 100755 --- a/actuator/src/main/java/org/tron/core/actuator/ClearABIContractActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/ClearABIContractActuator.java @@ -19,6 +19,8 @@ import org.tron.protos.Protocol.Transaction.Result.code; import org.tron.protos.contract.SmartContractOuterClass.ClearABIContract; +import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; + @Slf4j(topic = "actuator") public class ClearABIContractActuator extends AbstractActuator { @@ -90,7 +92,7 @@ public boolean validate() throws ContractValidateException { if (accountCapsule == null) { throw new ContractValidateException( ActuatorConstant.ACCOUNT_EXCEPTION_STR - + readableOwnerAddress + "] not exists"); + + readableOwnerAddress + NOT_EXIST_STR); } byte[] contractAddress = contract.getContractAddress().toByteArray(); diff --git a/actuator/src/main/java/org/tron/core/actuator/CreateAccountActuator.java b/actuator/src/main/java/org/tron/core/actuator/CreateAccountActuator.java index 7b6664b608e..1c6aca4d7d7 100755 --- a/actuator/src/main/java/org/tron/core/actuator/CreateAccountActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/CreateAccountActuator.java @@ -1,5 +1,7 @@ package org.tron.core.actuator; +import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; + import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import java.util.Objects; @@ -49,8 +51,11 @@ public boolean execute(Object result) Commons .adjustBalance(accountStore, accountCreateContract.getOwnerAddress().toByteArray(), -fee); // Add to blackhole address - Commons.adjustBalance(accountStore, accountStore.getBlackhole().createDbKey(), fee); - + if (dynamicStore.supportBlackHoleOptimization()) { + dynamicStore.burnTrx(fee); + } else { + Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee); + } ret.setStatus(fee, code.SUCESS); } catch (BalanceInsufficientException | InvalidProtocolBufferException e) { logger.debug(e.getMessage(), e); @@ -95,7 +100,7 @@ public boolean validate() throws ContractValidateException { String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); throw new ContractValidateException( ActuatorConstant.ACCOUNT_EXCEPTION_STR - + readableOwnerAddress + "] not exists"); + + readableOwnerAddress + NOT_EXIST_STR); } final long fee = calcFee(); diff --git a/actuator/src/main/java/org/tron/core/actuator/ExchangeCreateActuator.java b/actuator/src/main/java/org/tron/core/actuator/ExchangeCreateActuator.java index 86199c16f31..b7f5b90da45 100755 --- a/actuator/src/main/java/org/tron/core/actuator/ExchangeCreateActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/ExchangeCreateActuator.java @@ -1,5 +1,6 @@ package org.tron.core.actuator; +import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; import static org.tron.core.capsule.utils.TransactionUtil.isNumber; import static org.tron.core.config.Parameter.ChainSymbol.TRX_SYMBOL_BYTES; @@ -22,7 +23,6 @@ import org.tron.core.store.DynamicPropertiesStore; import org.tron.core.store.ExchangeStore; import org.tron.core.store.ExchangeV2Store; -import org.tron.core.utils.TransactionUtil; import org.tron.protos.Protocol.Transaction.Contract.ContractType; import org.tron.protos.Protocol.Transaction.Result.code; import org.tron.protos.contract.ExchangeContract.ExchangeCreateContract; @@ -118,9 +118,11 @@ public boolean execute(Object object) throws ContractExeException { accountStore.put(accountCapsule.createDbKey(), accountCapsule); dynamicStore.saveLatestExchangeNum(id); - - Commons.adjustBalance(accountStore, accountStore.getBlackhole().createDbKey(), fee); - + if (dynamicStore.supportBlackHoleOptimization()) { + dynamicStore.burnTrx(fee); + } else { + Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee); + } ret.setExchangeId(id); ret.setStatus(fee, code.SUCESS); } catch (BalanceInsufficientException | InvalidProtocolBufferException e) { @@ -161,7 +163,7 @@ public boolean validate() throws ContractValidateException { } if (!accountStore.has(ownerAddress)) { - throw new ContractValidateException("account[" + readableOwnerAddress + "] not exists"); + throw new ContractValidateException("account[" + readableOwnerAddress + NOT_EXIST_STR); } AccountCapsule accountCapsule = accountStore.get(ownerAddress); diff --git a/actuator/src/main/java/org/tron/core/actuator/ExchangeTransactionActuator.java b/actuator/src/main/java/org/tron/core/actuator/ExchangeTransactionActuator.java index 743fea39774..612f673832e 100755 --- a/actuator/src/main/java/org/tron/core/actuator/ExchangeTransactionActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/ExchangeTransactionActuator.java @@ -1,5 +1,6 @@ package org.tron.core.actuator; +import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; import static org.tron.core.capsule.utils.TransactionUtil.isNumber; import static org.tron.core.config.Parameter.ChainSymbol.TRX_SYMBOL_BYTES; @@ -137,7 +138,7 @@ public boolean validate() throws ContractValidateException { } if (!accountStore.has(ownerAddress)) { - throw new ContractValidateException("account[" + readableOwnerAddress + "] not exists"); + throw new ContractValidateException("account[" + readableOwnerAddress + NOT_EXIST_STR); } AccountCapsule accountCapsule = accountStore.get(ownerAddress); diff --git a/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceActuator.java b/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceActuator.java index 0892c5f1094..fa254f4e6ba 100755 --- a/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceActuator.java @@ -1,5 +1,6 @@ package org.tron.core.actuator; +import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; import static org.tron.core.config.Parameter.ChainConstant.FROZEN_PERIOD; import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; @@ -142,7 +143,7 @@ public boolean validate() throws ContractValidateException { if (accountCapsule == null) { String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); throw new ContractValidateException( - ActuatorConstant.ACCOUNT_EXCEPTION_STR + readableOwnerAddress + "] not exists"); + ActuatorConstant.ACCOUNT_EXCEPTION_STR + readableOwnerAddress + NOT_EXIST_STR); } long frozenBalance = freezeBalanceContract.getFrozenBalance(); @@ -207,7 +208,7 @@ public boolean validate() throws ContractValidateException { String readableOwnerAddress = StringUtil.createReadableString(receiverAddress); throw new ContractValidateException( ActuatorConstant.ACCOUNT_EXCEPTION_STR - + readableOwnerAddress + "] not exists"); + + readableOwnerAddress + NOT_EXIST_STR); } if (dynamicStore.getAllowTvmConstantinople() == 1 diff --git a/actuator/src/main/java/org/tron/core/actuator/MarketCancelOrderActuator.java b/actuator/src/main/java/org/tron/core/actuator/MarketCancelOrderActuator.java index a99d5a7b48d..f859e580253 100644 --- a/actuator/src/main/java/org/tron/core/actuator/MarketCancelOrderActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/MarketCancelOrderActuator.java @@ -15,6 +15,10 @@ package org.tron.core.actuator; +import static org.tron.core.actuator.ActuatorConstant.CONTRACT_NOT_EXIST; +import static org.tron.core.actuator.ActuatorConstant.STORE_NOT_EXIST; +import static org.tron.core.actuator.ActuatorConstant.TX_RESULT_NULL; + import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import java.util.Objects; @@ -77,7 +81,7 @@ public boolean execute(Object object) throws ContractExeException { TransactionResultCapsule ret = (TransactionResultCapsule) object; if (Objects.isNull(ret)) { - throw new RuntimeException("TransactionResultCapsule is null"); + throw new RuntimeException(TX_RESULT_NULL); } long fee = calcFee(); @@ -93,10 +97,14 @@ public boolean execute(Object object) throws ContractExeException { // fee accountCapsule.setBalance(accountCapsule.getBalance() - fee); - Commons.adjustBalance(accountStore, accountStore.getBlackhole().createDbKey(), fee); - + if (dynamicStore.supportBlackHoleOptimization()) { + dynamicStore.burnTrx(fee); + } else { + Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee); + } // 1. return balance and token - MarketUtils.returnSellTokenRemain(orderCapsule, accountCapsule, dynamicStore, assetIssueStore); + MarketUtils + .returnSellTokenRemain(orderCapsule, accountCapsule, dynamicStore, assetIssueStore); MarketUtils.updateOrderState(orderCapsule, State.CANCELED, marketAccountStore); accountStore.put(orderCapsule.getOwnerAddress().toByteArray(), accountCapsule); @@ -145,10 +153,10 @@ public boolean execute(Object object) throws ContractExeException { @Override public boolean validate() throws ContractValidateException { if (this.any == null) { - throw new ContractValidateException("No contract!"); + throw new ContractValidateException(CONTRACT_NOT_EXIST); } if (chainBaseManager == null) { - throw new ContractValidateException("No account store or dynamic store!"); + throw new ContractValidateException(STORE_NOT_EXIST); } initStores(); diff --git a/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java b/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java index 01d8ec40330..15e5a98f86a 100644 --- a/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java @@ -15,6 +15,9 @@ package org.tron.core.actuator; +import static org.tron.core.actuator.ActuatorConstant.CONTRACT_NOT_EXIST; +import static org.tron.core.actuator.ActuatorConstant.STORE_NOT_EXIST; +import static org.tron.core.actuator.ActuatorConstant.TX_RESULT_NULL; import static org.tron.core.capsule.utils.TransactionUtil.isNumber; import com.google.protobuf.ByteString; @@ -46,7 +49,6 @@ import org.tron.core.store.MarketOrderStore; import org.tron.core.store.MarketPairPriceToOrderStore; import org.tron.core.store.MarketPairToPriceStore; -import org.tron.core.utils.TransactionUtil; import org.tron.protos.Protocol.MarketOrder.State; import org.tron.protos.Protocol.MarketOrderDetail; import org.tron.protos.Protocol.MarketPrice; @@ -101,7 +103,7 @@ public boolean execute(Object object) throws ContractExeException { TransactionResultCapsule ret = (TransactionResultCapsule) object; if (Objects.isNull(ret)) { - throw new RuntimeException("TransactionResultCapsule is null"); + throw new RuntimeException(TX_RESULT_NULL); } long fee = calcFee(); @@ -124,8 +126,11 @@ public boolean execute(Object object) throws ContractExeException { // fee accountCapsule.setBalance(accountCapsule.getBalance() - fee); // add to blackhole address - Commons.adjustBalance(accountStore, accountStore.getBlackhole().createDbKey(), fee); - + if (dynamicStore.supportBlackHoleOptimization()) { + dynamicStore.burnTrx(fee); + } else { + Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee); + } // 1. transfer of balance transferBalanceOrToken(accountCapsule); @@ -160,10 +165,10 @@ public boolean execute(Object object) throws ContractExeException { @Override public boolean validate() throws ContractValidateException { if (this.any == null) { - throw new ContractValidateException("No contract!"); + throw new ContractValidateException(CONTRACT_NOT_EXIST); } if (chainBaseManager == null) { - throw new ContractValidateException("No account store or dynamic store!"); + throw new ContractValidateException(STORE_NOT_EXIST); } initStores(); @@ -288,7 +293,7 @@ public long calcFee() { /** * return marketPrice if matched, otherwise null - * */ + */ private MarketPrice hasMatch(List priceKeysList, MarketPrice takerPrice) { if (priceKeysList.isEmpty()) { return null; @@ -310,7 +315,6 @@ private void matchOrder(MarketOrderCapsule takerCapsule, MarketPrice takerPrice, // makerPair not exists long makerPriceNumber = pairToPriceStore.getPriceNum(makerPair); - if (makerPriceNumber == 0) { return; } @@ -319,7 +323,7 @@ private void matchOrder(MarketOrderCapsule takerCapsule, MarketPrice takerPrice, // get maker price list List priceKeysList = pairPriceToOrderStore .getPriceKeysList(MarketUtils.getPairPriceHeadKey(makerSellTokenID, makerBuyTokenID), - (long)(MAX_MATCH_NUM + 1), makerPriceNumber, true); + (long) (MAX_MATCH_NUM + 1), makerPriceNumber, true); int matchOrderCount = 0; // match different price diff --git a/actuator/src/main/java/org/tron/core/actuator/ShieldedTransferActuator.java b/actuator/src/main/java/org/tron/core/actuator/ShieldedTransferActuator.java index 2e64a16185e..8b00126c684 100644 --- a/actuator/src/main/java/org/tron/core/actuator/ShieldedTransferActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/ShieldedTransferActuator.java @@ -76,7 +76,7 @@ public boolean execute(Object result) executeTransparentFrom(shieldedTransferContract.getTransparentFromAddress().toByteArray(), shieldedTransferContract.getFromAmount(), ret, fee); } - Commons.adjustAssetBalanceV2(accountStore.getBlackhole().createDbKey(), + Commons.adjustAssetBalanceV2(accountStore.getBlackhole(), CommonParameter.getInstance().getZenTokenId(), fee, accountStore, assetIssueStore, dynamicStore); } catch (BalanceInsufficientException e) { diff --git a/actuator/src/main/java/org/tron/core/actuator/TransferActuator.java b/actuator/src/main/java/org/tron/core/actuator/TransferActuator.java index 2e87aad7d55..3b9c2ecc3aa 100755 --- a/actuator/src/main/java/org/tron/core/actuator/TransferActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/TransferActuator.java @@ -55,11 +55,15 @@ public boolean execute(Object object) throws ContractExeException { fee = fee + dynamicStore.getCreateNewAccountFeeInSystemContract(); } - Commons.adjustBalance(accountStore, ownerAddress, -fee); - Commons.adjustBalance(accountStore, accountStore.getBlackhole().createDbKey(), fee); - ret.setStatus(fee, code.SUCESS); - Commons.adjustBalance(accountStore, ownerAddress, -amount); + + Commons.adjustBalance(accountStore, ownerAddress, -(Math.addExact(fee, amount))); + if (dynamicStore.supportBlackHoleOptimization()) { + dynamicStore.burnTrx(fee); + } else { + Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee); + } Commons.adjustBalance(accountStore, toAddress, amount); + ret.setStatus(fee, code.SUCESS); } catch (BalanceInsufficientException | ArithmeticException | InvalidProtocolBufferException e) { logger.debug(e.getMessage(), e); ret.setStatus(fee, code.FAILED); diff --git a/actuator/src/main/java/org/tron/core/actuator/TransferAssetActuator.java b/actuator/src/main/java/org/tron/core/actuator/TransferAssetActuator.java index 1c9969becc4..cdc626d5a35 100644 --- a/actuator/src/main/java/org/tron/core/actuator/TransferAssetActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/TransferAssetActuator.java @@ -73,9 +73,6 @@ public boolean execute(Object result) throws ContractExeException { ByteString assetName = transferAssetContract.getAssetName(); long amount = transferAssetContract.getAmount(); - Commons.adjustBalance(accountStore, ownerAddress, -fee); - Commons.adjustBalance(accountStore, accountStore.getBlackhole().createDbKey(), fee); - AccountCapsule ownerAccountCapsule = accountStore.get(ownerAddress); if (!ownerAccountCapsule .reduceAssetAmountV2(assetName.toByteArray(), amount, dynamicStore, assetIssueStore)) { @@ -87,6 +84,12 @@ public boolean execute(Object result) throws ContractExeException { .addAssetAmountV2(assetName.toByteArray(), amount, dynamicStore, assetIssueStore); accountStore.put(toAddress, toAccountCapsule); + Commons.adjustBalance(accountStore, ownerAccountCapsule, -fee); + if (dynamicStore.supportBlackHoleOptimization()) { + dynamicStore.burnTrx(fee); + } else { + Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee); + } ret.setStatus(fee, code.SUCESS); } catch (BalanceInsufficientException e) { logger.debug(e.getMessage(), e); diff --git a/actuator/src/main/java/org/tron/core/actuator/UnfreezeAssetActuator.java b/actuator/src/main/java/org/tron/core/actuator/UnfreezeAssetActuator.java index fde468eccdb..434b9151609 100755 --- a/actuator/src/main/java/org/tron/core/actuator/UnfreezeAssetActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/UnfreezeAssetActuator.java @@ -1,5 +1,7 @@ package org.tron.core.actuator; +import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_STR; + import com.google.common.collect.Lists; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; @@ -112,7 +114,7 @@ public boolean validate() throws ContractValidateException { if (accountCapsule == null) { String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); throw new ContractValidateException( - "Account[" + readableOwnerAddress + "] does not exist"); + ACCOUNT_EXCEPTION_STR + readableOwnerAddress + "] does not exist"); } if (accountCapsule.getFrozenSupplyCount() <= 0) { diff --git a/actuator/src/main/java/org/tron/core/actuator/UnfreezeBalanceActuator.java b/actuator/src/main/java/org/tron/core/actuator/UnfreezeBalanceActuator.java index ef6d38ca7a2..d33e983b5e0 100755 --- a/actuator/src/main/java/org/tron/core/actuator/UnfreezeBalanceActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/UnfreezeBalanceActuator.java @@ -1,5 +1,6 @@ package org.tron.core.actuator; +import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_STR; import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; import com.google.common.collect.Lists; @@ -19,9 +20,9 @@ import org.tron.core.capsule.DelegatedResourceCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.VotesCapsule; -import org.tron.core.db.DelegationService; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; +import org.tron.core.service.MortgageService; import org.tron.core.store.AccountStore; import org.tron.core.store.DelegatedResourceAccountIndexStore; import org.tron.core.store.DelegatedResourceStore; @@ -56,7 +57,7 @@ public boolean execute(Object result) throws ContractExeException { DelegatedResourceAccountIndexStore delegatedResourceAccountIndexStore = chainBaseManager .getDelegatedResourceAccountIndexStore(); VotesStore votesStore = chainBaseManager.getVotesStore(); - DelegationService delegationService = chainBaseManager.getDelegationService(); + MortgageService mortgageService = chainBaseManager.getMortgageService(); try { unfreezeBalanceContract = any.unpack(UnfreezeBalanceContract.class); } catch (InvalidProtocolBufferException e) { @@ -67,7 +68,7 @@ public boolean execute(Object result) throws ContractExeException { byte[] ownerAddress = unfreezeBalanceContract.getOwnerAddress().toByteArray(); // - delegationService.withdrawReward(ownerAddress); + mortgageService.withdrawReward(ownerAddress); AccountCapsule accountCapsule = accountStore.get(ownerAddress); long oldBalance = accountCapsule.getBalance(); @@ -269,7 +270,7 @@ public boolean validate() throws ContractValidateException { if (accountCapsule == null) { String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); throw new ContractValidateException( - "Account[" + readableOwnerAddress + "] does not exist"); + ACCOUNT_EXCEPTION_STR + readableOwnerAddress + "] does not exist"); } long now = dynamicStore.getLatestBlockHeaderTimestamp(); byte[] receiverAddress = unfreezeBalanceContract.getReceiverAddress().toByteArray(); diff --git a/actuator/src/main/java/org/tron/core/actuator/UpdateSettingContractActuator.java b/actuator/src/main/java/org/tron/core/actuator/UpdateSettingContractActuator.java index 9e21e34a46d..f3d2e6f533d 100755 --- a/actuator/src/main/java/org/tron/core/actuator/UpdateSettingContractActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/UpdateSettingContractActuator.java @@ -107,7 +107,7 @@ public boolean validate() throws ContractValidateException { if (!Arrays.equals(ownerAddress, deployedContractOwnerAddress)) { throw new ContractValidateException( - "Account[" + readableOwnerAddress + "] is not the owner of the contract"); + ACCOUNT_EXCEPTION_STR + readableOwnerAddress + "] is not the owner of the contract"); } return true; 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 ab2c35d3add..3ff2d5ac3f2 100644 --- a/actuator/src/main/java/org/tron/core/actuator/VMActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/VMActuator.java @@ -332,10 +332,10 @@ private void create() // create vm to constructor smart contract try { long feeLimit = trx.getRawData().getFeeLimit(); - if (feeLimit < 0 || feeLimit > VMConfig.MAX_FEE_LIMIT) { + if (feeLimit < 0 || feeLimit > repository.getDynamicPropertiesStore().getMaxFeeLimit()) { logger.info("invalid feeLimit {}", feeLimit); throw new ContractValidateException( - "feeLimit must be >= 0 and <= " + VMConfig.MAX_FEE_LIMIT); + "feeLimit must be >= 0 and <= " + repository.getDynamicPropertiesStore().getMaxFeeLimit()); } AccountCapsule creator = this.repository .getAccount(newSmartContract.getOriginAddress().toByteArray()); @@ -459,10 +459,10 @@ private void call() if (isNotEmpty(code)) { long feeLimit = trx.getRawData().getFeeLimit(); - if (feeLimit < 0 || feeLimit > VMConfig.MAX_FEE_LIMIT) { + if (feeLimit < 0 || feeLimit > repository.getDynamicPropertiesStore().getMaxFeeLimit()) { logger.info("invalid feeLimit {}", feeLimit); throw new ContractValidateException( - "feeLimit must be >= 0 and <= " + VMConfig.MAX_FEE_LIMIT); + "feeLimit must be >= 0 and <= " + repository.getDynamicPropertiesStore().getMaxFeeLimit()); } AccountCapsule caller = repository.getAccount(callerAddress); long energyLimit; diff --git a/actuator/src/main/java/org/tron/core/actuator/VoteWitnessActuator.java b/actuator/src/main/java/org/tron/core/actuator/VoteWitnessActuator.java index 0b7ffd7fe31..bf406c72fe7 100755 --- a/actuator/src/main/java/org/tron/core/actuator/VoteWitnessActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/VoteWitnessActuator.java @@ -18,9 +18,9 @@ import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.VotesCapsule; -import org.tron.core.db.DelegationService; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; +import org.tron.core.service.MortgageService; import org.tron.core.store.AccountStore; import org.tron.core.store.VotesStore; import org.tron.core.store.WitnessStore; @@ -145,13 +145,13 @@ public boolean validate() throws ContractValidateException { private void countVoteAccount(VoteWitnessContract voteContract) { AccountStore accountStore = chainBaseManager.getAccountStore(); VotesStore votesStore = chainBaseManager.getVotesStore(); - DelegationService delegationService = chainBaseManager.getDelegationService(); + MortgageService mortgageService = chainBaseManager.getMortgageService(); byte[] ownerAddress = voteContract.getOwnerAddress().toByteArray(); VotesCapsule votesCapsule; // - delegationService.withdrawReward(ownerAddress); + mortgageService.withdrawReward(ownerAddress); AccountCapsule accountCapsule = accountStore.get(ownerAddress); diff --git a/actuator/src/main/java/org/tron/core/actuator/WithdrawBalanceActuator.java b/actuator/src/main/java/org/tron/core/actuator/WithdrawBalanceActuator.java index 4a2e7f7e18d..cea71c9d8ed 100755 --- a/actuator/src/main/java/org/tron/core/actuator/WithdrawBalanceActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/WithdrawBalanceActuator.java @@ -15,9 +15,9 @@ import org.tron.common.utils.StringUtil; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.db.DelegationService; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; +import org.tron.core.service.MortgageService; import org.tron.core.store.AccountStore; import org.tron.core.store.DynamicPropertiesStore; import org.tron.protos.Protocol.Transaction.Contract.ContractType; @@ -42,7 +42,7 @@ public boolean execute(Object result) throws ContractExeException { final WithdrawBalanceContract withdrawBalanceContract; AccountStore accountStore = chainBaseManager.getAccountStore(); DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); - DelegationService delegationService = chainBaseManager.getDelegationService(); + MortgageService mortgageService = chainBaseManager.getMortgageService(); try { withdrawBalanceContract = any.unpack(WithdrawBalanceContract.class); } catch (InvalidProtocolBufferException e) { @@ -51,8 +51,9 @@ public boolean execute(Object result) throws ContractExeException { throw new ContractExeException(e.getMessage()); } - delegationService.withdrawReward(withdrawBalanceContract.getOwnerAddress() + mortgageService.withdrawReward(withdrawBalanceContract.getOwnerAddress() .toByteArray()); + AccountCapsule accountCapsule = accountStore. get(withdrawBalanceContract.getOwnerAddress().toByteArray()); long oldBalance = accountCapsule.getBalance(); @@ -81,7 +82,7 @@ public boolean validate() throws ContractValidateException { } AccountStore accountStore = chainBaseManager.getAccountStore(); DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); - DelegationService delegationService = chainBaseManager.getDelegationService(); + MortgageService mortgageService = chainBaseManager.getMortgageService(); if (!this.any.is(WithdrawBalanceContract.class)) { throw new ContractValidateException( "contract type error, expected type [WithdrawBalanceContract], real type[" + any @@ -127,7 +128,7 @@ public boolean validate() throws ContractValidateException { } if (accountCapsule.getAllowance() <= 0 && - delegationService.queryReward(ownerAddress) <= 0) { + mortgageService.queryReward(ownerAddress) <= 0) { throw new ContractValidateException("witnessAccount does not have any reward"); } try { diff --git a/actuator/src/main/java/org/tron/core/actuator/WitnessCreateActuator.java b/actuator/src/main/java/org/tron/core/actuator/WitnessCreateActuator.java index 0ed047dd689..ee223a32ffa 100755 --- a/actuator/src/main/java/org/tron/core/actuator/WitnessCreateActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/WitnessCreateActuator.java @@ -1,5 +1,7 @@ package org.tron.core.actuator; +import static org.tron.core.actuator.ActuatorConstant.WITNESS_EXCEPTION_STR; + import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import java.util.Objects; @@ -95,7 +97,8 @@ public boolean validate() throws ContractValidateException { } */ if (witnessStore.has(ownerAddress)) { - throw new ContractValidateException("Witness[" + readableOwnerAddress + "] has existed"); + throw new ContractValidateException( + WITNESS_EXCEPTION_STR + readableOwnerAddress + "] has existed"); } if (accountCapsule.getBalance() < dynamicStore @@ -139,9 +142,11 @@ private void createWitness(final WitnessCreateContract witnessCreateContract) long cost = dynamicStore.getAccountUpgradeCost(); Commons .adjustBalance(accountStore, witnessCreateContract.getOwnerAddress().toByteArray(), -cost); - - Commons.adjustBalance(accountStore, accountStore.getBlackhole().createDbKey(), +cost); - + if (dynamicStore.supportBlackHoleOptimization()) { + dynamicStore.burnTrx(cost); + } else { + Commons.adjustBalance(accountStore, accountStore.getBlackhole(), +cost); + } dynamicStore.addTotalCreateWitnessCost(cost); } } 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 5c9c7e92879..0c3537666d3 100644 --- a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java @@ -401,6 +401,40 @@ public static void validator(DynamicPropertiesStore dynamicPropertiesStore, } break; } + case MAX_FEE_LIMIT: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_1_2)) { + throw new ContractValidateException("Bad chain parameter id [MAX_FEE_LIMIT]"); + } + if (value < 0 || value > 10_000_000_000L) { + throw new ContractValidateException( + "Bad MAX_FEE_LIMIT parameter value, valid range is [0,10_000_000_000L]"); + } + break; + } + case ALLOW_TRANSACTION_FEE_POOL: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_1_2)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_TRANSACTION_FEE_POOL]"); + } + if (value != 1 && value != 0) { + throw new ContractValidateException( + "This value[ALLOW_TRANSACTION_FEE_POOL] is only allowed to be 1 or 0"); + } + break; + } + case ALLOW_BLACKHOLE_OPTIMIZATION: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_1_2)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_REMOVE_BLACKHOLE]"); + } + if (value != 1 && value != 0) { + throw new ContractValidateException( + "This value[ALLOW_REMOVE_BLACKHOLE] is only allowed to be 1 or 0"); + } + break; + } + + default: break; } @@ -450,7 +484,10 @@ public enum ProposalType { // current value, value range // ALLOW_TVM_STAKE(43), // 0, 1 ALLOW_MARKET_TRANSACTION(44), // {0, 1} MARKET_SELL_FEE(45), // 0 [0,10_000_000_000] - MARKET_CANCEL_FEE(46); // 0 [0,10_000_000_000] + MARKET_CANCEL_FEE(46), // 0 [0,10_000_000_000] + MAX_FEE_LIMIT(47), // [0, 10_000_000_000] + ALLOW_TRANSACTION_FEE_POOL(48), // 0, 1 + ALLOW_BLACKHOLE_OPTIMIZATION(49);// 0,1 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 51315ee3bcb..cb7c10a1fff 100644 --- a/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java @@ -54,39 +54,39 @@ @Component public class TransactionUtil { - private static final int maxAccountNameLen = 200; - private static final int maxAccountIdLen = 32; - private static final int minAccountIdLen = 8; - private static final int maxAssetNameLen = 32; - private static final int maxTokenAbbrNameLen = 5; - private static final int maxAssetDescriptionLen = 200; - private static final int maxUrlLen = 256; + private static final int MAX_ACCOUNT_NAME_LEN = 200; + private static final int MAX_ACCOUNT_ID_LEN = 32; + private static final int MIN_ACCOUNT_ID_LEN = 8; + private static final int MAX_ASSET_NAME_LEN = 32; + private static final int MAX_TOKEN_ABBR_NAME_LEN = 5; + private static final int MAX_ASSET_DESCRIPTION_LEN = 200; + private static final int MAX_URL_LEN = 256; @Autowired private ChainBaseManager chainBaseManager; public static boolean validAccountName(byte[] accountName) { - return validBytes(accountName, maxAccountNameLen, true); + return validBytes(accountName, MAX_ACCOUNT_NAME_LEN, true); } public static boolean validAssetDescription(byte[] description) { - return validBytes(description, maxAssetDescriptionLen, true); + return validBytes(description, MAX_ASSET_DESCRIPTION_LEN, true); } public static boolean validUrl(byte[] url) { - return validBytes(url, maxUrlLen, false); + return validBytes(url, MAX_URL_LEN, false); } public static boolean validAccountId(byte[] accountId) { - return validReadableBytes(accountId, maxAccountIdLen) && accountId.length >= minAccountIdLen; + return validReadableBytes(accountId, MAX_ACCOUNT_ID_LEN) && accountId.length >= MIN_ACCOUNT_ID_LEN; } public static boolean validAssetName(byte[] assetName) { - return validReadableBytes(assetName, maxAssetNameLen); + return validReadableBytes(assetName, MAX_ASSET_NAME_LEN); } public static boolean validTokenAbbrName(byte[] abbrName) { - return validReadableBytes(abbrName, maxTokenAbbrNameLen); + return validReadableBytes(abbrName, MAX_TOKEN_ABBR_NAME_LEN); } private static boolean validBytes(byte[] bytes, int maxLength, boolean allowEmpty) { diff --git a/actuator/src/main/java/org/tron/core/vm/OpCode.java b/actuator/src/main/java/org/tron/core/vm/OpCode.java index fb1511afd01..954731ecd02 100644 --- a/actuator/src/main/java/org/tron/core/vm/OpCode.java +++ b/actuator/src/main/java/org/tron/core/vm/OpCode.java @@ -585,6 +585,7 @@ public enum OpCode { CALLTOKENID(0xd3, 0, 1, OpCode.Tier.BaseTier), ISCONTRACT(0xd4, 1, 1, OpCode.Tier.ExtTier), + /** * (0xf0) Create a new account with associated code */ 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 f9735e76c6a..1cb38bace74 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 @@ -27,7 +27,8 @@ */ public class VMConfig { - public static final int MAX_FEE_LIMIT = 1_000_000_000; //1000 TRX + //1000 TRX + //public static final int MAX_FEE_LIMIT = 1_000_000_000; private static boolean vmTraceCompressed = false; diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/StakeProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/StakeProcessor.java index a413fb5c5cf..7131526236c 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/StakeProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/StakeProcessor.java @@ -18,6 +18,8 @@ import org.tron.core.vm.repository.Repository; import org.tron.protos.Protocol; +import static org.tron.core.actuator.ActuatorConstant.*; + @Slf4j(topic = "Processor") public class StakeProcessor { @@ -62,7 +64,7 @@ private void selfValidate(StakeParam stakeParam, Repository repository) if (accountCapsule == null) { String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); throw new ContractValidateException( - "Account[" + readableOwnerAddress + "] not exists"); + ACCOUNT_EXCEPTION_STR + readableOwnerAddress + NOT_EXIST_STR); } } 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 ae8e472d0bf..5b9eb6f77e1 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 @@ -1812,17 +1812,14 @@ public void tokenIssue(DataWord name, DataWord abbr, DataWord totalSupply, DataW TokenIssueParam tokenIssueParam = new TokenIssueParam(); tokenIssueParam.setName(name.getNoEndZeroesData()); tokenIssueParam.setAbbr(abbr.getNoEndZeroesData()); + tokenIssueParam.setTotalSupply(totalSupply.sValue().longValueExact()); + tokenIssueParam.setPrecision(precision.sValue().intValueExact()); tokenIssueParam.setOwnerAddress(ownerAddress); try { - tokenIssueParam.setTotalSupply(totalSupply.sValue().longValueExact()); - tokenIssueParam.setPrecision(precision.sValue().intValueExact()); tokenIssueProcessor.validate(tokenIssueParam, repository); tokenIssueProcessor.execute(tokenIssueParam, repository); stackPush(new DataWord(repository.getTokenIdNum())); repository.commit(); - } catch (ArithmeticException e) { - logger.error("totalSupply or precision out of long range"); - stackPushZero(); } catch (ContractValidateException e) { logger.error("validateForAssetIssue failure:{}", e.getMessage()); stackPushZero(); diff --git a/actuator/src/main/java/org/tron/core/vm/repository/RepositoryImpl.java b/actuator/src/main/java/org/tron/core/vm/repository/RepositoryImpl.java index 80653688fc5..e64228bc9aa 100644 --- a/actuator/src/main/java/org/tron/core/vm/repository/RepositoryImpl.java +++ b/actuator/src/main/java/org/tron/core/vm/repository/RepositoryImpl.java @@ -6,7 +6,6 @@ import com.google.protobuf.ByteString; import java.util.HashMap; import java.util.Optional; - import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.spongycastle.util.Strings; @@ -14,16 +13,39 @@ import org.tron.common.crypto.Hash; import org.tron.common.parameter.CommonParameter; import org.tron.common.runtime.vm.DataWord; -import org.tron.common.utils.*; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.ByteUtil; +import org.tron.common.utils.Commons; +import org.tron.common.utils.Sha256Hash; +import org.tron.common.utils.StorageUtils; +import org.tron.common.utils.StringUtil; import org.tron.core.ChainBaseManager; import org.tron.core.capsule.*; import org.tron.core.capsule.BlockCapsule.BlockId; +import org.tron.core.capsule.BytesCapsule; +import org.tron.core.capsule.ContractCapsule; +import org.tron.core.capsule.VotesCapsule; +import org.tron.core.capsule.WitnessCapsule; import org.tron.core.config.Parameter; -import org.tron.core.db.*; +import org.tron.core.db.BlockIndexStore; +import org.tron.core.db.BlockStore; +import org.tron.core.db.KhaosDatabase; +import org.tron.core.db.TransactionTrace; import org.tron.core.exception.BadItemException; import org.tron.core.exception.ItemNotFoundException; import org.tron.core.exception.StoreException; -import org.tron.core.store.*; +import org.tron.core.service.MortgageService; +import org.tron.core.store.AccountStore; +import org.tron.core.store.AssetIssueStore; +import org.tron.core.store.AssetIssueV2Store; +import org.tron.core.store.CodeStore; +import org.tron.core.store.ContractStore; +import org.tron.core.store.DelegationStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.store.StorageRowStore; +import org.tron.core.store.StoreFactory; +import org.tron.core.store.VotesStore; +import org.tron.core.store.WitnessStore; import org.tron.core.vm.config.VMConfig; import org.tron.core.vm.program.Program.IllegalOperationException; import org.tron.core.vm.program.Storage; @@ -36,7 +58,7 @@ public class RepositoryImpl implements Repository { //for energycal private long precision = Parameter.ChainConstant.PRECISION; private long windowSize = Parameter.ChainConstant.WINDOW_SIZE_MS / - BLOCK_PRODUCED_INTERVAL; + BLOCK_PRODUCED_INTERVAL; private static final byte[] TOTAL_NET_WEIGHT = "TOTAL_NET_WEIGHT".getBytes(); private StoreFactory storeFactory; @@ -65,7 +87,7 @@ public class RepositoryImpl implements Repository { @Getter private VotesStore votesStore; @Getter - private DelegationService delegationService; + private MortgageService mortgageService; @Getter private DelegationStore delegationStore; @@ -105,7 +127,7 @@ protected void init(StoreFactory storeFactory, RepositoryImpl parent) { blockIndexStore = manager.getBlockIndexStore(); witnessStore = manager.getWitnessStore(); votesStore = manager.getVotesStore(); - delegationService = manager.getDelegationService(); + mortgageService = manager.getMortgageService(); delegationStore = manager.getDelegationStore(); } this.parent = parent; @@ -219,18 +241,18 @@ public BytesCapsule getDynamic(byte[] word) { @Override public VotesCapsule getVotesCapsule(byte[] address) { Key cacheKey = new Key(address); - if(votesCache.containsKey(cacheKey)) { + if (votesCache.containsKey(cacheKey)) { return votesCache.get(cacheKey).getVotes(); } VotesCapsule votesCapsule; - if(parent != null) { + if (parent != null) { votesCapsule = parent.getVotesCapsule(address); } else { votesCapsule = getVotesStore().get(address); } - if(votesCapsule != null) { + if (votesCapsule != null) { votesCache.put(cacheKey, Value.create(votesCapsule.getData())); } return votesCapsule; @@ -242,14 +264,14 @@ public WitnessCapsule getWitnessCapsule(byte[] address) { } @Override - public long getBeginCycle(byte[] address){ + public long getBeginCycle(byte[] address) { Key cacheKey = new Key(address); BytesCapsule bytesCapsule = getDelegationCache(cacheKey); return bytesCapsule == null ? 0 : ByteArray.toLong(bytesCapsule.getData()); } @Override - public long getEndCycle(byte[] address){ + public long getEndCycle(byte[] address) { byte[] key = ("end-" + Hex.toHexString(address)).getBytes(); Key cacheKey = new Key(key); BytesCapsule bytesCapsule = getDelegationCache(cacheKey); @@ -563,7 +585,7 @@ public void putAccountValue(byte[] address, AccountCapsule accountCapsule) { } @Override - public void putDynamic(Key key, Value value){ + public void putDynamic(Key key, Value value) { dynamicPropertiesCache.put(key, value); } @@ -585,8 +607,8 @@ public void putAssetIssueValue(byte[] tokenId, AssetIssueCapsule assetIssueCapsu } @Override - public void putDelegation(Key key, Value value){ - delegationCache.put(key,value); + public void putDelegation(Key key, Value value) { + delegationCache.put(key, value); } @@ -635,7 +657,7 @@ public long getTokenBalance(byte[] address, byte[] tokenId) { @Override public byte[] getBlackHoleAddress() { - return getAccountStore().getBlackhole().getAddress().toByteArray(); + return getAccountStore().getBlackholeAddress(); } @Override @@ -699,7 +721,7 @@ public long calculateGlobalEnergyLimit(AccountCapsule accountCapsule) { public long getHeadSlot() { return (getDynamicPropertiesStore().getLatestBlockHeaderTimestamp() - Long.parseLong(CommonParameter.getInstance() - .getGenesisBlock().getTimestamp())) + .getGenesisBlock().getTimestamp())) / BLOCK_PRODUCED_INTERVAL; } @@ -766,8 +788,8 @@ private void commitDynamicCache(Repository deposit) { private void commitVotesCache(Repository deposit) { votesCache.forEach(((key, value) -> { - if(value.getType().isDirty() || value.getType().isCreate()) { - if(deposit != null) { + if (value.getType().isDirty() || value.getType().isCreate()) { + if (deposit != null) { deposit.putVotesCapsule(key, value); } else { getVotesStore().put(key.getData(), value.getVotes()); @@ -778,7 +800,7 @@ private void commitVotesCache(Repository deposit) { private void commitAssetIssue(Repository deposit) { AssetIssueStore assetIssueStoreFinal = Commons - .getAssetIssueStoreFinal(dynamicPropertiesStore, assetIssueStore, assetIssueV2Store); + .getAssetIssueStoreFinal(dynamicPropertiesStore, assetIssueStore, assetIssueV2Store); assetIssueCache.forEach((key, value) -> { if (value.getType().isCreate() || value.getType().isDirty()) { @@ -786,7 +808,7 @@ private void commitAssetIssue(Repository deposit) { deposit.putAssetIssue(key, value); } else { assetIssueStoreFinal - .put(key.getData(), value.getAssetIssue()); + .put(key.getData(), value.getAssetIssue()); } } }); @@ -794,8 +816,8 @@ private void commitAssetIssue(Repository deposit) { private void commitDelegationCache(Repository deposit) { delegationCache.forEach((key, value) -> { - if(value.getType().isDirty() || value.getType().isCreate()) { - if(deposit != null) { + if (value.getType().isDirty() || value.getType().isCreate()) { + if (deposit != null) { deposit.putDelegation(key, value); } else { getDelegationStore().put(key.getData(), value.getBytes()); @@ -827,16 +849,16 @@ public AccountCapsule createNormalAccount(byte[] address) { @Override public void saveTokenIdNum(long num) { this.updateDynamic(DynamicPropertiesStore.getTOKEN_ID_NUM(), - new BytesCapsule(ByteArray.fromLong(num))); + new BytesCapsule(ByteArray.fromLong(num))); } @Override public long getTokenIdNum() { return Optional.ofNullable(this.getDynamic(DynamicPropertiesStore.getTOKEN_ID_NUM())) - .map(BytesCapsule::getData) - .map(ByteArray::toLong) - .orElseThrow( - () -> new IllegalArgumentException("error in contract not found TOKEN_ID_NUM")); + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("error in contract not found TOKEN_ID_NUM")); } //The unit is trx @@ -855,9 +877,9 @@ public void saveTotalNetWeight(long totalNetWeight) { @Override public long getTotalNetWeight() { return Optional.ofNullable(getDynamic(TOTAL_NET_WEIGHT)) - .map(BytesCapsule::getData) - .map(ByteArray::toLong) - .orElseThrow( - () -> new IllegalArgumentException("not found TOTAL_NET_WEIGHT")); + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("not found TOTAL_NET_WEIGHT")); } } diff --git a/build.gradle b/build.gradle index 12d78a0c223..0ff89c1723e 100644 --- a/build.gradle +++ b/build.gradle @@ -21,8 +21,8 @@ subprojects { maven { url 'https://jitpack.io' } } dependencies { - classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.3' - classpath 'com.github.jengelman.gradle.plugins:shadow:2.0.2' + classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.12' + classpath 'com.github.jengelman.gradle.plugins:shadow:5.2.0' } } @@ -38,7 +38,10 @@ subprojects { compile group: 'org.slf4j', name: 'jcl-over-slf4j', version: '1.7.25' compile "org.slf4j:jcl-over-slf4j:1.7.25" compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.3' - compile group: 'org.projectlombok', name: 'lombok', version: '1.18.2' + compileOnly 'org.projectlombok:lombok:1.18.12' + 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 "com.google.code.findbugs:jsr305:3.0.0" compile group: 'org.springframework', name: 'spring-context', version: '4.2.4.RELEASE' @@ -55,10 +58,6 @@ subprojects { from sourceSets.main.allSource } - artifacts { -// archives jar - archives sourcesJar - } tasks.withType(AbstractArchiveTask) { preserveFileTimestamps = false 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 ef35df21400..b8e798d1232 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 @@ -387,29 +387,27 @@ public long getTotal() throws RuntimeException { private void updateByBatchInner(Map rows) throws Exception { try (WriteBatch batch = database.createWriteBatch()) { - rows.forEach((key, value) -> { - if (value == null) { - batch.delete(key); - } else { - batch.put(key, value); - } - }); + innerBatchUpdate(rows,batch); database.write(batch, writeOptions); } } private void updateByBatchInner(Map rows, WriteOptions options) throws Exception { try (WriteBatch batch = database.createWriteBatch()) { - rows.forEach((key, value) -> { - if (value == null) { - batch.delete(key); - } else { - batch.put(key, value); - } - }); + innerBatchUpdate(rows,batch); database.write(batch, options); } } + + private void innerBatchUpdate(Map rows, WriteBatch batch) { + rows.forEach((key, value) -> { + if (value == null) { + batch.delete(key); + } else { + batch.put(key, value); + } + }); + } @Override public void updateByBatch(Map rows, WriteOptionsWrapper options) { diff --git a/chainbase/src/main/java/org/tron/common/utils/Commons.java b/chainbase/src/main/java/org/tron/common/utils/Commons.java index 0dc7ea4fee2..f2f7578d200 100644 --- a/chainbase/src/main/java/org/tron/common/utils/Commons.java +++ b/chainbase/src/main/java/org/tron/common/utils/Commons.java @@ -18,7 +18,7 @@ public class Commons { public static final int ASSET_ISSUE_COUNT_LIMIT_MAX = 1000; - private static byte[] decode58Check(String input) { + public static byte[] decode58Check(String input) { byte[] decodeCheck = Base58.decode(input); if (decodeCheck.length <= 4) { return null; diff --git a/chainbase/src/main/java/org/tron/common/utils/WalletUtil.java b/chainbase/src/main/java/org/tron/common/utils/WalletUtil.java index 3c9d7b0ee79..bd367393405 100644 --- a/chainbase/src/main/java/org/tron/common/utils/WalletUtil.java +++ b/chainbase/src/main/java/org/tron/common/utils/WalletUtil.java @@ -102,7 +102,8 @@ public static boolean isConstant(SmartContract.ABI abi, byte[] selector) { System.arraycopy(Hash.sha3(sb.toString().getBytes()), 0, funcSelector, 0, 4); if (Arrays.equals(funcSelector, selector)) { if (entry.getConstant() || entry.getStateMutability() - .equals(StateMutabilityType.View)) { + .equals(StateMutabilityType.View) || entry.getStateMutability() + .equals(StateMutabilityType.Pure)) { return true; } else { return false; diff --git a/chainbase/src/main/java/org/tron/common/zksnark/JLibrustzcash.java b/chainbase/src/main/java/org/tron/common/zksnark/JLibrustzcash.java index 5dbaf55dfa4..f7b8c17b57f 100644 --- a/chainbase/src/main/java/org/tron/common/zksnark/JLibrustzcash.java +++ b/chainbase/src/main/java/org/tron/common/zksnark/JLibrustzcash.java @@ -84,11 +84,10 @@ public static boolean librustzcashComputeCm(ComputeCmParams params) { } public static boolean librustzcashComputeNf(ComputeNfParams params) { - if (!isOpenZen()) { - return true; + if (isOpenZen()) { + INSTANCE.librustzcashSaplingComputeNf(params.getD(), params.getPkD(), params.getValue(), + params.getR(), params.getAk(), params.getNk(), params.getPosition(), params.getResult()); } - INSTANCE.librustzcashSaplingComputeNf(params.getD(), params.getPkD(), params.getValue(), - params.getR(), params.getAk(), params.getNk(), params.getPosition(), params.getResult()); return true; } diff --git a/chainbase/src/main/java/org/tron/core/ChainBaseManager.java b/chainbase/src/main/java/org/tron/core/ChainBaseManager.java index 06d2ca520f6..011b9800a5a 100644 --- a/chainbase/src/main/java/org/tron/core/ChainBaseManager.java +++ b/chainbase/src/main/java/org/tron/core/ChainBaseManager.java @@ -21,7 +21,6 @@ import org.tron.core.db.BlockStore; import org.tron.core.db.CommonDataBase; import org.tron.core.db.CommonStore; -import org.tron.core.db.DelegationService; import org.tron.core.db.KhaosDatabase; import org.tron.core.db.PbftSignDataStore; import org.tron.core.db.RecentBlockStore; @@ -30,11 +29,14 @@ import org.tron.core.exception.BadItemException; import org.tron.core.exception.HeaderNotFound; import org.tron.core.exception.ItemNotFoundException; +import org.tron.core.service.MortgageService; import org.tron.core.store.AccountIdIndexStore; import org.tron.core.store.AccountIndexStore; import org.tron.core.store.AccountStore; +import org.tron.core.store.AccountTraceStore; import org.tron.core.store.AssetIssueStore; import org.tron.core.store.AssetIssueV2Store; +import org.tron.core.store.BalanceTraceStore; import org.tron.core.store.CodeStore; import org.tron.core.store.ContractStore; import org.tron.core.store.DelegatedResourceAccountIndexStore; @@ -150,7 +152,7 @@ public class ChainBaseManager { @Getter @Setter - private DelegationService delegationService; + private MortgageService mortgageService; @Autowired @Getter @@ -189,6 +191,14 @@ public class ChainBaseManager { @Getter private PbftSignDataStore pbftSignDataStore; + @Autowired + @Getter + private BalanceTraceStore balanceTraceStore; + + @Autowired + @Getter + private AccountTraceStore accountTraceStore; + @Getter private ForkController forkController = ForkController.instance(); diff --git a/chainbase/src/main/java/org/tron/core/capsule/AccountTraceCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/AccountTraceCapsule.java new file mode 100644 index 00000000000..2437540644f --- /dev/null +++ b/chainbase/src/main/java/org/tron/core/capsule/AccountTraceCapsule.java @@ -0,0 +1,57 @@ +package org.tron.core.capsule; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.util.List; +import java.util.Objects; +import org.tron.common.utils.StringUtil; +import org.tron.core.exception.BadItemException; +import org.tron.protos.contract.BalanceContract; +import org.tron.protos.contract.BalanceContract.AccountTrace; +import org.tron.protos.contract.BalanceContract.TransactionBalanceTrace; + +public class AccountTraceCapsule implements ProtoCapsule { + private BalanceContract.AccountTrace accountTrace; + + public AccountTraceCapsule() { + accountTrace = AccountTrace.newBuilder().build(); + } + + public AccountTraceCapsule(long balance) { + this(); + accountTrace = accountTrace.toBuilder().setBalance(balance).build(); + } + + public AccountTraceCapsule(AccountTrace accountTrace) { + this.accountTrace = accountTrace; + } + + public AccountTraceCapsule(byte[] data) throws BadItemException { + try { + this.accountTrace = AccountTrace.parseFrom(data); + } catch (InvalidProtocolBufferException e) { + throw new BadItemException("AccountTraceCapsule proto data parse exception"); + } + } + + public Long getBalance() { + return accountTrace.getBalance(); + } + + @Override + public byte[] getData() { + if (Objects.isNull(accountTrace)) { + return null; + } + + if (accountTrace.getBalance() == 0) { + accountTrace = accountTrace.toBuilder().setPlaceholder(1).build(); + } + + return accountTrace.toByteArray(); + } + + @Override + public AccountTrace getInstance() { + return accountTrace; + } +} diff --git a/chainbase/src/main/java/org/tron/core/capsule/BlockBalanceTraceCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/BlockBalanceTraceCapsule.java new file mode 100644 index 00000000000..870b2e7018b --- /dev/null +++ b/chainbase/src/main/java/org/tron/core/capsule/BlockBalanceTraceCapsule.java @@ -0,0 +1,88 @@ +package org.tron.core.capsule; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.util.List; +import java.util.Map; +import org.tron.common.utils.StringUtil; +import org.tron.core.exception.BadItemException; +import org.tron.protos.contract.BalanceContract; +import org.tron.protos.contract.BalanceContract.BlockBalanceTrace; +import org.tron.protos.contract.BalanceContract.TransactionBalanceTrace; + +import java.util.Objects; + +public class BlockBalanceTraceCapsule implements ProtoCapsule { + private BlockBalanceTrace balanceTrace; + + public BlockBalanceTraceCapsule() { + balanceTrace = BlockBalanceTrace.newBuilder().build(); + } + + public BlockBalanceTraceCapsule(BlockCapsule blockCapsule) { + this(); + BlockBalanceTrace.BlockIdentifier blockIdentifier = BlockBalanceTrace.BlockIdentifier.newBuilder() + .setHash(blockCapsule.getBlockId().getByteString()) + .setNumber(blockCapsule.getNum()) + .build(); + + balanceTrace = balanceTrace.toBuilder() + .setBlockIdentifier(blockIdentifier) + .setTimestamp(blockCapsule.getTimeStamp()) + .build(); + } + + public BlockBalanceTraceCapsule(byte[] data) throws BadItemException { + try { + this.balanceTrace = BlockBalanceTrace.parseFrom(data); + } catch (InvalidProtocolBufferException e) { + throw new BadItemException("TransactionInfoCapsule proto data parse exception"); + } + } + + public BlockBalanceTraceCapsule(BlockBalanceTrace blockBalanceTrace) { + this.balanceTrace = blockBalanceTrace; + } + + public void addTransactionBalanceTrace(TransactionBalanceTrace transactionBalanceTrace) { + balanceTrace = balanceTrace.toBuilder() + .addTransactionBalanceTrace(transactionBalanceTrace) + .build(); + } + + public void setTransactionBalanceTrace(int index, TransactionBalanceTrace transactionBalanceTrace) { + balanceTrace = balanceTrace.toBuilder() + .setTransactionBalanceTrace(index, transactionBalanceTrace) + .build(); + } + +// public void setParentBlockIdentifier(BlockBalanceTrace.BlockIdentifier blockIdentifier) { +// balanceTrace = balanceTrace.toBuilder() +// .setParentBlockIdentifier(blockIdentifier) +// .build(); +// } + + @Override + public byte[] getData() { + if (Objects.isNull(balanceTrace)) { + return null; + } + return balanceTrace.toByteArray(); + } + + @Override + public BlockBalanceTrace getInstance() { + return balanceTrace; + } + + public BlockBalanceTrace.BlockIdentifier getBlockIdentifier() { + return balanceTrace.getBlockIdentifier(); + } + + public long getTimestamp() { + return balanceTrace.getTimestamp(); + } + + public List getTransactions() { + return balanceTrace.getTransactionBalanceTraceList(); + } +} diff --git a/chainbase/src/main/java/org/tron/core/capsule/BlockCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/BlockCapsule.java index b9bfd9c7162..cfb218f7164 100755 --- a/chainbase/src/main/java/org/tron/core/capsule/BlockCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/BlockCapsule.java @@ -233,7 +233,7 @@ public void setAccountStateRoot(byte[] root) { this.block.getBlockHeader().toBuilder().setRawData(blockHeaderRaw)).build(); } - /* only for genisis */ + /* only for genesis */ public void setWitness(String witness) { BlockHeader.raw blockHeaderRaw = this.block.getBlockHeader().getRawData().toBuilder().setWitnessAddress( 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 f8c175e0cd7..38f2d72c378 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/ReceiptCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/ReceiptCapsule.java @@ -124,13 +124,13 @@ public void payEnergyBill(DynamicPropertiesStore dynamicPropertiesStore, if (Objects.isNull(origin) && dynamicPropertiesStore.getAllowTvmConstantinople() == 1) { payEnergyBill(dynamicPropertiesStore, accountStore, forkController, caller, - receipt.getEnergyUsageTotal(), energyProcessor, now); + receipt.getEnergyUsageTotal(), receipt.getResult(), energyProcessor, now); return; } if (caller.getAddress().equals(origin.getAddress())) { payEnergyBill(dynamicPropertiesStore, accountStore, forkController, caller, - receipt.getEnergyUsageTotal(), energyProcessor, now); + receipt.getEnergyUsageTotal(), receipt.getResult(), energyProcessor, now); } else { long originUsage = Math.multiplyExact(receipt.getEnergyUsageTotal(), percent) / 100; originUsage = getOriginUsage(dynamicPropertiesStore, origin, originEnergyLimit, @@ -141,7 +141,7 @@ public void payEnergyBill(DynamicPropertiesStore dynamicPropertiesStore, energyProcessor.useEnergy(origin, originUsage, now); this.setOriginEnergyUsage(originUsage); payEnergyBill(dynamicPropertiesStore, accountStore, forkController, - caller, callerUsage, energyProcessor, now); + caller, callerUsage, receipt.getResult(), energyProcessor, now); } } @@ -161,6 +161,7 @@ private void payEnergyBill( ForkController forkController, AccountCapsule account, long usage, + contractResult contractResult, EnergyProcessor energyProcessor, long now) throws BalanceInsufficientException { long accountEnergyLeft = energyProcessor.getAccountLeftEnergyFromFreeze(account); @@ -193,9 +194,17 @@ private void payEnergyBill( } account.setBalance(balance - energyFee); - //send to blackHole - Commons.adjustBalance(accountStore, accountStore.getBlackhole().getAddress().toByteArray(), - energyFee); + if (dynamicPropertiesStore.supportTransactionFeePool() && + !contractResult.equals(contractResult.OUT_OF_TIME)) { + dynamicPropertiesStore.addTransactionFeePool(energyFee); + } else if (dynamicPropertiesStore.supportBlackHoleOptimization()) { + dynamicPropertiesStore.burnTrx(energyFee); + } else { + //send to blackHole + Commons.adjustBalance(accountStore, accountStore.getBlackhole(), + energyFee); + } + } accountStore.put(account.getAddress().toByteArray(), account); 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 353fbb61dc2..a389af23044 100755 --- a/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java @@ -70,6 +70,7 @@ 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.BalanceContract; import org.tron.protos.contract.BalanceContract.TransferContract; import org.tron.protos.contract.ShieldContract.ShieldedTransferContract; import org.tron.protos.contract.ShieldContract.SpendDescription; @@ -447,15 +448,7 @@ public static boolean validateSignature(Transaction transaction, if (permission == null) { throw new PermissionException("permission isn't exit"); } - if (permissionId != 0) { - if (permission.getType() != PermissionType.Active) { - throw new PermissionException("Permission type is error"); - } - //check oprations - if (!checkPermissionOperations(permission, contract)) { - throw new PermissionException("Permission denied"); - } - } + checkPermission(permissionId, permission, contract); long weight = checkWeight(permission, transaction.getSignatureList(), hash, null); if (weight >= permission.getThreshold()) { return true; @@ -503,6 +496,13 @@ public void setTimestamp() { this.transaction = this.transaction.toBuilder().setRawData(rawData).build(); } + public void setTimestamp(long timestamp) { + Transaction.raw rawData = this.transaction.getRawData().toBuilder() + .setTimestamp(timestamp) + .build(); + this.transaction = this.transaction.toBuilder().setRawData(rawData).build(); + } + public long getTimestamp() { return transaction.getRawData().getTimestamp(); } @@ -549,15 +549,7 @@ public void addSign(byte[] privateKey, AccountStore accountStore) if (permission == null) { throw new PermissionException("permission isn't exit"); } - if (permissionId != 0) { - if (permission.getType() != PermissionType.Active) { - throw new PermissionException("Permission type is error"); - } - //check oprations - if (!checkPermissionOperations(permission, contract)) { - throw new PermissionException("Permission denied"); - } - } + checkPermission(permissionId, permission, contract); List approveList = new ArrayList<>(); SignInterface cryptoEngine = SignUtils .fromPrivate(privateKey, CommonParameter.getInstance().isECKeyCryptoEngine()); @@ -581,6 +573,18 @@ public void addSign(byte[] privateKey, AccountStore accountStore) .signHash(getRawHash().getBytes()))); this.transaction = this.transaction.toBuilder().addSignature(sig).build(); } + + private static void checkPermission(int permissionId, Permission permission, Transaction.Contract contract) throws PermissionException { + if (permissionId != 0) { + if (permission.getType() != PermissionType.Active) { + throw new PermissionException("Permission type is error"); + } + //check operations + if (!checkPermissionOperations(permission, contract)) { + throw new PermissionException("Permission denied"); + } + } + } /** * validate signature @@ -588,30 +592,29 @@ public void addSign(byte[] privateKey, AccountStore accountStore) public boolean validatePubSignature(AccountStore accountStore, DynamicPropertiesStore dynamicPropertiesStore) throws ValidateSignatureException { - if (isVerified) { - return true; - } - if (this.transaction.getSignatureCount() <= 0 - || this.transaction.getRawData().getContractCount() <= 0) { - throw new ValidateSignatureException("miss sig or contract"); - } - if (this.transaction.getSignatureCount() > dynamicPropertiesStore - .getTotalSignNum()) { - throw new ValidateSignatureException("too many signatures"); - } + if (!isVerified) { + if (this.transaction.getSignatureCount() <= 0 + || this.transaction.getRawData().getContractCount() <= 0) { + throw new ValidateSignatureException("miss sig or contract"); + } + if (this.transaction.getSignatureCount() > dynamicPropertiesStore + .getTotalSignNum()) { + throw new ValidateSignatureException("too many signatures"); + } - byte[] hash = this.getRawHash().getBytes(); + byte[] hash = this.getRawHash().getBytes(); - try { - if (!validateSignature(this.transaction, hash, accountStore, dynamicPropertiesStore)) { + try { + if (!validateSignature(this.transaction, hash, accountStore, dynamicPropertiesStore)) { + isVerified = false; + throw new ValidateSignatureException("sig error"); + } + } catch (SignatureException | PermissionException | SignatureFormatException e) { isVerified = false; - throw new ValidateSignatureException("sig error"); + throw new ValidateSignatureException(e.getMessage()); } - } catch (SignatureException | PermissionException | SignatureFormatException e) { - isVerified = false; - throw new ValidateSignatureException(e.getMessage()); + isVerified = true; } - isVerified = true; return true; } @@ -620,26 +623,24 @@ public boolean validatePubSignature(AccountStore accountStore, */ public boolean validateSignature(AccountStore accountStore, DynamicPropertiesStore dynamicPropertiesStore) throws ValidateSignatureException { - if (isVerified) { - return true; - } - //Do not support multi contracts in one transaction - Transaction.Contract contract = this.getInstance().getRawData().getContract(0); - if (contract.getType() != ContractType.ShieldedTransferContract) { - validatePubSignature(accountStore, dynamicPropertiesStore); - } else { //ShieldedTransfer - byte[] owner = getOwner(contract); - if (!ArrayUtils.isEmpty(owner)) { //transfer from transparent address + if (!isVerified) { + //Do not support multi contracts in one transaction + Transaction.Contract contract = this.getInstance().getRawData().getContract(0); + if (contract.getType() != ContractType.ShieldedTransferContract) { validatePubSignature(accountStore, dynamicPropertiesStore); - } else { //transfer from shielded address - if (this.transaction.getSignatureCount() > 0) { - throw new ValidateSignatureException("there should be no signatures signed by " - + "transparent address when transfer from shielded address"); + } else { //ShieldedTransfer + byte[] owner = getOwner(contract); + if (!ArrayUtils.isEmpty(owner)) { //transfer from transparent address + validatePubSignature(accountStore, dynamicPropertiesStore); + } else { //transfer from shielded address + if (this.transaction.getSignatureCount() > 0) { + throw new ValidateSignatureException("there should be no signatures signed by " + + "transparent address when transfer from shielded address"); + } } } - } - - isVerified = true; + isVerified = true; + } return true; } @@ -766,4 +767,15 @@ public boolean isContractType() { return false; } } + + public BalanceContract.TransferContract getTransferContract() { + try { + return transaction.getRawData() + .getContract(0) + .getParameter() + .unpack(BalanceContract.TransferContract.class); + } catch (InvalidProtocolBufferException e) { + return null; + } + } } diff --git a/chainbase/src/main/java/org/tron/core/capsule/TransactionInfoCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/TransactionInfoCapsule.java index f07c28bb8d4..e7fb1f7be59 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/TransactionInfoCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/TransactionInfoCapsule.java @@ -33,6 +33,11 @@ public TransactionInfoCapsule() { this.transactionInfo = TransactionInfo.newBuilder().build(); } + + public long getPackingFee() { + return transactionInfo.getPackingFee(); + } + public long getFee() { return transactionInfo.getFee(); } 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 6a558ec2261..ef92853404d 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 @@ -75,6 +75,20 @@ public static TransactionInfoCapsule buildTransactionInfoInstance(TransactionCap long fee = programResult.getRet().getFee() + traceReceipt.getEnergyFee() + traceReceipt.getNetFee() + traceReceipt.getMultiSignFee(); + + boolean supportTransactionFeePool = trace.getTransactionContext().getStoreFactory() + .getChainBaseManager().getDynamicPropertiesStore().supportTransactionFeePool(); + if (supportTransactionFeePool) { + long packingFee = 0L; + if (trace.isNetFeeForBandwidth()) { + packingFee += traceReceipt.getNetFee(); + } + if (!traceReceipt.getResult().equals(Transaction.Result.contractResult.OUT_OF_TIME)) { + packingFee += traceReceipt.getEnergyFee(); + } + builder.setPackingFee(packingFee); + } + ByteString contractResult = ByteString.copyFrom(programResult.getHReturn()); ByteString ContractAddress = ByteString.copyFrom(programResult.getContractAddress()); diff --git a/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java b/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java index 2676383052a..9c9c968aa73 100644 --- a/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java +++ b/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java @@ -153,8 +153,8 @@ public boolean pop() { } public void setMaxSize(int maxSize) { - miniUnlinkedStore.setMaxCapcity(maxSize); - miniStore.setMaxCapcity(maxSize); + miniUnlinkedStore.setMaxCapacity(maxSize); + miniStore.setMaxCapacity(maxSize); } /** @@ -197,7 +197,7 @@ public Pair, LinkedList> getBranch(Sha256Hash return new Pair<>(list1, list2); } - + private void checkNull(Object o) throws NonCommonBlockException { if (o == null) { throw new NonCommonBlockException(); @@ -235,7 +235,7 @@ public Pair, LinkedList> getBranch( return new Pair<>(list1, list2); } - // only for unittest + // only for unit test public BlockCapsule getParentBlock(Sha256Hash hash) { return Stream.of(miniStore.getByHash(hash), miniUnlinkedStore.getByHash(hash)) .filter(Objects::nonNull) @@ -335,7 +335,7 @@ protected boolean removeEldestEntry(Map.Entry> entry } }; - public synchronized void setMaxCapcity(int maxCapacity) { + public synchronized void setMaxCapacity(int maxCapacity) { this.maxCapacity = maxCapacity; } 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 44894e721b8..09bac96e0ae 100644 --- a/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java +++ b/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java @@ -67,12 +67,37 @@ private long getUsage(long usage, long windowSize) { return usage * windowSize / precision; } - protected boolean consumeFee(AccountCapsule accountCapsule, long fee) { + protected boolean consumeFeeForBandwidth(AccountCapsule accountCapsule, long fee) { try { long latestOperationTime = dynamicPropertiesStore.getLatestBlockHeaderTimestamp(); accountCapsule.setLatestOperationTime(latestOperationTime); Commons.adjustBalance(accountStore, accountCapsule, -fee); - Commons.adjustBalance(accountStore, accountStore.getBlackhole().createDbKey(), +fee); + if (dynamicPropertiesStore.supportTransactionFeePool()) { + dynamicPropertiesStore.addTransactionFeePool(fee); + } else if (dynamicPropertiesStore.supportBlackHoleOptimization()) { + dynamicPropertiesStore.burnTrx(fee); + } else { + Commons.adjustBalance(accountStore, accountStore.getBlackhole().createDbKey(), +fee); + } + + return true; + } catch (BalanceInsufficientException e) { + return false; + } + } + + + protected boolean consumeFeeForNewAccount(AccountCapsule accountCapsule, long fee) { + try { + long latestOperationTime = dynamicPropertiesStore.getLatestBlockHeaderTimestamp(); + accountCapsule.setLatestOperationTime(latestOperationTime); + Commons.adjustBalance(accountStore, accountCapsule, -fee); + if (dynamicPropertiesStore.supportBlackHoleOptimization()) { + dynamicPropertiesStore.burnTrx(fee); + } else { + Commons.adjustBalance(accountStore, accountStore.getBlackhole().createDbKey(), +fee); + } + return true; } catch (BalanceInsufficientException e) { return false; diff --git a/chainbase/src/main/java/org/tron/core/db/StorageMarket.java b/chainbase/src/main/java/org/tron/core/db/StorageMarket.java index 229adfdb9a8..6fe6ee2ee1f 100644 --- a/chainbase/src/main/java/org/tron/core/db/StorageMarket.java +++ b/chainbase/src/main/java/org/tron/core/db/StorageMarket.java @@ -22,7 +22,7 @@ public StorageMarket(AccountStore accountStore, DynamicPropertiesStore dynamicPr this.dynamicPropertiesStore = dynamicPropertiesStore; } - private long exchange_to_supply(boolean isTRX, long quant) { + private long exchangeToSupply(boolean isTRX, long quant) { logger.info("isTRX: " + isTRX); long balance = isTRX ? dynamicPropertiesStore.getTotalStoragePool() : dynamicPropertiesStore.getTotalStorageReserved(); @@ -44,7 +44,7 @@ private long exchange_to_supply(boolean isTRX, long quant) { return out; } - private long exchange_to_supply2(boolean isTRX, long quant) { + private long exchangeToSupply2(boolean isTRX, long quant) { logger.info("isTRX: " + isTRX); long balance = isTRX ? dynamicPropertiesStore.getTotalStoragePool() : dynamicPropertiesStore.getTotalStorageReserved(); @@ -85,7 +85,7 @@ private long exchange_from_supply(boolean isTRX, long supplyQuant) { } public long exchange(long from, boolean isTRX) { - long relay = exchange_to_supply(isTRX, from); + long relay = exchangeToSupply(isTRX, from); return exchange_from_supply(!isTRX, relay); } @@ -142,7 +142,7 @@ public long payTax(long duration, long limit) { } public long tryBuyStorageBytes(long storageBought) { - long relay = exchange_to_supply2(false, storageBought); + long relay = exchangeToSupply2(false, storageBought); return exchange_from_supply(true, relay); } @@ -158,7 +158,7 @@ public AccountCapsule buyStorageBytes(AccountCapsule accountCapsule, long storag long now = dynamicPropertiesStore.getLatestBlockHeaderTimestamp(); long currentStorageLimit = accountCapsule.getStorageLimit(); - long relay = exchange_to_supply2(false, storageBought); + long relay = exchangeToSupply2(false, storageBought); long quant = exchange_from_supply(true, relay); long newBalance = accountCapsule.getBalance() - quant; 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 c33f98a16df..984b06c1e76 100644 --- a/chainbase/src/main/java/org/tron/core/db/TransactionTrace.java +++ b/chainbase/src/main/java/org/tron/core/db/TransactionTrace.java @@ -73,6 +73,9 @@ public class TransactionTrace { @Getter @Setter private TimeResultType timeResultType = TimeResultType.NORMAL; + @Getter + @Setter + private boolean netFeeForBandwidth = true; public TransactionTrace(TransactionCapsule trx, StoreFactory storeFactory, Runtime runtime) { @@ -162,6 +165,12 @@ public void setNetBill(long netUsage, long netFee) { receipt.setNetFee(netFee); } + public void setNetBillForCreateNewAccount(long netUsage, long netFee) { + receipt.setNetUsage(netUsage); + receipt.setNetFee(netFee); + setNetFeeForBandwidth(false); + } + public void addNetBill(long netFee) { receipt.addNetFee(netFee); } diff --git a/framework/src/main/java/org/tron/core/db2/common/ConcurrentHashDB.java b/chainbase/src/main/java/org/tron/core/db2/common/ConcurrentHashDB.java similarity index 100% rename from framework/src/main/java/org/tron/core/db2/common/ConcurrentHashDB.java rename to chainbase/src/main/java/org/tron/core/db2/common/ConcurrentHashDB.java diff --git a/chainbase/src/main/java/org/tron/core/db2/common/HashDB.java b/chainbase/src/main/java/org/tron/core/db2/common/HashDB.java index 950effbe3d7..87612f1d81f 100644 --- a/chainbase/src/main/java/org/tron/core/db2/common/HashDB.java +++ b/chainbase/src/main/java/org/tron/core/db2/common/HashDB.java @@ -3,10 +3,11 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; public class HashDB implements DB { - private Map db = new HashMap<>(); + private Map db = new ConcurrentHashMap<>(); private String name; public HashDB(String name) { diff --git a/chainbase/src/main/java/org/tron/core/db2/common/IRevokingDB.java b/chainbase/src/main/java/org/tron/core/db2/common/IRevokingDB.java index 97663639973..c39d0782720 100644 --- a/chainbase/src/main/java/org/tron/core/db2/common/IRevokingDB.java +++ b/chainbase/src/main/java/org/tron/core/db2/common/IRevokingDB.java @@ -1,5 +1,6 @@ package org.tron.core.db2.common; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; @@ -34,4 +35,8 @@ public interface IRevokingDB extends Iterable> { List getKeysNext(byte[] key, long limit); + default Map getNext(byte[] key, long limit) { + return Collections.emptyMap(); + } + } diff --git a/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java b/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java index ca1f51cc7a5..c2d8068ed0d 100644 --- a/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java +++ b/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java @@ -226,8 +226,7 @@ private List getKeysNext(Snapshot head, byte[] key, long limit) { } // just get the same token pair - List levelDBListFiltered = new ArrayList<>(); - levelDBListFiltered = levelDBList.stream() + List levelDBListFiltered = levelDBList.stream() .filter(e -> MarketUtils.pairKeyIsEqual(e.getBytes(), key)) .collect(Collectors.toList()); @@ -288,4 +287,45 @@ private synchronized Set getlatestValues(Snapshot head, long limit) { return result; } + + // for accout-trace + @Override + public Map getNext(byte[] key, long limit) { + return getNext(head(), key, limit); + } + + // for accout-trace + private Map getNext(Snapshot head, byte[] key, long limit) { + if (limit <= 0) { + return Collections.emptyMap(); + } + + Map collection = new HashMap<>(); + if (head.getPrevious() != null) { + ((SnapshotImpl) head).collect(collection); + } + + Map levelDBMap = new HashMap<>(); + + if (((SnapshotRoot) head.getRoot()).db.getClass() == LevelDB.class) { + ((LevelDB) ((SnapshotRoot) head.getRoot()).db).getDb().getNext(key, limit).entrySet().stream() + .map(e -> Maps + .immutableEntry(WrappedByteArray.of(e.getKey()), WrappedByteArray.of(e.getValue()))) + .forEach(e -> levelDBMap.put(e.getKey(), e.getValue())); + } else if (((SnapshotRoot) head.getRoot()).db.getClass() == RocksDB.class) { + ((RocksDB) ((SnapshotRoot) head.getRoot()).db).getDb().getNext(key, limit).entrySet().stream() + .map(e -> Maps + .immutableEntry(WrappedByteArray.of(e.getKey()), WrappedByteArray.of(e.getValue()))) + .forEach(e -> levelDBMap.put(e.getKey(), e.getValue())); + } + + levelDBMap.putAll(collection); + + return levelDBMap.entrySet().stream() + .map(e -> Maps.immutableEntry(e.getKey().getBytes(), e.getValue().getBytes())) + .sorted((e1, e2) -> ByteUtil.compare(e1.getKey(), e2.getKey())) + .filter(e -> ByteUtil.greaterOrEquals(e.getKey(), key)) + .limit(limit) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + } } diff --git a/chainbase/src/main/java/org/tron/core/db2/core/SnapshotImpl.java b/chainbase/src/main/java/org/tron/core/db2/core/SnapshotImpl.java index 403a0ad988d..fb3d028a6be 100644 --- a/chainbase/src/main/java/org/tron/core/db2/core/SnapshotImpl.java +++ b/chainbase/src/main/java/org/tron/core/db2/core/SnapshotImpl.java @@ -23,12 +23,13 @@ public class SnapshotImpl extends AbstractSnapshot { protected Snapshot root; SnapshotImpl(Snapshot snapshot) { - root = snapshot.getRoot(); - previous = snapshot; - snapshot.setNext(this); synchronized (this) { db = new HashDB(SnapshotImpl.class.getSimpleName()); } + + root = snapshot.getRoot(); + previous = snapshot; + snapshot.setNext(this); } @Override diff --git a/chainbase/src/main/java/org/tron/core/db/DelegationService.java b/chainbase/src/main/java/org/tron/core/service/MortgageService.java similarity index 96% rename from chainbase/src/main/java/org/tron/core/db/DelegationService.java rename to chainbase/src/main/java/org/tron/core/service/MortgageService.java index a0445e247f8..4146f8162ff 100644 --- a/chainbase/src/main/java/org/tron/core/db/DelegationService.java +++ b/chainbase/src/main/java/org/tron/core/service/MortgageService.java @@ -1,4 +1,4 @@ -package org.tron.core.db; +package org.tron.core.service; import com.google.protobuf.ByteString; import java.util.ArrayList; @@ -21,9 +21,9 @@ import org.tron.core.store.WitnessStore; import org.tron.protos.Protocol.Vote; -@Slf4j(topic = "delegation") +@Slf4j(topic = "mortgage") @Component -public class DelegationService { +public class MortgageService { @Setter private WitnessStore witnessStore; @@ -77,6 +77,11 @@ public void payBlockReward(byte[] witnessAddress, long value) { payReward(witnessAddress, value); } + public void payTransactionFeeReward(byte[] witnessAddress, long value) { + logger.debug("pay {} transaction fee reward {}", Hex.toHexString(witnessAddress), value); + payReward(witnessAddress, value); + } + private void payReward(byte[] witnessAddress, long value) { long cycle = dynamicPropertiesStore.getCurrentCycleNumber(); int brokerage = delegationStore.getBrokerage(cycle, witnessAddress); diff --git a/chainbase/src/main/java/org/tron/core/store/AccountStore.java b/chainbase/src/main/java/org/tron/core/store/AccountStore.java index 2cf9e8d0372..afe4379b93b 100644 --- a/chainbase/src/main/java/org/tron/core/store/AccountStore.java +++ b/chainbase/src/main/java/org/tron/core/store/AccountStore.java @@ -1,18 +1,25 @@ package org.tron.core.store; +import com.google.protobuf.ByteString; import com.typesafe.config.ConfigObject; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.OptionalLong; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ArrayUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; +import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.Commons; import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.BlockCapsule; import org.tron.core.db.TronStoreWithRevoking; import org.tron.core.db.accountstate.AccountStateCallBackUtils; +import org.tron.protos.contract.BalanceContract; +import org.tron.protos.contract.BalanceContract.TransactionBalanceTrace; +import org.tron.protos.contract.BalanceContract.TransactionBalanceTrace.Operation; @Slf4j(topic = "DB") @Component @@ -23,6 +30,12 @@ public class AccountStore extends TronStoreWithRevoking { @Autowired private AccountStateCallBackUtils accountStateCallBackUtils; + @Autowired + private BalanceTraceStore balanceTraceStore; + + @Autowired + private AccountTraceStore accountTraceStore; + @Autowired private AccountStore(@Value("account") String dbName) { super(dbName); @@ -46,10 +59,45 @@ public AccountCapsule get(byte[] key) { @Override public void put(byte[] key, AccountCapsule item) { + if (CommonParameter.getInstance().isHistoryBalanceLookup()) { + AccountCapsule old = super.getUnchecked(key); + if (old == null) { + if (item.getBalance() != 0) { + recordBalance(item, item.getBalance()); + BlockCapsule.BlockId blockId = balanceTraceStore.getCurrentBlockId(); + if (blockId != null) { + accountTraceStore.recordBalanceWithBlock(key, blockId.getNum(), item.getBalance()); + } + } + } else if (old.getBalance() != item.getBalance()) { + recordBalance(item, item.getBalance() - old.getBalance()); + BlockCapsule.BlockId blockId = balanceTraceStore.getCurrentBlockId(); + if (blockId != null) { + accountTraceStore.recordBalanceWithBlock(key, blockId.getNum(), item.getBalance()); + } + } + } + super.put(key, item); accountStateCallBackUtils.accountCallBack(key, item); } + @Override + public void delete(byte[] key) { + if (CommonParameter.getInstance().isHistoryBalanceLookup()) { + AccountCapsule old = super.getUnchecked(key); + if (old != null) { + recordBalance(old, -old.getBalance()); + } + + BlockCapsule.BlockId blockId = balanceTraceStore.getCurrentBlockId(); + if (blockId != null) { + accountTraceStore.recordBalanceWithBlock(key, blockId.getNum(), 0); + } + } + super.delete(key); + } + /** * Max TRX account. */ @@ -64,6 +112,11 @@ public AccountCapsule getBlackhole() { return getUnchecked(assertsAddress.get("Blackhole")); } + + public byte[] getBlackholeAddress() { + return assertsAddress.get("Blackhole"); + } + /** * Get foundation account info. */ @@ -71,6 +124,38 @@ public AccountCapsule getZion() { return getUnchecked(assertsAddress.get("Zion")); } + + // do somethings + // check old balance and new balance, if equals, do nothing, then get balance trace from balancetraceStore + private void recordBalance(AccountCapsule accountCapsule, long diff) { + TransactionBalanceTrace transactionBalanceTrace = balanceTraceStore.getCurrentTransactionBalanceTrace(); + + if (transactionBalanceTrace == null) { + return; + } + + long operationIdentifier; + OptionalLong max = transactionBalanceTrace.getOperationList().stream() + .mapToLong(Operation::getOperationIdentifier) + .max(); + if (max.isPresent()) { + operationIdentifier = max.getAsLong() + 1; + } else { + operationIdentifier = 0; + } + + ByteString address = accountCapsule.getAddress(); + Operation operation = Operation.newBuilder() + .setAddress(address) + .setAmount(diff) + .setOperationIdentifier(operationIdentifier) + .build(); + transactionBalanceTrace = transactionBalanceTrace.toBuilder() + .addOperation(operation) + .build(); + balanceTraceStore.setCurrentTransactionBalanceTrace(transactionBalanceTrace); + } + @Override public void close() { super.close(); diff --git a/chainbase/src/main/java/org/tron/core/store/AccountTraceStore.java b/chainbase/src/main/java/org/tron/core/store/AccountTraceStore.java new file mode 100644 index 00000000000..ed8f45980d6 --- /dev/null +++ b/chainbase/src/main/java/org/tron/core/store/AccountTraceStore.java @@ -0,0 +1,84 @@ +package org.tron.core.store; + +import com.google.common.primitives.Bytes; +import com.google.common.primitives.Longs; +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.OptionalLong; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.spongycastle.pqc.math.linearalgebra.ByteUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.Sha256Hash; +import org.tron.common.utils.StringUtil; +import org.tron.core.capsule.AccountTraceCapsule; +import org.tron.core.capsule.BlockBalanceTraceCapsule; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.db.TronStoreWithRevoking; +import org.tron.core.exception.BadItemException; +import org.tron.protos.contract.BalanceContract; +import org.tron.protos.contract.BalanceContract.TransactionBalanceTrace; + + +@Component +@Slf4j(topic = "DB") +public class AccountTraceStore extends TronStoreWithRevoking { + + @Autowired + protected AccountTraceStore(@Value("account-trace") String dbName) { + super(dbName); + } + + private long xor(long l) { + return l ^ Long.MAX_VALUE; + } + + public void recordBalanceWithBlock(byte[] address, long number, long balance) { +// Pair pair = getPrevBalance(address, number); +// logger.info("recordBalanceWithBlock===== address:{} number:{} balance:{}", StringUtil.encode58Check(address), number, balance); + byte[] key = Bytes.concat(address, Longs.toByteArray(xor(number))); + put(key, new AccountTraceCapsule(balance)); + } + + public Pair getPrevBalance(byte[] address, long number) { + byte[] key = Bytes.concat(address, Longs.toByteArray(xor(number))); + Map result = revokingDB.getNext(key, 1); + + if (MapUtils.isEmpty(result)) { + return Pair.of(number, 0L); + } + + Map.Entry entry = new ArrayList<>(result.entrySet()).get(0); + byte[] resultAddress = Arrays.copyOf(entry.getKey(), 21); + if (!Arrays.equals(address, resultAddress)) { + return Pair.of(number, 0L); + } + + try { + byte[] numberbytes = Arrays.copyOfRange(entry.getKey(), 21, 29); + return Pair.of(xor(Longs.fromByteArray(numberbytes)), new AccountTraceCapsule(entry.getValue()).getBalance()); + } catch (BadItemException e) { + return Pair.of(number, 0L); + } + } + +} diff --git a/chainbase/src/main/java/org/tron/core/store/BalanceTraceStore.java b/chainbase/src/main/java/org/tron/core/store/BalanceTraceStore.java new file mode 100644 index 00000000000..45e6cc8bb9d --- /dev/null +++ b/chainbase/src/main/java/org/tron/core/store/BalanceTraceStore.java @@ -0,0 +1,178 @@ +package org.tron.core.store; + +import com.google.common.primitives.Bytes; +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.capsule.BlockBalanceTraceCapsule; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.db.TronStoreWithRevoking; +import org.tron.core.exception.BadItemException; +import org.tron.protos.contract.BalanceContract; +import org.tron.protos.contract.BalanceContract.TransactionBalanceTrace; + +import java.util.Objects; + + +@Component +@Slf4j(topic = "DB") +public class BalanceTraceStore extends TronStoreWithRevoking { + + @Getter + private BlockCapsule.BlockId currentBlockId; + + @Getter + private Sha256Hash currentTransactionId; + + @Getter + @Setter + private BlockBalanceTraceCapsule currentBlockBalanceTraceCapsule; + + @Getter + @Setter + private TransactionBalanceTrace currentTransactionBalanceTrace; + + @Autowired + protected BalanceTraceStore(@Value("balance-trace") String dbName) { + super(dbName); + } + + public void setCurrentTransactionId(TransactionCapsule transactionCapsule) { + if (currentBlockId == null) { + return; + } + currentTransactionId = transactionCapsule.getTransactionId(); + } + + public void setCurrentBlockId(BlockCapsule blockCapsule) { + currentBlockId = blockCapsule.getBlockId(); + } + + public void resetCurrentTransactionTrace() { + if (!CommonParameter.getInstance().isHistoryBalanceLookup()) { + return; + } + + if (currentBlockId == null) { + return; + } + + if (!CollectionUtils.isEmpty(currentTransactionBalanceTrace.getOperationList())) { + currentBlockBalanceTraceCapsule.addTransactionBalanceTrace(currentTransactionBalanceTrace); + } + + currentTransactionId = null; + currentTransactionBalanceTrace = null; + } + + public void resetCurrentBlockTrace() { + if (CommonParameter.getInstance().isHistoryBalanceLookup()) { + putBlockBalanceTrace(currentBlockBalanceTraceCapsule); + currentBlockId = null; + currentBlockBalanceTraceCapsule = null; + } + } + + public void initCurrentBlockBalanceTrace(BlockCapsule blockCapsule) { + if (CommonParameter.getInstance().isHistoryBalanceLookup()) { + setCurrentBlockId(blockCapsule); + currentBlockBalanceTraceCapsule = new BlockBalanceTraceCapsule(blockCapsule); + } + } + + public void initCurrentTransactionBalanceTrace(TransactionCapsule transactionCapsule) { + if (!CommonParameter.getInstance().isHistoryBalanceLookup()) { + return; + } + + if (currentBlockId == null) { + return; + } + + setCurrentTransactionId(transactionCapsule); + currentTransactionBalanceTrace = TransactionBalanceTrace.newBuilder() + .setTransactionIdentifier(transactionCapsule.getTransactionId().getByteString()) + .setType(transactionCapsule.getInstance().getRawData().getContract(0).getType().name()) + .build(); + } + + public void updateCurrentTransactionStatus(String status) { + if (!CommonParameter.getInstance().isHistoryBalanceLookup()) { + return; + } + if (currentBlockId == null) { + return; + } + + currentTransactionBalanceTrace = currentTransactionBalanceTrace.toBuilder() + .setStatus(StringUtils.isEmpty(status) ? "SUCCESS" : status) + .build(); + } + + private void putBlockBalanceTrace(BlockBalanceTraceCapsule blockBalanceTrace) { + byte[] key = ByteArray.fromLong(getCurrentBlockId().getNum()); + put(key, blockBalanceTrace); + } + + public BlockBalanceTraceCapsule getBlockBalanceTrace(BlockCapsule.BlockId blockId) throws BadItemException { + long blockNumber = blockId.getNum(); + if (blockNumber == -1) { + return null; + } + + byte[] key = ByteArray.fromLong(blockNumber); + byte[] value = revokingDB.getUnchecked(key); + if (Objects.isNull(value)) { + return null; + } + + BlockBalanceTraceCapsule blockBalanceTraceCapsule = new BlockBalanceTraceCapsule(value); + if (Objects.isNull(blockBalanceTraceCapsule.getInstance())) { + return null; + } + + return blockBalanceTraceCapsule; + } + + public TransactionBalanceTrace getTransactionBalanceTrace(BlockCapsule.BlockId blockId, Sha256Hash transactionId) throws BadItemException { + long blockNumber = blockId.getNum(); + if (blockNumber == -1) { + return null; + } + + byte[] key = ByteArray.fromLong(blockNumber); + byte[] value = revokingDB.getUnchecked(key); + if (Objects.isNull(value)) { + return null; + } + + BlockBalanceTraceCapsule blockBalanceTraceCapsule = new BlockBalanceTraceCapsule(value); + if (Objects.isNull(blockBalanceTraceCapsule.getInstance())) { + return null; + } + + for (TransactionBalanceTrace transactionBalanceTrace : blockBalanceTraceCapsule.getInstance().getTransactionBalanceTraceList()) { + if (transactionBalanceTrace.getTransactionIdentifier().equals(transactionId.getByteString())) { + return transactionBalanceTrace; + } + } + + return null; + } +} 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 226f1c3c60d..b077f108295 100644 --- a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java +++ b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java @@ -4,7 +4,6 @@ import java.util.Arrays; import java.util.Optional; import java.util.stream.IntStream; - import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.joda.time.DateTime; @@ -18,7 +17,6 @@ import org.tron.core.config.Parameter; import org.tron.core.config.Parameter.ChainConstant; import org.tron.core.db.TronStoreWithRevoking; -import org.tron.protos.contract.Common; @Slf4j(topic = "DB") @Component @@ -143,13 +141,19 @@ public class DynamicPropertiesStore extends TronStoreWithRevoking private static final byte[] CURRENT_CYCLE_NUMBER = "CURRENT_CYCLE_NUMBER".getBytes(); private static final byte[] CHANGE_DELEGATION = "CHANGE_DELEGATION".getBytes(); private static final byte[] ALLOW_PBFT = "ALLOW_PBFT".getBytes(); -// private static final byte[] CURRENT_CYCLE_TIMESTAMP = "CURRENT_CYCLE_TIMESTAMP".getBytes(); to be delete v4.1 private static final byte[] ALLOW_MARKET_TRANSACTION = "ALLOW_MARKET_TRANSACTION".getBytes(); private static final byte[] MARKET_SELL_FEE = "MARKET_SELL_FEE".getBytes(); private static final byte[] MARKET_CANCEL_FEE = "MARKET_CANCEL_FEE".getBytes(); private static final byte[] MARKET_QUANTITY_LIMIT = "MARKET_QUANTITY_LIMIT".getBytes(); + private static final byte[] ALLOW_TRANSACTION_FEE_POOL = "ALLOW_TRANSACTION_FEE_POOL".getBytes(); + private static final byte[] TRANSACTION_FEE_POOL = "TRANSACTION_FEE_POOL".getBytes(); + + private static final byte[] MAX_FEE_LIMIT = "MAX_FEE_LIMIT".getBytes(); + private static final byte[] BURN_TRX_AMOUNT = "BURN_TRX_AMOUNT".getBytes(); + private static final byte[] ALLOW_BLACKHOLE_OPTIMIZATION = "ALLOW_BLACKHOLE_OPTIMIZATION".getBytes(); + @Autowired private DynamicPropertiesStore(@Value("properties") String dbName) { super(dbName); @@ -463,6 +467,18 @@ private DynamicPropertiesStore(@Value("properties") String dbName) { this.saveMarketQuantityLimit(1_000_000_000_000_000L); } + try { + this.getAllowTransactionFeePool(); + } catch (IllegalArgumentException e) { + this.saveAllowTransactionFeePool(CommonParameter.getInstance().getAllowTransactionFeePool()); + } + + try { + this.getTransactionFeePool(); + } catch (IllegalArgumentException e) { + this.saveTransactionFeePool(0L); + } + try { this.getTotalTransactionCost(); } catch (IllegalArgumentException e) { @@ -606,14 +622,14 @@ private DynamicPropertiesStore(@Value("properties") String dbName) { this.getAllowTvmStake(); } catch (IllegalArgumentException e) { this.saveAllowTvmStake( - CommonParameter.getInstance().getAllowTvmStake()); + CommonParameter.getInstance().getAllowTvmStake()); } try { this.getAllowTvmAssetIssue(); } catch (IllegalArgumentException e) { this.saveAllowTvmAssetIssue( - CommonParameter.getInstance().getAllowTvmAssetIssue()); + CommonParameter.getInstance().getAllowTvmAssetIssue()); } try { @@ -695,6 +711,24 @@ private DynamicPropertiesStore(@Value("properties") String dbName) { this.saveAllowPBFT(CommonParameter.getInstance().getAllowPBFT()); } + try { + this.getMaxFeeLimit(); + } catch (IllegalArgumentException e) { + this.saveMaxFeeLimit(1_000_000_000L); + } + + try { + this.getBurnTrxAmount(); + } catch (IllegalArgumentException e) { + this.saveBurnTrx(0L); + } + + try { + this.getAllowBlackHoleOptimization(); + } catch (IllegalArgumentException e) { + this.saveAllowBlackHoleOptimization(CommonParameter.getInstance().getAllowBlackHoleOptimization()); + } + } public String intArrayToString(int[] a) { @@ -1373,6 +1407,45 @@ public long getMarketQuantityLimit() { () -> new IllegalArgumentException("not found MARKET_QUANTITY_LIMIT")); } + + public boolean supportTransactionFeePool() { + return getAllowTransactionFeePool() == 1L; + } + + public void saveAllowTransactionFeePool(long value) { + this.put(ALLOW_TRANSACTION_FEE_POOL, + new BytesCapsule(ByteArray.fromLong(value))); + } + + public long getAllowTransactionFeePool() { + return Optional.ofNullable(getUnchecked(ALLOW_TRANSACTION_FEE_POOL)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("not found ALLOW_TRANSACTION_FEE_POOL")); + } + + public void addTransactionFeePool(long amount) { + if (amount <= 0) { + return; + } + amount += getTransactionFeePool(); + saveTransactionFeePool(amount); + } + + public void saveTransactionFeePool(long value) { + this.put(TRANSACTION_FEE_POOL, + new BytesCapsule(ByteArray.fromLong(value))); + } + + public long getTransactionFeePool() { + return Optional.ofNullable(getUnchecked(TRANSACTION_FEE_POOL)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("not found TRANSACTION_FEE_POOL")); + } + public void saveTotalTransactionCost(long value) { this.put(TOTAL_TRANSACTION_COST, new BytesCapsule(ByteArray.fromLong(value))); @@ -1713,30 +1786,30 @@ public long getAllowTvmIstanbul() { public void saveAllowTvmStake(long allowTvmStake) { this.put(DynamicPropertiesStore.ALLOW_TVM_STAKE, - new BytesCapsule(ByteArray.fromLong(allowTvmStake))); + new BytesCapsule(ByteArray.fromLong(allowTvmStake))); } public void saveAllowTvmAssetIssue(long allowTvmAssetIssue) { this.put(DynamicPropertiesStore.ALLOW_TVM_ASSET_ISSUE, - new BytesCapsule(ByteArray.fromLong(allowTvmAssetIssue))); + new BytesCapsule(ByteArray.fromLong(allowTvmAssetIssue))); } public long getAllowTvmStake() { String msg = "not found ALLOW_TVM_STAKE"; return Optional.ofNullable(getUnchecked(ALLOW_TVM_STAKE)) - .map(BytesCapsule::getData) - .map(ByteArray::toLong) - .orElseThrow( - () -> new IllegalArgumentException(msg)); + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException(msg)); } public long getAllowTvmAssetIssue() { String msg = "not found ALLOW_TVM_ASSETISSUE"; return Optional.ofNullable(getUnchecked(ALLOW_TVM_ASSET_ISSUE)) - .map(BytesCapsule::getData) - .map(ByteArray::toLong) - .orElseThrow( - () -> new IllegalArgumentException(msg)); + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException(msg)); } public boolean supportShieldedTransaction() { @@ -2046,6 +2119,54 @@ public boolean allowPBFT() { return getAllowPBFT() == 1; } + public long getMaxFeeLimit() { + return Optional.ofNullable(getUnchecked(MAX_FEE_LIMIT)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("not found MAX_FEE_LIMIT")); + } + + public void saveMaxFeeLimit(long maxFeeLimit) { + this.put(MAX_FEE_LIMIT, + new BytesCapsule(ByteArray.fromLong(maxFeeLimit))); + } + + public long getBurnTrxAmount() { + return Optional.ofNullable(getUnchecked(BURN_TRX_AMOUNT)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow(() -> new IllegalArgumentException("not found BURN_TRX_AMOUNT")); + } + + public void burnTrx(long amount) { + if (amount <= 0) { + return; + } + amount += getBurnTrxAmount(); + saveBurnTrx(amount); + } + + private void saveBurnTrx(long amount) { + this.put(BURN_TRX_AMOUNT, new BytesCapsule(ByteArray.fromLong(amount))); + } + + public boolean supportBlackHoleOptimization() { + return getAllowBlackHoleOptimization() == 1L; + } + + public void saveAllowBlackHoleOptimization(long value) { + this.put(ALLOW_BLACKHOLE_OPTIMIZATION, new BytesCapsule(ByteArray.fromLong(value))); + } + + public long getAllowBlackHoleOptimization() { + return Optional.ofNullable(getUnchecked(ALLOW_BLACKHOLE_OPTIMIZATION)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("not found ALLOW_BLACKHOLE_OPTIMIZATION")); + } + private static class DynamicResourceProperties { private static final byte[] ONE_DAY_NET_LIMIT = "ONE_DAY_NET_LIMIT".getBytes(); 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 0ab934e4719..5b6203a24dd 100644 --- a/common/src/main/java/org/tron/common/parameter/CommonParameter.java +++ b/common/src/main/java/org/tron/common/parameter/CommonParameter.java @@ -138,6 +138,9 @@ public class CommonParameter { public boolean nodeDiscoveryPublicHomeNode; @Getter @Setter + public long nodeDiscoveryPingTimeout; + @Getter + @Setter public long nodeP2pPingInterval; @Getter @Setter @@ -297,6 +300,18 @@ public class CommonParameter { @Getter @Setter public long allowMarketTransaction; //committee parameter + + @Getter + @Setter + public long allowTransactionFeePool; + + @Getter + @Setter + public long allowBlackHoleOptimization; + + // @Getter + // @Setter + // public long allowShieldedTransaction; //committee parameter // full node used this parameter to close shielded transaction @Getter @Setter @@ -441,6 +456,11 @@ public class CommonParameter { @Setter public boolean isLiteFullNode = false; + @Getter + @Setter + @Parameter(names = {"--history-balance-lookup"}) + public boolean historyBalanceLookup = false; + 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/setting/RocksDbSettings.java b/common/src/main/java/org/tron/common/setting/RocksDbSettings.java index d391400fa90..a53d4927ed4 100644 --- a/common/src/main/java/org/tron/common/setting/RocksDbSettings.java +++ b/common/src/main/java/org/tron/common/setting/RocksDbSettings.java @@ -45,10 +45,7 @@ public static RocksDbSettings getDefaultSettings() { } public static RocksDbSettings getSettings() { - if (rocksDbSettings == null) { - return getDefaultSettings(); - } - return rocksDbSettings; + return rocksDbSettings == null ? getDefaultSettings() : rocksDbSettings; } public static RocksDbSettings initCustomSettings(int levelNumber, int compactThreads, diff --git a/common/src/main/java/org/tron/core/Constant.java b/common/src/main/java/org/tron/core/Constant.java index 57190233df8..b7dbd333404 100644 --- a/common/src/main/java/org/tron/core/Constant.java +++ b/common/src/main/java/org/tron/core/Constant.java @@ -8,8 +8,6 @@ public class Constant { //config for junit test public static final String TEST_CONF = "config-test.conf"; - public static final String DATABASE_DIR = "storage.directory"; - // locate in storageDbDirectory, store the db infos, // now only has the split block number public static final String INFO_FILE_NAME = "info.properties"; @@ -25,6 +23,7 @@ public class Constant { public static final long TRANSACTION_MAX_BYTE_SIZE = 500 * 1_024L; public static final long MAXIMUM_TIME_UNTIL_EXPIRATION = 24 * 60 * 60 * 1_000L; //one day public static final long TRANSACTION_DEFAULT_EXPIRATION_TIME = 60 * 1_000L; //60 seconds + public static final long TRANSACTION_FEE_POOL_PERIOD = 1; //1 blocks // config for smart contract public static final long SUN_PER_ENERGY = 100; // 1 us = 100 SUN = 100 * 10^-6 TRX public static final long ENERGY_LIMIT_IN_CONSTANT_TX = 3_000_000L; // ref: 1 us = 1 energy @@ -83,6 +82,7 @@ public class Constant { public static final String NODE_MIN_PARTICIPATION_RATE = "node.minParticipationRate"; public static final String NODE_LISTEN_PORT = "node.listen.port"; public static final String NODE_DISCOVERY_PUBLIC_HOME_NODE = "node.discovery.public.home.node"; + public static final String NODE_DISCOVERY_PING_TIMEOUT = "node.discovery.ping.timeout"; public static final String NODE_P2P_PING_INTERVAL = "node.p2p.pingInterval"; public static final String NODE_P2P_VERSION = "node.p2p.version"; @@ -263,9 +263,16 @@ public class Constant { public static final String COMMITTEE_ALLOW_TVM_ASSETISSUE = "committee.allowTvmAssetIssue"; + public static final String COMMITTEE_ALLOW_TRANSACTION_FEE_POOL = "committee.allowTransactionFeePool"; + public static final String COMMITTEE_ALLOW_BLACK_HOLE_OPTIMIZATION = "committee.allowBlackHoleOptimization"; + public static final String METRICS_STORAGE_ENABLE = "node.metrics.storageEnable"; public static final String METRICS_INFLUXDB_IP = "node.metrics.influxdb.ip"; public static final String METRICS_INFLUXDB_PORT = "node.metrics.influxdb.port"; public static final String METRICS_INFLUXDB_DATABASE = "node.metrics.influxdb.database"; public static final String METRICS_REPORT_INTERVAL = "node.metrics.influxdb.metricsReportInterval"; + + public static final String HISTORY_BALANCE_LOOKUP = "storage.balance.history.lookup"; + + public static final String LOCAL_HOST = "127.0.0.1"; } 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 d38c6a5a8e4..8f8f27c7744 100644 --- a/common/src/main/java/org/tron/core/config/Parameter.java +++ b/common/src/main/java/org/tron/core/config/Parameter.java @@ -13,7 +13,8 @@ public enum ForkBlockVersionEnum { VERSION_3_6_6(10, 0L, 0), VERSION_4_0(16, 0L, 0), VERSION_4_0_1(17, 1596780000000L, 80),//GMT 2020-08-07 06:00:00,80 means 22 SR upgrade - VERSION_4_1(19, 1596780000000L, 80);//GMT 2020-08-07 06:00:00,80 means 22 SR upgrade + VERSION_4_1(19, 1596780000000L, 80),//GMT 2020-08-07 06:00:00,80 means 22 SR upgrade + VERSION_4_1_2(20, 1596780000000L, 80); @Getter private int value; @@ -61,7 +62,7 @@ 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 = 19; + public static final int BLOCK_VERSION = 20; public static final long FROZEN_PERIOD = 86_400_000L; public static final long TRX_PRECISION = 1000_000L; } diff --git a/framework/src/main/java/org/tron/core/exception/BadBlockException.java b/common/src/main/java/org/tron/core/exception/BadBlockException.java similarity index 100% rename from framework/src/main/java/org/tron/core/exception/BadBlockException.java rename to common/src/main/java/org/tron/core/exception/BadBlockException.java diff --git a/framework/src/main/java/org/tron/core/exception/BadTransactionException.java b/common/src/main/java/org/tron/core/exception/BadTransactionException.java similarity index 100% rename from framework/src/main/java/org/tron/core/exception/BadTransactionException.java rename to common/src/main/java/org/tron/core/exception/BadTransactionException.java diff --git a/framework/src/main/java/org/tron/core/exception/CancelException.java b/common/src/main/java/org/tron/core/exception/CancelException.java similarity index 100% rename from framework/src/main/java/org/tron/core/exception/CancelException.java rename to common/src/main/java/org/tron/core/exception/CancelException.java diff --git a/framework/src/main/java/org/tron/keystore/CipherException.java b/common/src/main/java/org/tron/core/exception/CipherException.java similarity index 90% rename from framework/src/main/java/org/tron/keystore/CipherException.java rename to common/src/main/java/org/tron/core/exception/CipherException.java index 6645e78f5d4..06349a9bf21 100644 --- a/framework/src/main/java/org/tron/keystore/CipherException.java +++ b/common/src/main/java/org/tron/core/exception/CipherException.java @@ -1,4 +1,4 @@ -package org.tron.keystore; +package org.tron.core.exception; /** * Cipher exception wrapper. diff --git a/framework/src/main/java/org/tron/core/exception/ContractSizeNotEqualToOneException.java b/common/src/main/java/org/tron/core/exception/ContractSizeNotEqualToOneException.java similarity index 100% rename from framework/src/main/java/org/tron/core/exception/ContractSizeNotEqualToOneException.java rename to common/src/main/java/org/tron/core/exception/ContractSizeNotEqualToOneException.java diff --git a/framework/src/main/java/org/tron/core/exception/DupTransactionException.java b/common/src/main/java/org/tron/core/exception/DupTransactionException.java similarity index 100% rename from framework/src/main/java/org/tron/core/exception/DupTransactionException.java rename to common/src/main/java/org/tron/core/exception/DupTransactionException.java diff --git a/framework/src/main/java/org/tron/core/exception/HighFreqException.java b/common/src/main/java/org/tron/core/exception/HighFreqException.java similarity index 100% rename from framework/src/main/java/org/tron/core/exception/HighFreqException.java rename to common/src/main/java/org/tron/core/exception/HighFreqException.java diff --git a/framework/src/main/java/org/tron/core/exception/NonUniqueObjectException.java b/common/src/main/java/org/tron/core/exception/NonUniqueObjectException.java similarity index 100% rename from framework/src/main/java/org/tron/core/exception/NonUniqueObjectException.java rename to common/src/main/java/org/tron/core/exception/NonUniqueObjectException.java diff --git a/framework/src/main/java/org/tron/core/exception/TaposException.java b/common/src/main/java/org/tron/core/exception/TaposException.java similarity index 100% rename from framework/src/main/java/org/tron/core/exception/TaposException.java rename to common/src/main/java/org/tron/core/exception/TaposException.java diff --git a/framework/src/main/java/org/tron/core/exception/TooBigTransactionException.java b/common/src/main/java/org/tron/core/exception/TooBigTransactionException.java similarity index 100% rename from framework/src/main/java/org/tron/core/exception/TooBigTransactionException.java rename to common/src/main/java/org/tron/core/exception/TooBigTransactionException.java diff --git a/framework/src/main/java/org/tron/core/exception/TraitorPeerException.java b/common/src/main/java/org/tron/core/exception/TraitorPeerException.java similarity index 100% rename from framework/src/main/java/org/tron/core/exception/TraitorPeerException.java rename to common/src/main/java/org/tron/core/exception/TraitorPeerException.java diff --git a/framework/src/main/java/org/tron/core/exception/TransactionExpirationException.java b/common/src/main/java/org/tron/core/exception/TransactionExpirationException.java similarity index 100% rename from framework/src/main/java/org/tron/core/exception/TransactionExpirationException.java rename to common/src/main/java/org/tron/core/exception/TransactionExpirationException.java diff --git a/framework/src/main/java/org/tron/core/exception/TronRuntimeException.java b/common/src/main/java/org/tron/core/exception/TronRuntimeException.java similarity index 100% rename from framework/src/main/java/org/tron/core/exception/TronRuntimeException.java rename to common/src/main/java/org/tron/core/exception/TronRuntimeException.java diff --git a/framework/src/main/java/org/tron/core/exception/UnReachBlockException.java b/common/src/main/java/org/tron/core/exception/UnReachBlockException.java similarity index 100% rename from framework/src/main/java/org/tron/core/exception/UnReachBlockException.java rename to common/src/main/java/org/tron/core/exception/UnReachBlockException.java diff --git a/framework/src/main/java/org/tron/core/exception/ValidateScheduleException.java b/common/src/main/java/org/tron/core/exception/ValidateScheduleException.java similarity index 100% rename from framework/src/main/java/org/tron/core/exception/ValidateScheduleException.java rename to common/src/main/java/org/tron/core/exception/ValidateScheduleException.java diff --git a/consensus/src/main/java/org/tron/consensus/pbft/message/PbftMessage.java b/consensus/src/main/java/org/tron/consensus/pbft/message/PbftMessage.java index d157c1f8335..b6de49ee878 100644 --- a/consensus/src/main/java/org/tron/consensus/pbft/message/PbftMessage.java +++ b/consensus/src/main/java/org/tron/consensus/pbft/message/PbftMessage.java @@ -5,6 +5,7 @@ import org.tron.common.crypto.ECKey; import org.tron.common.crypto.ECKey.ECDSASignature; import org.tron.common.utils.Sha256Hash; +import org.tron.consensus.base.Param; import org.tron.consensus.base.Param.Miner; import org.tron.core.capsule.BlockCapsule; import org.tron.core.net.message.MessageTypes; diff --git a/framework/build.gradle b/framework/build.gradle index ccc01e7f16a..90f7770c624 100644 --- a/framework/build.gradle +++ b/framework/build.gradle @@ -4,7 +4,6 @@ plugins { apply plugin: 'application' apply plugin: 'checkstyle' -apply plugin: 'com.github.johnrengelman.shadow' mainClassName = 'org.tron.program.FullNode' @@ -131,12 +130,6 @@ run { } } -shadowJar { - baseName = 'java-tron' - classifier = null - version = null -} - test { testLogging { exceptionFormat = 'full' @@ -213,6 +206,8 @@ def binaryRelease(taskName, jarName, mainClass) { manifest { attributes "Main-Class": "${mainClass}" } + +// classifier(jarName) } } @@ -262,12 +257,15 @@ createScript(project, 'org.tron.program.KeystoreFactory', 'KeystoreFactory') createScript(project, 'org.tron.program.DBConvert', 'DBConvert') createScript(project, 'org.tron.tool.litefullnode.LiteFullNodeTool', 'LiteFullNodeTool') -artifacts { - archives(binaryRelease('buildSolidityNodeJar', 'SolidityNode', 'org.tron.program.SolidityNode'), - binaryRelease('buildFullNodeJar', 'FullNode', 'org.tron.program.FullNode'), - binaryRelease('buildKeystoreFactoryJar', 'KeystoreFactory', 'org.tron.program.KeystoreFactory'), - binaryRelease('buildDBConvertJar', 'DBConvert', 'org.tron.program.DBConvert'), - binaryRelease('buildLiteFullNodeToolJar', 'LiteFullNodeTool', 'org.tron.tool.litefullnode.LiteFullNodeTool')) +def releaseBinary = hasProperty('binaryRelease') ? getProperty('binaryRelease') : 'true' +if (releaseBinary == 'true') { + artifacts { + archives(binaryRelease('buildSolidityNodeJar', 'SolidityNode', 'org.tron.program.SolidityNode'), + binaryRelease('buildFullNodeJar', 'FullNode', 'org.tron.program.FullNode'), + binaryRelease('buildKeystoreFactoryJar', 'KeystoreFactory', 'org.tron.program.KeystoreFactory'), + binaryRelease('buildDBConvertJar', 'DBConvert', 'org.tron.program.DBConvert'), + binaryRelease('buildLiteFullNodeToolJar', 'LiteFullNodeTool', 'org.tron.tool.litefullnode.LiteFullNodeTool')) + } } task copyToParent(type: Copy) { diff --git a/framework/src/main/java/org/tron/common/logsfilter/EventPluginLoader.java b/framework/src/main/java/org/tron/common/logsfilter/EventPluginLoader.java index ef218dc84af..53ab444ae5d 100644 --- a/framework/src/main/java/org/tron/common/logsfilter/EventPluginLoader.java +++ b/framework/src/main/java/org/tron/common/logsfilter/EventPluginLoader.java @@ -1,5 +1,6 @@ package org.tron.common.logsfilter; +import com.beust.jcommander.internal.Sets; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; @@ -112,6 +113,7 @@ public static boolean matchFilter(ContractTrigger trigger) { if (!matched) { return false; } + return filterContractAddress(trigger, filterQuery.getContractAddressList()) && filterContractTopicList(trigger, filterQuery.getContractTopicList()); } @@ -144,12 +146,12 @@ private static boolean filterContractTopicList(ContractTrigger trigger, List hset = null; + Set hset = Sets.newHashSet(); if (trigger instanceof ContractLogTrigger) { hset = ((ContractLogTrigger) trigger).getTopicList().stream().collect(Collectors.toSet()); } else if (trigger instanceof ContractEventTrigger) { hset = new HashSet<>(((ContractEventTrigger) trigger).getTopicMap().values()); - } else if (trigger instanceof ContractTrigger) { + } else if (trigger != null) { hset = trigger.getLogInfo().getClonedTopics() .stream().map(Hex::toHexString).collect(Collectors.toSet()); } diff --git a/framework/src/main/java/org/tron/common/logsfilter/capsule/ContractTriggerCapsule.java b/framework/src/main/java/org/tron/common/logsfilter/capsule/ContractTriggerCapsule.java index 935b56c5a77..64e64f873e9 100644 --- a/framework/src/main/java/org/tron/common/logsfilter/capsule/ContractTriggerCapsule.java +++ b/framework/src/main/java/org/tron/common/logsfilter/capsule/ContractTriggerCapsule.java @@ -2,8 +2,9 @@ import static org.tron.common.logsfilter.EventPluginLoader.matchFilter; -import java.util.ArrayList; import java.util.List; +import java.util.concurrent.LinkedBlockingQueue; + import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @@ -132,7 +133,8 @@ public void processTrigger() { if (EventPluginLoader.getInstance().isSolidityEventTriggerEnable()) { Args.getSolidityContractEventTriggerMap().computeIfAbsent(event - .getBlockNumber(), listBlk -> new ArrayList<>()).add((ContractEventTrigger) event); + .getBlockNumber(), listBlk -> new LinkedBlockingQueue()) + .offer((ContractEventTrigger) event); } } else { @@ -142,7 +144,8 @@ public void processTrigger() { if (EventPluginLoader.getInstance().isSolidityLogTriggerEnable()) { Args.getSolidityContractLogTriggerMap().computeIfAbsent(event - .getBlockNumber(), listBlk -> new ArrayList<>()).add((ContractLogTrigger) event); + .getBlockNumber(), listBlk -> new LinkedBlockingQueue()) + .offer((ContractLogTrigger) event); } } } diff --git a/framework/src/main/java/org/tron/common/overlay/discover/dht/Bucket.java b/framework/src/main/java/org/tron/common/overlay/discover/dht/Bucket.java index 8569ab23943..bc523b46d4d 100644 --- a/framework/src/main/java/org/tron/common/overlay/discover/dht/Bucket.java +++ b/framework/src/main/java/org/tron/common/overlay/discover/dht/Bucket.java @@ -138,7 +138,7 @@ public interface DoOnTree { public static class SaveLeaf implements DoOnTree { - List leafs = new ArrayList<>(); + private List leafs = new ArrayList<>(); @Override public void call(Bucket bucket) { diff --git a/framework/src/main/java/org/tron/common/overlay/discover/dht/Peer.java b/framework/src/main/java/org/tron/common/overlay/discover/dht/Peer.java index 65315901a66..cc55c39a1f7 100644 --- a/framework/src/main/java/org/tron/common/overlay/discover/dht/Peer.java +++ b/framework/src/main/java/org/tron/common/overlay/discover/dht/Peer.java @@ -22,11 +22,12 @@ import org.spongycastle.util.BigIntegers; import org.spongycastle.util.encoders.Hex; import org.tron.common.utils.Utils; +import org.tron.core.Constant; public class Peer { private byte[] id; - private String host = "127.0.0.1"; + private String host = Constant.LOCAL_HOST; private int port = 0; public Peer(byte[] id, String host, int port) { diff --git a/framework/src/main/java/org/tron/common/overlay/discover/node/NodeHandler.java b/framework/src/main/java/org/tron/common/overlay/discover/node/NodeHandler.java index 76379683065..aedf330e806 100644 --- a/framework/src/main/java/org/tron/common/overlay/discover/node/NodeHandler.java +++ b/framework/src/main/java/org/tron/common/overlay/discover/node/NodeHandler.java @@ -35,7 +35,7 @@ @Slf4j(topic = "discover") public class NodeHandler { - private static long pingTimeout = 15000; + private static long pingTimeout = Args.getInstance().getNodeDiscoveryPingTimeout(); private Node sourceNode; private Node node; private State state; diff --git a/framework/src/main/java/org/tron/common/overlay/discover/node/statistics/MessageStatistics.java b/framework/src/main/java/org/tron/common/overlay/discover/node/statistics/MessageStatistics.java index 6710dd47362..fa285929639 100644 --- a/framework/src/main/java/org/tron/common/overlay/discover/node/statistics/MessageStatistics.java +++ b/framework/src/main/java/org/tron/common/overlay/discover/node/statistics/MessageStatistics.java @@ -174,44 +174,20 @@ private void addTcpMessage(Message msg, boolean flag) { case INVENTORY: InventoryMessage inventoryMessage = (InventoryMessage) msg; int inventorySize = inventoryMessage.getInventory().getIdsCount(); - if (flag) { - if (inventoryMessage.getInvMessageType() == MessageTypes.TRX) { - tronInTrxInventory.add(); - tronInTrxInventoryElement.add(inventorySize); - } else { - tronInBlockInventory.add(); - tronInBlockInventoryElement.add(inventorySize); - } - } else { - if (inventoryMessage.getInvMessageType() == MessageTypes.TRX) { - tronOutTrxInventory.add(); - tronOutTrxInventoryElement.add(inventorySize); - } else { - tronOutBlockInventory.add(); - tronOutBlockInventoryElement.add(inventorySize); - } - } + messageProcess(inventoryMessage.getInvMessageType(), + tronInTrxInventory,tronInTrxInventoryElement,tronInBlockInventory, + tronInBlockInventoryElement,tronOutTrxInventory,tronOutTrxInventoryElement, + tronOutBlockInventory,tronOutBlockInventoryElement, + flag, inventorySize); break; case FETCH_INV_DATA: FetchInvDataMessage fetchInvDataMessage = (FetchInvDataMessage) msg; int fetchSize = fetchInvDataMessage.getInventory().getIdsCount(); - if (flag) { - if (fetchInvDataMessage.getInvMessageType() == MessageTypes.TRX) { - tronInTrxFetchInvData.add(); - tronInTrxFetchInvDataElement.add(fetchSize); - } else { - tronInBlockFetchInvData.add(); - tronInBlockFetchInvDataElement.add(fetchSize); - } - } else { - if (fetchInvDataMessage.getInvMessageType() == MessageTypes.TRX) { - tronOutTrxFetchInvData.add(); - tronOutTrxFetchInvDataElement.add(fetchSize); - } else { - tronOutBlockFetchInvData.add(); - tronOutBlockFetchInvDataElement.add(fetchSize); - } - } + messageProcess(fetchInvDataMessage.getInvMessageType(), + tronInTrxFetchInvData,tronInTrxFetchInvDataElement,tronInBlockFetchInvData, + tronInBlockFetchInvDataElement,tronOutTrxFetchInvData,tronOutTrxFetchInvDataElement, + tronOutBlockFetchInvData,tronOutBlockFetchInvDataElement, + flag, fetchSize); break; case TRXS: TransactionsMessage transactionsMessage = (TransactionsMessage) msg; @@ -240,5 +216,35 @@ private void addTcpMessage(Message msg, boolean flag) { break; } } + + + private void messageProcess(MessageTypes messageType, + MessageCount inTrx, + MessageCount inTrxEle, + MessageCount inBlock, + MessageCount inBlockEle, + MessageCount outTrx, + MessageCount outTrxEle, + MessageCount outBlock, + MessageCount outBlockEle, + boolean flag, int size) { + if (flag) { + if (messageType == MessageTypes.TRX) { + inTrx.add(); + inTrxEle.add(size); + } else { + inBlock.add(); + inBlockEle.add(size); + } + } else { + if (messageType == MessageTypes.TRX) { + outTrx.add(); + outTrxEle.add(size); + } else { + outBlock.add(); + outBlockEle.add(size); + } + } + } } diff --git a/framework/src/main/java/org/tron/common/overlay/discover/node/statistics/NodeStatistics.java b/framework/src/main/java/org/tron/common/overlay/discover/node/statistics/NodeStatistics.java index adf85e7b8e6..82b18b2071c 100644 --- a/framework/src/main/java/org/tron/common/overlay/discover/node/statistics/NodeStatistics.java +++ b/framework/src/main/java/org/tron/common/overlay/discover/node/statistics/NodeStatistics.java @@ -166,7 +166,7 @@ public String toString() { + " " + messageStatistics.discoverOutNeighbours + "/" + messageStatistics.discoverInFindNode + " " - + ((int) discoverMessageLatency.getAvrg()) + "ms" + + ((int) discoverMessageLatency.getAvg()) + "ms" + ", p2p: " + p2pHandShake + "/" + messageStatistics.p2pInHello + "/" + messageStatistics.p2pOutHello + " " + ", tron: " + messageStatistics.tronInMessage + "/" + messageStatistics.tronOutMessage @@ -205,7 +205,7 @@ public void add(long value) { count++; } - public long getAvrg() { + public long getAvg() { return count == 0 ? 0 : sum / count; } diff --git a/framework/src/main/java/org/tron/common/overlay/discover/node/statistics/Reputation.java b/framework/src/main/java/org/tron/common/overlay/discover/node/statistics/Reputation.java index 0efa17979e5..685407c11ed 100644 --- a/framework/src/main/java/org/tron/common/overlay/discover/node/statistics/Reputation.java +++ b/framework/src/main/java/org/tron/common/overlay/discover/node/statistics/Reputation.java @@ -29,8 +29,8 @@ private int getPacketLossRateScore() { } private int getNetLatencyScore() { - return (int) (nodeStatistics.discoverMessageLatency.getAvrg() == 0 ? 0 - : min(1000 / nodeStatistics.discoverMessageLatency.getAvrg(), 20)); + return (int) (nodeStatistics.discoverMessageLatency.getAvg() == 0 ? 0 + : min(1000 / nodeStatistics.discoverMessageLatency.getAvg(), 20)); } private int getHandshakeScore() { diff --git a/framework/src/main/java/org/tron/common/overlay/server/SyncPool.java b/framework/src/main/java/org/tron/common/overlay/server/SyncPool.java index c8a42484260..311181c8efa 100644 --- a/framework/src/main/java/org/tron/common/overlay/server/SyncPool.java +++ b/framework/src/main/java/org/tron/common/overlay/server/SyncPool.java @@ -144,7 +144,7 @@ public synchronized void onConnect(Channel peer) { activePeers.add(peerConnection); activePeers .sort(Comparator.comparingDouble( - c -> c.getNodeStatistics().pingMessageLatency.getAvrg())); + c -> c.getNodeStatistics().pingMessageLatency.getAvg())); peerConnection.onConnect(); } } diff --git a/framework/src/main/java/org/tron/common/storage/DepositImpl.java b/framework/src/main/java/org/tron/common/storage/DepositImpl.java index b40a2d666c4..183ce17df93 100644 --- a/framework/src/main/java/org/tron/common/storage/DepositImpl.java +++ b/framework/src/main/java/org/tron/common/storage/DepositImpl.java @@ -176,7 +176,7 @@ public synchronized AccountCapsule getAccount(byte[] address) { public byte[] getBlackHoleAddress() { // using dbManager directly, black hole address should not be changed // when executing smart contract. - return getAccountStore().getBlackhole().getAddress().toByteArray(); + return getAccountStore().getBlackholeAddress(); } @Override diff --git a/framework/src/main/java/org/tron/core/Wallet.java b/framework/src/main/java/org/tron/core/Wallet.java index 80c2705833b..7dbb317eb90 100755 --- a/framework/src/main/java/org/tron/core/Wallet.java +++ b/framework/src/main/java/org/tron/core/Wallet.java @@ -22,8 +22,6 @@ import static org.tron.common.utils.Commons.getExchangeStoreFinal; import static org.tron.common.utils.WalletUtil.isConstant; import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; -import static org.tron.core.config.Parameter.ChainConstant.FROZEN_PERIOD; -import static org.tron.core.config.Parameter.ChainConstant.WITNESS_STANDBY_LENGTH; import static org.tron.core.config.Parameter.DatabaseConstants.EXCHANGE_COUNT_LIMIT_MAX; import static org.tron.core.config.Parameter.DatabaseConstants.MARKET_COUNT_LIMIT_MAX; import static org.tron.core.config.Parameter.DatabaseConstants.PROPOSAL_COUNT_LIMIT_MAX; @@ -40,7 +38,6 @@ import java.security.SignatureException; import java.util.ArrayList; import java.util.Arrays; -import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -48,11 +45,11 @@ import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; -import java.util.concurrent.atomic.AtomicLong; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.Pair; import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -110,7 +107,6 @@ 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; @@ -126,6 +122,7 @@ import org.tron.core.actuator.VMActuator; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; +import org.tron.core.capsule.BlockBalanceTraceCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.BlockCapsule.BlockId; import org.tron.core.capsule.BytesCapsule; @@ -149,6 +146,7 @@ import org.tron.core.capsule.utils.MarketUtils; import org.tron.core.config.args.Args; import org.tron.core.db.BandwidthProcessor; +import org.tron.core.db.BlockIndexStore; import org.tron.core.db.EnergyProcessor; import org.tron.core.db.Manager; import org.tron.core.db.TransactionContext; @@ -174,8 +172,9 @@ import org.tron.core.net.message.TransactionMessage; import org.tron.core.store.AccountIdIndexStore; import org.tron.core.store.AccountStore; +import org.tron.core.store.AccountTraceStore; +import org.tron.core.store.BalanceTraceStore; import org.tron.core.store.ContractStore; -import org.tron.core.store.DelegationStore; import org.tron.core.store.MarketOrderStore; import org.tron.core.store.MarketPairPriceToOrderStore; import org.tron.core.store.MarketPairToPriceStore; @@ -210,8 +209,9 @@ import org.tron.protos.Protocol.Transaction.Contract.ContractType; import org.tron.protos.Protocol.Transaction.Result.code; import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.Protocol.Vote; import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; +import org.tron.protos.contract.BalanceContract; +import org.tron.protos.contract.BalanceContract.BlockBalanceTrace; import org.tron.protos.contract.BalanceContract.TransferContract; import org.tron.protos.contract.ShieldContract.IncrementalMerkleTree; import org.tron.protos.contract.ShieldContract.IncrementalMerkleVoucherInfo; @@ -983,6 +983,20 @@ public Protocol.ChainParameters getChainParameters() { // .setValue(dbManager.getDynamicPropertiesStore().getAllowTvmAssetIssue()) // .build()); + builder.addChainParameter(Protocol.ChainParameters.ChainParameter.newBuilder() + .setKey("getAllowTransactionFeePool") + .setValue(dbManager.getDynamicPropertiesStore().getAllowTransactionFeePool()) + .build()); + builder.addChainParameter(Protocol.ChainParameters.ChainParameter.newBuilder() + .setKey("getMaxFeeLimit") + .setValue(dbManager.getDynamicPropertiesStore().getMaxFeeLimit()) + .build()); + + builder.addChainParameter(Protocol.ChainParameters.ChainParameter.newBuilder() + .setKey("getAllowOptimizeBlackHole") + .setValue(dbManager.getDynamicPropertiesStore().getAllowBlackHoleOptimization()) + .build()); + return builder.build(); } @@ -1379,7 +1393,7 @@ private long getBlockNumber(OutputPoint outPoint) return blockNum; } - //in:outPoint,out:blockNumber + //in:outPoint, out:blockNumber private IncrementalMerkleVoucherContainer createWitness(OutputPoint outPoint, Long blockNumber) throws ItemNotFoundException, BadItemException, InvalidProtocolBufferException, ZksnarkException { @@ -3650,5 +3664,78 @@ public BytesMessage getTriggerInputForShieldedTRC20Contract( BytesMessage.Builder bytesBuilder = BytesMessage.newBuilder(); return bytesBuilder.setValue(ByteString.copyFrom(Hex.decode(input))).build(); } + + public BalanceContract.AccountBalanceResponse getAccountBalance( + BalanceContract.AccountBalanceRequest request) + throws ItemNotFoundException { + BalanceContract.AccountIdentifier accountIdentifier = request.getAccountIdentifier(); + checkAccountIdentifier(accountIdentifier); + BlockBalanceTrace.BlockIdentifier blockIdentifier = request.getBlockIdentifier(); + checkBlockIdentifier(blockIdentifier); + + AccountTraceStore accountTraceStore = chainBaseManager.getAccountTraceStore(); + BlockIndexStore blockIndexStore = chainBaseManager.getBlockIndexStore(); + BlockId blockId = blockIndexStore.get(blockIdentifier.getNumber()); + if (!blockId.getByteString().equals(blockIdentifier.getHash())) { + throw new IllegalArgumentException("number and hash do not match"); + } + + Pair pair = accountTraceStore.getPrevBalance( + accountIdentifier.getAddress().toByteArray(), blockIdentifier.getNumber()); + BalanceContract.AccountBalanceResponse.Builder builder = + BalanceContract.AccountBalanceResponse.newBuilder(); + if (pair.getLeft() == blockIdentifier.getNumber()) { + builder.setBlockIdentifier(blockIdentifier); + } else { + blockId = blockIndexStore.get(pair.getLeft()); + builder.setBlockIdentifier(BlockBalanceTrace.BlockIdentifier.newBuilder() + .setNumber(pair.getLeft()) + .setHash(blockId.getByteString())); + } + + builder.setBalance(pair.getRight()); + return builder.build(); + } + + public BalanceContract.BlockBalanceTrace getBlockBalance( + BlockBalanceTrace.BlockIdentifier request) throws ItemNotFoundException, BadItemException { + checkBlockIdentifier(request); + BalanceTraceStore balanceTraceStore = chainBaseManager.getBalanceTraceStore(); + BlockIndexStore blockIndexStore = chainBaseManager.getBlockIndexStore(); + BlockId blockId = blockIndexStore.get(request.getNumber()); + if (!blockId.getByteString().equals(request.getHash())) { + throw new IllegalArgumentException("number and hash do not match"); + } + + BlockBalanceTraceCapsule blockBalanceTraceCapsule = + balanceTraceStore.getBlockBalanceTrace(blockId); + if (blockBalanceTraceCapsule == null) { + throw new ItemNotFoundException("This block does not exist"); + } + + return blockBalanceTraceCapsule.getInstance(); + } + + public void checkBlockIdentifier(BlockBalanceTrace.BlockIdentifier blockIdentifier) { + if (blockIdentifier == blockIdentifier.getDefaultInstanceForType()) { + throw new IllegalArgumentException("block_identifier null"); + } + if (blockIdentifier.getNumber() < 0) { + throw new IllegalArgumentException("block_identifier number less than 0"); + } + if (blockIdentifier.getHash().size() != 32) { + throw new IllegalArgumentException("block_identifier hash length not equals 32"); + } + + } + + public void checkAccountIdentifier(BalanceContract.AccountIdentifier accountIdentifier) { + if (accountIdentifier == accountIdentifier.getDefaultInstanceForType()) { + throw new IllegalArgumentException("account_identifier is null"); + } + if (accountIdentifier.getAddress().isEmpty()) { + throw new IllegalArgumentException("account_identifier address is null"); + } + } } 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 0623901114f..83e9b5d7ccc 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 @@ -25,6 +25,7 @@ import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import lombok.Getter; @@ -59,8 +60,8 @@ import org.tron.core.config.Configuration; import org.tron.core.config.Parameter.NetConstants; import org.tron.core.config.Parameter.NodeConstant; +import org.tron.core.exception.CipherException; import org.tron.core.store.AccountStore; -import org.tron.keystore.CipherException; import org.tron.keystore.Credentials; import org.tron.keystore.WalletUtils; import org.tron.program.Version; @@ -76,12 +77,12 @@ public class Args extends CommonParameter { @Autowired(required = false) @Getter - private static ConcurrentHashMap> + private static ConcurrentHashMap> solidityContractLogTriggerMap = new ConcurrentHashMap<>(); @Autowired(required = false) @Getter - private static ConcurrentHashMap> + private static ConcurrentHashMap> solidityContractEventTriggerMap = new ConcurrentHashMap<>(); public static void clearParam() { @@ -122,6 +123,7 @@ public static void clearParam() { PARAMETER.nodeDiscoveryBindIp = ""; PARAMETER.nodeExternalIp = ""; PARAMETER.nodeDiscoveryPublicHomeNode = false; + PARAMETER.nodeDiscoveryPingTimeout = 15000; PARAMETER.nodeP2pPingInterval = 0L; PARAMETER.nodeP2pVersion = 0; PARAMETER.rpcPort = 0; @@ -177,9 +179,12 @@ public static void clearParam() { PARAMETER.allowPBFT = 0; PARAMETER.allowShieldedTRC20Transaction = 0; PARAMETER.allowMarketTransaction = 0; + PARAMETER.allowTransactionFeePool = 0; + PARAMETER.allowBlackHoleOptimization = 0; PARAMETER.allowTvmIstanbul = 0; PARAMETER.allowTvmStake = 0; PARAMETER.allowTvmAssetIssue = 0; + PARAMETER.historyBalanceLookup = false; } /** @@ -190,7 +195,7 @@ public static void setParam(final String[] args, final String confFileName) { if (PARAMETER.version) { JCommander.getConsole() .println(Version.getVersion() - + "\n" + Version.versionName + "\n" + Version.versionCode); + + "\n" + Version.VERSION_NAME + "\n" + Version.VERSION_CODE); exit(0); } @@ -226,17 +231,7 @@ public static void setParam(final String[] args, final String confFileName) { localWitnesses = new LocalWitnesses(); List localwitness = config.getStringList(Constant.LOCAL_WITNESS); localWitnesses.setPrivateKeys(localwitness); - - if (config.hasPath(Constant.LOCAL_WITNESS_ACCOUNT_ADDRESS)) { - byte[] bytes = Commons - .decodeFromBase58Check(config.getString(Constant.LOCAL_WITNESS_ACCOUNT_ADDRESS)); - if (bytes != null) { - localWitnesses.setWitnessAccountAddress(bytes); - logger.debug("Got localWitnessAccountAddress from config.conf"); - } else { - logger.warn(IGNORE_WRONG_WITNESS_ADDRESS_FORMAT); - } - } + witnessAddressCheck(config); localWitnesses.initWitnessAccountAddress(PARAMETER.isECKeyCryptoEngine()); logger.debug("Got privateKey from config.conf"); } else if (config.hasPath(Constant.LOCAL_WITNESS_KEYSTORE)) { @@ -269,17 +264,7 @@ public static void setParam(final String[] args, final String confFileName) { } } localWitnesses.setPrivateKeys(privateKeys); - - if (config.hasPath(Constant.LOCAL_WITNESS_ACCOUNT_ADDRESS)) { - byte[] bytes = Commons - .decodeFromBase58Check(config.getString(Constant.LOCAL_WITNESS_ACCOUNT_ADDRESS)); - if (bytes != null) { - localWitnesses.setWitnessAccountAddress(bytes); - logger.debug("Got localWitnessAccountAddress from config.conf"); - } else { - logger.warn(IGNORE_WRONG_WITNESS_ADDRESS_FORMAT); - } - } + witnessAddressCheck(config); localWitnesses.initWitnessAccountAddress(PARAMETER.isECKeyCryptoEngine()); logger.debug("Got privateKey from keystore"); } @@ -426,6 +411,10 @@ public static void setParam(final String[] args, final String confFileName) { config.hasPath(Constant.NODE_DISCOVERY_PUBLIC_HOME_NODE) && config .getBoolean(Constant.NODE_DISCOVERY_PUBLIC_HOME_NODE); + PARAMETER.nodeDiscoveryPingTimeout = + config.hasPath(Constant.NODE_DISCOVERY_PING_TIMEOUT) + ? config.getLong(Constant.NODE_DISCOVERY_PING_TIMEOUT) : 15000; + PARAMETER.nodeP2pPingInterval = config.hasPath(Constant.NODE_P2P_PING_INTERVAL) ? config.getLong(Constant.NODE_P2P_PING_INTERVAL) : 0; @@ -639,6 +628,15 @@ 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; + + PARAMETER.allowBlackHoleOptimization = + config.hasPath(Constant.COMMITTEE_ALLOW_BLACK_HOLE_OPTIMIZATION) ? config + .getInt(Constant.COMMITTEE_ALLOW_BLACK_HOLE_OPTIMIZATION) : 0; + PARAMETER.allowTvmIstanbul = config.hasPath(Constant.COMMITTEE_ALLOW_TVM_ISTANBUL) ? config .getInt(Constant.COMMITTEE_ALLOW_TVM_ISTANBUL) : 0; @@ -729,7 +727,7 @@ public static void setParam(final String[] args, final String confFileName) { PARAMETER.metricsStorageEnable = config.hasPath(Constant.METRICS_STORAGE_ENABLE) && config .getBoolean(Constant.METRICS_STORAGE_ENABLE); PARAMETER.influxDbIp = config.hasPath(Constant.METRICS_INFLUXDB_IP) ? config - .getString(Constant.METRICS_INFLUXDB_IP) : "127.0.0.1"; + .getString(Constant.METRICS_INFLUXDB_IP) : Constant.LOCAL_HOST; PARAMETER.influxDbPort = config.hasPath(Constant.METRICS_INFLUXDB_PORT) ? config .getInt(Constant.METRICS_INFLUXDB_PORT) : 8086; PARAMETER.influxDbDatabase = config.hasPath(Constant.METRICS_INFLUXDB_DATABASE) ? config @@ -743,6 +741,9 @@ public static void setParam(final String[] args, final String confFileName) { config.hasPath(Constant.NODE_OPEN_HISTORY_QUERY_WHEN_LITEFN) && config.getBoolean(Constant.NODE_OPEN_HISTORY_QUERY_WHEN_LITEFN)); + PARAMETER.historyBalanceLookup = config.hasPath(Constant.HISTORY_BALANCE_LOOKUP) && config + .getBoolean(Constant.HISTORY_BALANCE_LOOKUP); + logConfig(); } @@ -805,7 +806,7 @@ private static List getNodes(final com.typesafe.config.Config config, Stri Node n = Node.instanceOf(configString); if (!(PARAMETER.nodeDiscoveryBindIp.equals(n.getHost()) || PARAMETER.nodeExternalIp.equals(n.getHost()) - || "127.0.0.1".equals(n.getHost())) + || Constant.LOCAL_HOST.equals(n.getHost())) || PARAMETER.nodeListenPort != n.getPort()) { ret.add(n); } @@ -1067,7 +1068,7 @@ public static void logConfig() { logger.info("Backup member size: {}", parameter.getBackupMembers().size()); logger.info("************************ Code version *************************"); logger.info("Code version : {}", Version.getVersion()); - logger.info("Version code: {}", Version.versionCode); + logger.info("Version code: {}", Version.VERSION_CODE); logger.info("************************ DB config *************************"); logger.info("DB version : {}", parameter.getStorage().getDbVersion()); logger.info("DB engine : {}", parameter.getStorage().getDbEngine()); @@ -1101,5 +1102,18 @@ public String getOutputDirectory() { } return this.outputDirectory; } + + private static void witnessAddressCheck(Config config) { + if (config.hasPath(Constant.LOCAL_WITNESS_ACCOUNT_ADDRESS)) { + byte[] bytes = Commons + .decodeFromBase58Check(config.getString(Constant.LOCAL_WITNESS_ACCOUNT_ADDRESS)); + if (bytes != null) { + localWitnesses.setWitnessAccountAddress(bytes); + logger.debug("Got localWitnessAccountAddress from config.conf"); + } else { + logger.warn(IGNORE_WRONG_WITNESS_ADDRESS_FORMAT); + } + } + } } 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 f8952c5f8eb..f3c5351dfab 100644 --- a/framework/src/main/java/org/tron/core/consensus/ProposalService.java +++ b/framework/src/main/java/org/tron/core/consensus/ProposalService.java @@ -230,6 +230,18 @@ public static boolean process(Manager manager, ProposalCapsule proposalCapsule) manager.getDynamicPropertiesStore().saveMarketCancelFee(entry.getValue()); break; } + case MAX_FEE_LIMIT: { + manager.getDynamicPropertiesStore().saveMaxFeeLimit(entry.getValue()); + break; + } + case ALLOW_TRANSACTION_FEE_POOL: { + manager.getDynamicPropertiesStore().saveAllowTransactionFeePool(entry.getValue()); + break; + } + case ALLOW_BLACKHOLE_OPTIMIZATION: { + manager.getDynamicPropertiesStore().saveAllowBlackHoleOptimization(entry.getValue()); + break; + } default: find = false; break; diff --git a/framework/src/main/java/org/tron/core/db/BandwidthProcessor.java b/framework/src/main/java/org/tron/core/db/BandwidthProcessor.java index 549f177c17a..c1de0c24b0f 100644 --- a/framework/src/main/java/org/tron/core/db/BandwidthProcessor.java +++ b/framework/src/main/java/org/tron/core/db/BandwidthProcessor.java @@ -130,7 +130,7 @@ public void consume(TransactionCapsule trx, TransactionTrace trace) private boolean useTransactionFee(AccountCapsule accountCapsule, long bytes, TransactionTrace trace) { long fee = chainBaseManager.getDynamicPropertiesStore().getTransactionFee() * bytes; - if (consumeFee(accountCapsule, fee)) { + if (consumeFeeForBandwidth(accountCapsule, fee)) { trace.setNetBill(0, fee); chainBaseManager.getDynamicPropertiesStore().addTotalTransactionCost(fee); return true; @@ -181,8 +181,8 @@ public boolean consumeBandwidthForCreateNewAccount(AccountCapsule accountCapsule public boolean consumeFeeForCreateNewAccount(AccountCapsule accountCapsule, TransactionTrace trace) { long fee = chainBaseManager.getDynamicPropertiesStore().getCreateAccountFee(); - if (consumeFee(accountCapsule, fee)) { - trace.setNetBill(0, fee); + if (consumeFeeForNewAccount(accountCapsule, fee)) { + trace.setNetBillForCreateNewAccount(0, fee); chainBaseManager.getDynamicPropertiesStore().addTotalCreateAccountCost(fee); return true; } else { 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 fbf4a4e556c..b233400c85e 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,8 @@ package org.tron.core.db; import static org.tron.common.utils.Commons.adjustBalance; +import static org.tron.protos.Protocol.Transaction.Contract.ContractType.TransferContract; +import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; @@ -69,6 +71,7 @@ import org.tron.core.Constant; import org.tron.core.actuator.ActuatorCreator; import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.BlockBalanceTraceCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.BlockCapsule.BlockId; import org.tron.core.capsule.BytesCapsule; @@ -111,6 +114,7 @@ import org.tron.core.exception.ZksnarkException; import org.tron.core.metrics.MetricsKey; import org.tron.core.metrics.MetricsUtil; +import org.tron.core.service.MortgageService; import org.tron.core.store.AccountIdIndexStore; import org.tron.core.store.AccountIndexStore; import org.tron.core.store.AccountStore; @@ -131,7 +135,6 @@ import org.tron.core.store.StoreFactory; import org.tron.core.store.TransactionHistoryStore; import org.tron.core.store.TransactionRetStore; -import org.tron.core.store.TreeBlockIndexStore; import org.tron.core.store.VotesStore; import org.tron.core.store.WitnessScheduleStore; import org.tron.core.store.WitnessStore; @@ -139,10 +142,8 @@ import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Transaction; import org.tron.protos.Protocol.Transaction.Contract; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import org.tron.protos.Protocol.Transaction.Result; -import org.tron.protos.Protocol.Transaction.Result.contractResult; import org.tron.protos.Protocol.TransactionInfo; +import org.tron.protos.contract.BalanceContract; @Slf4j(topic = "DB") @@ -151,6 +152,8 @@ public class Manager { private static final int SHIELDED_TRANS_IN_BLOCK_COUNTS = 1; private static final String SAVE_BLOCK = "save block: "; + private static final int SLEEP_TIME_OUT = 50; + private static final int TX_ID_CACHE_SIZE = 100_000; private final int shieldedTransInPendingMaxCounts = Args.getInstance().getShieldedTransInPendingMaxCounts(); @Getter @@ -187,7 +190,7 @@ public class Manager { private BlockingQueue pushTransactionQueue = new LinkedBlockingQueue<>(); @Getter private Cache transactionIdCache = CacheBuilder - .newBuilder().maximumSize(100_000).recordStats().build(); + .newBuilder().maximumSize(TX_ID_CACHE_SIZE).recordStats().build(); @Autowired private AccountStateCallBack accountStateCallBack; @Autowired @@ -195,7 +198,7 @@ public class Manager { private Set ownerAddressSet = new HashSet<>(); @Getter @Autowired - private DelegationService delegationService; + private MortgageService mortgageService; @Autowired private Consensus consensus; @Autowired @@ -224,7 +227,7 @@ public class Manager { if (tx != null) { this.rePush(tx); } else { - TimeUnit.MILLISECONDS.sleep(50L); + TimeUnit.MILLISECONDS.sleep(SLEEP_TIME_OUT); } } catch (Throwable ex) { logger.error("unknown exception happened in rePush loop", ex); @@ -339,7 +342,7 @@ public void stopRePushTriggerThread() { @PostConstruct public void init() { Message.setDynamicPropertiesStore(this.getDynamicPropertiesStore()); - delegationService + mortgageService .initStore(chainBaseManager.getWitnessStore(), chainBaseManager.getDelegationStore(), chainBaseManager.getDynamicPropertiesStore(), chainBaseManager.getAccountStore()); accountStateCallBack.setChainBaseManager(chainBaseManager); @@ -354,7 +357,7 @@ public void init() { this.rePushTransactions = new LinkedBlockingQueue<>(); this.triggerCapsuleQueue = new LinkedBlockingQueue<>(); chainBaseManager.setMerkleContainer(getMerkleContainer()); - chainBaseManager.setDelegationService(delegationService); + chainBaseManager.setMortgageService(mortgageService); this.initGenesis(); try { @@ -438,6 +441,7 @@ public void initGenesis() { this.initWitness(); this.khaosDb.start(genesisBlock); this.updateRecentBlock(genesisBlock); + initAccountHistoryBalance(); } } } @@ -465,6 +469,37 @@ public void initAccount() { }); } + public void initAccountHistoryBalance() { + BlockCapsule genesis = chainBaseManager.getGenesisBlock(); + BlockBalanceTraceCapsule genesisBlockBalanceTraceCapsule = + new BlockBalanceTraceCapsule(genesis); + List transactionCapsules = genesis.getTransactions(); + for (TransactionCapsule transactionCapsule : transactionCapsules) { + BalanceContract.TransferContract transferContract = transactionCapsule.getTransferContract(); + BalanceContract.TransactionBalanceTrace.Operation operation = + BalanceContract.TransactionBalanceTrace.Operation.newBuilder() + .setOperationIdentifier(0) + .setAddress(transferContract.getToAddress()) + .setAmount(transferContract.getAmount()) + .build(); + + BalanceContract.TransactionBalanceTrace transactionBalanceTrace = + BalanceContract.TransactionBalanceTrace.newBuilder() + .setTransactionIdentifier(transactionCapsule.getTransactionId().getByteString()) + .setType(TransferContract.name()) + .setStatus(SUCCESS.name()) + .addOperation(operation) + .build(); + genesisBlockBalanceTraceCapsule.addTransactionBalanceTrace(transactionBalanceTrace); + + chainBaseManager.getAccountTraceStore().recordBalanceWithBlock( + transferContract.getToAddress().toByteArray(), 0, transferContract.getAmount()); + } + + chainBaseManager.getBalanceTraceStore() + .put(Longs.toByteArray(0), genesisBlockBalanceTraceCapsule); + } + /** * save witnesses into database. */ @@ -612,12 +647,17 @@ void validateDup(TransactionCapsule transactionCapsule) throws DupTransactionExc } private boolean containsTransaction(TransactionCapsule transactionCapsule) { + return containsTransaction(transactionCapsule.getTransactionId().getBytes()); + } + + + private boolean containsTransaction(byte[] transactionId) { if (transactionCache != null) { - return transactionCache.has(transactionCapsule.getTransactionId().getBytes()); + return transactionCache.has(transactionId); } return chainBaseManager.getTransactionStore() - .has(transactionCapsule.getTransactionId().getBytes()); + .has(transactionId); } /** @@ -678,8 +718,12 @@ public void consumeMultiSignFee(TransactionCapsule trx, TransactionTrace trace) try { if (accountCapsule != null) { adjustBalance(getAccountStore(), accountCapsule, -fee); - adjustBalance(getAccountStore(), this.getAccountStore() - .getBlackhole().createDbKey(), +fee); + + if (getDynamicPropertiesStore().supportBlackHoleOptimization()) { + getDynamicPropertiesStore().burnTrx(fee); + } else { + adjustBalance(getAccountStore(), this.getAccountStore().getBlackhole(), +fee); + } } } catch (BalanceInsufficientException e) { throw new AccountResourceInsufficientException( @@ -787,7 +831,7 @@ private void switchFork(BlockCapsule newHead) while (!getDynamicPropertiesStore() .getLatestBlockHeaderHash() .equals(binaryTree.getValue().peekLast().getParentHash())) { - reorgContractTrigger(); + reOrgContractTrigger(); eraseBlock(); } } @@ -1065,6 +1109,10 @@ public TransactionInfo processTransaction(final TransactionCapsule trxCap, Block return null; } + if (Objects.nonNull(blockCap)) { + chainBaseManager.getBalanceTraceStore().initCurrentTransactionBalanceTrace(trxCap); + } + validateTapos(trxCap); validateCommon(trxCap); @@ -1128,6 +1176,13 @@ public TransactionInfo processTransaction(final TransactionCapsule trxCap, Block ownerAddressSet.add(ByteArray.toHexString(TransactionCapsule.getOwner(contract))); } + if (Objects.nonNull(blockCap)) { + chainBaseManager.getBalanceTraceStore() + .updateCurrentTransactionStatus( + trace.getRuntimeResult().getResultCode().name()); + chainBaseManager.getBalanceTraceStore().resetCurrentTransactionTrace(); + } + return transactionInfo.getInstance(); } @@ -1261,8 +1316,8 @@ private boolean isShieldedTransaction(Transaction transaction) { return true; } default: + return false; } - return false; } public TransactionStore getTransactionStore() { @@ -1296,6 +1351,9 @@ public void processBlock(BlockCapsule block) if (!consensus.validBlock(block)) { throw new ValidateScheduleException("validateWitnessSchedule error"); } + + chainBaseManager.getBalanceTraceStore().initCurrentBlockBalanceTrace(block); + //reset BlockEnergyUsage chainBaseManager.getDynamicPropertiesStore().saveBlockEnergyUsage(0); //parallel check sign @@ -1353,6 +1411,8 @@ public void processBlock(BlockCapsule block) updateTransHashCache(block); updateRecentBlock(block); updateDynamicProperties(block); + + chainBaseManager.getBalanceTraceStore().resetCurrentBlockTrace(); } private void payReward(BlockCapsule block) { @@ -1360,44 +1420,76 @@ private void payReward(BlockCapsule block) { chainBaseManager.getWitnessStore().getUnchecked(block.getInstance().getBlockHeader() .getRawData().getWitnessAddress().toByteArray()); if (getDynamicPropertiesStore().allowChangeDelegation()) { - delegationService.payBlockReward(witnessCapsule.getAddress().toByteArray(), + mortgageService.payBlockReward(witnessCapsule.getAddress().toByteArray(), getDynamicPropertiesStore().getWitnessPayPerBlock()); - delegationService.payStandbyWitness(); + mortgageService.payStandbyWitness(); + + if (chainBaseManager.getDynamicPropertiesStore().supportTransactionFeePool()) { + long transactionFeeReward = Math + .floorDiv(chainBaseManager.getDynamicPropertiesStore().getTransactionFeePool(), + Constant.TRANSACTION_FEE_POOL_PERIOD); + mortgageService.payTransactionFeeReward(witnessCapsule.getAddress().toByteArray(), + transactionFeeReward); + chainBaseManager.getDynamicPropertiesStore().saveTransactionFeePool( + chainBaseManager.getDynamicPropertiesStore().getTransactionFeePool() + - transactionFeeReward); + } } else { byte[] witness = block.getWitnessAddress().toByteArray(); AccountCapsule account = getAccountStore().get(witness); account.setAllowance(account.getAllowance() + chainBaseManager.getDynamicPropertiesStore().getWitnessPayPerBlock()); + + if (chainBaseManager.getDynamicPropertiesStore().supportTransactionFeePool()) { + long transactionFeeReward = Math + .floorDiv(chainBaseManager.getDynamicPropertiesStore().getTransactionFeePool(), + Constant.TRANSACTION_FEE_POOL_PERIOD); + account.setAllowance(account.getAllowance() + transactionFeeReward); + chainBaseManager.getDynamicPropertiesStore().saveTransactionFeePool( + chainBaseManager.getDynamicPropertiesStore().getTransactionFeePool() + - transactionFeeReward); + } + getAccountStore().put(account.createDbKey(), account); } } - private void postSolitityLogContractTrigger(Long blockNum, Long lastSolidityNum) { + private void postSolidityLogContractTrigger(Long blockNum, Long lastSolidityNum) { if (blockNum > lastSolidityNum) { return; } - for (ContractLogTrigger logTriggerCapsule : Args - .getSolidityContractLogTriggerMap().get(blockNum)) { - if (chainBaseManager.getTransactionStore().getUnchecked(ByteArray.fromHexString( - logTriggerCapsule.getTransactionId())) != null) { - logTriggerCapsule.setTriggerName(Trigger.SOLIDITYLOG_TRIGGER_NAME); - EventPluginLoader.getInstance().postSolidityLogTrigger(logTriggerCapsule); + BlockingQueue contractLogTriggersQueue = Args.getSolidityContractLogTriggerMap() + .get(blockNum); + while (!contractLogTriggersQueue.isEmpty()) { + ContractLogTrigger triggerCapsule = (ContractLogTrigger) contractLogTriggersQueue.poll(); + if (triggerCapsule == null) { + break; + } + if (containsTransaction(ByteArray.fromHexString(triggerCapsule + .getTransactionId()))) { + triggerCapsule.setTriggerName(Trigger.SOLIDITYLOG_TRIGGER_NAME); + EventPluginLoader.getInstance().postSolidityLogTrigger(triggerCapsule); } } Args.getSolidityContractLogTriggerMap().remove(blockNum); } - private void postSolitityEventContractTrigger(Long blockNum, Long lastSolidityNum) { + private void postSolidityEventContractTrigger(Long blockNum, Long lastSolidityNum) { if (blockNum > lastSolidityNum) { return; } - for (ContractEventTrigger eventTriggerCapsule : Args - .getSolidityContractEventTriggerMap().get(blockNum)) { - if (chainBaseManager.getTransactionStore() - .getUnchecked(ByteArray.fromHexString(eventTriggerCapsule - .getTransactionId())) != null) { - eventTriggerCapsule.setTriggerName(Trigger.SOLIDITYEVENT_TRIGGER_NAME); - EventPluginLoader.getInstance().postSolidityEventTrigger(eventTriggerCapsule); + BlockingQueue contractEventTriggersQueue = Args.getSolidityContractEventTriggerMap() + .get(blockNum); + while (!contractEventTriggersQueue.isEmpty()) { + ContractEventTrigger triggerCapsule = (ContractEventTrigger) contractEventTriggersQueue + .poll(); + if (triggerCapsule == null) { + break; + } + if (containsTransaction(ByteArray.fromHexString(triggerCapsule + .getTransactionId()))) { + triggerCapsule.setTriggerName(Trigger.SOLIDITYEVENT_TRIGGER_NAME); + EventPluginLoader.getInstance().postSolidityEventTrigger(triggerCapsule); } } Args.getSolidityContractEventTriggerMap().remove(blockNum); @@ -1416,6 +1508,10 @@ public void updateRecentBlock(BlockCapsule block) { } public void updateFork(BlockCapsule block) { + int blockVersion = block.getInstance().getBlockHeader().getRawData().getVersion(); + if (blockVersion > ChainConstant.BLOCK_VERSION) { + logger.warn("newer block version found: " + blockVersion + ", YOU MUST UPGRADE java-tron!"); + } chainBaseManager .getForkController().update(block); } @@ -1574,12 +1670,12 @@ private void postSolidityTrigger(final long latestSolidifiedBlockNumber) { } if (eventPluginLoaded && EventPluginLoader.getInstance().isSolidityLogTriggerEnable()) { for (Long i : Args.getSolidityContractLogTriggerMap().keySet()) { - postSolitityLogContractTrigger(i, latestSolidifiedBlockNumber); + postSolidityLogContractTrigger(i, latestSolidifiedBlockNumber); } } if (eventPluginLoaded && EventPluginLoader.getInstance().isSolidityEventTriggerEnable()) { for (Long i : Args.getSolidityContractEventTriggerMap().keySet()) { - postSolitityEventContractTrigger(i, latestSolidifiedBlockNumber); + postSolidityEventContractTrigger(i, latestSolidifiedBlockNumber); } } } @@ -1611,11 +1707,11 @@ private void postTransactionTrigger(final TransactionCapsule trxCap, } } - private void reorgContractTrigger() { + private void reOrgContractTrigger() { if (eventPluginLoaded && (EventPluginLoader.getInstance().isContractEventTriggerEnable() || EventPluginLoader.getInstance().isContractLogTriggerEnable())) { - logger.info("switchfork occurred, post reorgContractTrigger"); + logger.info("switchfork occurred, post reOrgContractTrigger"); try { BlockCapsule oldHeadBlock = chainBaseManager.getBlockById( getDynamicPropertiesStore().getLatestBlockHeaderHash()); diff --git a/framework/src/main/java/org/tron/core/db/backup/NeedBeanCondition.java b/framework/src/main/java/org/tron/core/db/backup/NeedBeanCondition.java index 550486beff2..64da8d2acc4 100644 --- a/framework/src/main/java/org/tron/core/db/backup/NeedBeanCondition.java +++ b/framework/src/main/java/org/tron/core/db/backup/NeedBeanCondition.java @@ -11,6 +11,6 @@ public class NeedBeanCondition implements Condition { public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return (Args.getInstance().getStorage().getDbVersion() == 2 && "ROCKSDB" .equals(Args.getInstance().getStorage().getDbEngine().toUpperCase())) && Args.getInstance() - .getDbBackupConfig().isEnable(); + .getDbBackupConfig().isEnable() && !Args.getInstance().isWitness(); } } \ No newline at end of file diff --git a/framework/src/main/java/org/tron/core/exception/VMMemoryOverflowException.java b/framework/src/main/java/org/tron/core/exception/VMMemoryOverflowException.java deleted file mode 100644 index 875ecfab86d..00000000000 --- a/framework/src/main/java/org/tron/core/exception/VMMemoryOverflowException.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.tron.core.exception; - -public class VMMemoryOverflowException extends TronException { - - public VMMemoryOverflowException() { - super("VM memory overflow"); - } - - public VMMemoryOverflowException(String message) { - super(message); - } - -} diff --git a/framework/src/main/java/org/tron/core/exception/ValidateBandwidthException.java b/framework/src/main/java/org/tron/core/exception/ValidateBandwidthException.java deleted file mode 100644 index c80203a3c07..00000000000 --- a/framework/src/main/java/org/tron/core/exception/ValidateBandwidthException.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.tron.core.exception; - -public class ValidateBandwidthException extends TronException { - - public ValidateBandwidthException() { - super(); - } - - public ValidateBandwidthException(String message) { - super(message); - } - -} \ No newline at end of file diff --git a/framework/src/main/java/org/tron/core/metrics/MetricsApiService.java b/framework/src/main/java/org/tron/core/metrics/MetricsApiService.java index 3f41f81b6e1..2e1651fbc99 100644 --- a/framework/src/main/java/org/tron/core/metrics/MetricsApiService.java +++ b/framework/src/main/java/org/tron/core/metrics/MetricsApiService.java @@ -3,6 +3,7 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import org.tron.core.Constant; import org.tron.core.metrics.blockchain.BlockChainInfo; import org.tron.core.metrics.blockchain.BlockChainMetricManager; import org.tron.core.metrics.net.NetInfo; @@ -35,7 +36,7 @@ public MetricsInfo getMetricsInfo() { MetricsInfo metricsInfo = new MetricsInfo(); - metricsInfo.setInterval((System.currentTimeMillis() - time) / 1000); + metricsInfo.setInterval((System.currentTimeMillis() - time) / Constant.ONE_THOUSAND); NodeInfo nodeInfo = nodeMetricManager.getNodeInfo(); metricsInfo.setNode(nodeInfo); @@ -52,7 +53,7 @@ public MetricsInfo getMetricsInfo() { public Protocol.MetricsInfo getMetricProtoInfo() { Protocol.MetricsInfo.Builder builder = Protocol.MetricsInfo.newBuilder(); - builder.setInterval((System.currentTimeMillis() - time) / 1000); + builder.setInterval((System.currentTimeMillis() - time) / Constant.ONE_THOUSAND); Protocol.MetricsInfo.NodeInfo nodeInfo = nodeMetricManager.getNodeProtoInfo(); builder.setNode(nodeInfo); diff --git a/framework/src/main/java/org/tron/core/metrics/MetricsUtil.java b/framework/src/main/java/org/tron/core/metrics/MetricsUtil.java index 156bd5e8617..6a40cf2d269 100644 --- a/framework/src/main/java/org/tron/core/metrics/MetricsUtil.java +++ b/framework/src/main/java/org/tron/core/metrics/MetricsUtil.java @@ -14,6 +14,7 @@ import metrics_influxdb.InfluxdbReporter; import metrics_influxdb.api.protocols.InfluxdbProtocols; import org.tron.common.parameter.CommonParameter; +import org.tron.core.Constant; import org.tron.core.metrics.net.RateInfo; @Slf4j(topic = "metrics") @@ -35,7 +36,8 @@ public static void init() { .filter(MetricFilter.ALL) .skipIdleMetrics(false) .build(); - int interval = CommonParameter.getInstance().getMetricsReportInterval() * 1000; + int interval = CommonParameter.getInstance().getMetricsReportInterval() + * Constant.ONE_THOUSAND; influxReport.start(interval, TimeUnit.MILLISECONDS); } } 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 298dae4d6fd..d99c6a95e3c 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 @@ -7,6 +7,7 @@ import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import org.tron.core.Constant; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.BlockCapsule.BlockId; import org.tron.core.config.args.Args; @@ -38,7 +39,7 @@ public class BlockMsgHandler implements TronMsgHandler { @Autowired private WitnessProductBlockService witnessProductBlockService; - private int maxBlockSize = BLOCK_SIZE + 1000; + private int maxBlockSize = BLOCK_SIZE + Constant.ONE_THOUSAND; private boolean fastForward = Args.getInstance().isFastForward(); 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 89cdaaf8845..01f9e0b6f66 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 @@ -20,6 +20,7 @@ import org.tron.common.overlay.server.Channel; import org.tron.common.utils.Pair; import org.tron.common.utils.Sha256Hash; +import org.tron.core.Constant; import org.tron.core.capsule.BlockCapsule.BlockId; import org.tron.core.config.Parameter.NetConstants; import org.tron.core.net.TronNetDelegate; @@ -162,11 +163,11 @@ public String log() { getNodeStatistics().pingMessageLatency.getCount(), getNodeStatistics().pingMessageLatency.getMax(), - getNodeStatistics().pingMessageLatency.getAvrg(), + getNodeStatistics().pingMessageLatency.getAvg(), getNodeStatistics().pingMessageLatency.getMin(), getNodeStatistics().pingMessageLatency.getLast(), - (now - getStartTime()) / 1000, + (now - getStartTime()) / Constant.ONE_THOUSAND, fastForwardBlock != null ? fastForwardBlock.getNum() : blockBothHave.getNum(), isNeedSyncFromPeer(), isNeedSyncFromUs(), @@ -174,7 +175,8 @@ public String log() { !syncBlockToFetch.isEmpty() ? syncBlockToFetch.peek().getNum() : -1, syncBlockRequested.size(), remainNum, - syncChainRequested == null ? 0 : (now - syncChainRequested.getValue()) / 1000, + syncChainRequested == null ? 0 : (now - syncChainRequested.getValue()) + / Constant.ONE_THOUSAND, syncBlockInProcess.size()) + nodeStatistics.toString() + "\n"; } diff --git a/framework/src/main/java/org/tron/core/net/service/AdvService.java b/framework/src/main/java/org/tron/core/net/service/AdvService.java index 3fb9336f091..6ee374321cc 100644 --- a/framework/src/main/java/org/tron/core/net/service/AdvService.java +++ b/framework/src/main/java/org/tron/core/net/service/AdvService.java @@ -39,6 +39,11 @@ @Slf4j(topic = "net") @Component public class AdvService { + + private final int MAX_INV_TO_FETCH_CACHE_SIZE = 100_000; + private final int MAX_TRX_CACHE_SIZE = 50_000; + private final int MAX_BLOCK_CACHE_SIZE = 10; + private final int MAX_SPREAD_SIZE = 1_000; @Autowired private TronNetDelegate tronNetDelegate; @@ -48,13 +53,16 @@ public class AdvService { private ConcurrentHashMap invToSpread = new ConcurrentHashMap<>(); private Cache invToFetchCache = CacheBuilder.newBuilder() - .maximumSize(100_000).expireAfterWrite(1, TimeUnit.HOURS).recordStats().build(); + .maximumSize(MAX_INV_TO_FETCH_CACHE_SIZE).expireAfterWrite(1, TimeUnit.HOURS) + .recordStats().build(); private Cache trxCache = CacheBuilder.newBuilder() - .maximumSize(50_000).expireAfterWrite(1, TimeUnit.HOURS).recordStats().build(); + .maximumSize(MAX_TRX_CACHE_SIZE).expireAfterWrite(1, TimeUnit.HOURS) + .recordStats().build(); private Cache blockCache = CacheBuilder.newBuilder() - .maximumSize(10).expireAfterWrite(1, TimeUnit.MINUTES).recordStats().build(); + .maximumSize(MAX_BLOCK_CACHE_SIZE).expireAfterWrite(1, TimeUnit.MINUTES) + .recordStats().build(); private ScheduledExecutorService spreadExecutor = Executors.newSingleThreadScheduledExecutor(); @@ -63,8 +71,6 @@ public class AdvService { @Getter private MessageCount trxCount = new MessageCount(); - private int maxSpreadSize = 1_000; - private boolean fastForward = Args.getInstance().isFastForward(); public void init() { @@ -144,7 +150,7 @@ public void broadcast(Message msg) { return; } - if (invToSpread.size() > maxSpreadSize) { + if (invToSpread.size() > MAX_SPREAD_SIZE) { logger.warn("Drop message, type: {}, ID: {}.", msg.getType(), msg.getMessageId()); return; } 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 0b26fcfeacf..8e011724774 100644 --- a/framework/src/main/java/org/tron/core/services/NodeInfoService.java +++ b/framework/src/main/java/org/tron/core/services/NodeInfoService.java @@ -131,7 +131,7 @@ private void setConnectInfo(NodeInfo nodeInfo) { PeerInfo peerInfo = new PeerInfo(); peerInfo.setHeadBlockWeBothHave(peerConnection.getBlockBothHave().getString()); peerInfo.setActive(peerConnection.isActive()); - peerInfo.setAvgLatency(peerConnection.getNodeStatistics().pingMessageLatency.getAvrg()); + peerInfo.setAvgLatency(peerConnection.getNodeStatistics().pingMessageLatency.getAvg()); peerInfo.setBlockInPorcSize(peerConnection.getSyncBlockInProcess().size()); peerInfo.setConnectTime(peerConnection.getStartTime()); peerInfo.setDisconnectTimes(peerConnection.getNodeStatistics().getDisconnectTimes()); @@ -169,7 +169,7 @@ private void setConnectInfo(NodeInfo nodeInfo) { private void setConfigNodeInfo(NodeInfo nodeInfo) { ConfigNodeInfo configNodeInfo = new ConfigNodeInfo(); configNodeInfo.setCodeVersion(Version.getVersion()); - configNodeInfo.setVersionNum(Version.versionCode); + configNodeInfo.setVersionNum(Version.VERSION_CODE); configNodeInfo.setP2pVersion(String.valueOf(parameter.getNodeP2pVersion())); configNodeInfo.setListenPort(parameter.getNodeListenPort()); configNodeInfo.setDiscoverEnable(parameter.isNodeDiscoveryEnable()); 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 92e3c448719..2d0183f57f6 100755 --- a/framework/src/main/java/org/tron/core/services/RpcApiService.java +++ b/framework/src/main/java/org/tron/core/services/RpcApiService.java @@ -140,6 +140,9 @@ 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.AccountBalanceRequest; +import org.tron.protos.contract.BalanceContract.AccountBalanceResponse; +import org.tron.protos.contract.BalanceContract.BlockBalanceTrace; import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; import org.tron.protos.contract.BalanceContract.TransferContract; import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; @@ -172,7 +175,6 @@ public class RpcApiService implements Service { public static final String CONTRACT_VALIDATE_EXCEPTION = "ContractValidateException: {}"; - public static final String CONTRACT_VALIDATE_ERROR = "contract validate error : "; private static final String EXCEPTION_CAUGHT = "exception caught"; private static final long BLOCK_LIMIT_NUM = 100; private static final long TRANSACTION_LIMIT_NUM = 1000; @@ -295,7 +297,7 @@ private void callContract(TriggerSmartContract request, trxExtBuilder.setResult(retBuilder); } catch (ContractValidateException | VMIllegalException e) { retBuilder.setResult(false).setCode(response_code.CONTRACT_VALIDATE_ERROR) - .setMessage(ByteString.copyFromUtf8(CONTRACT_VALIDATE_ERROR + e.getMessage())); + .setMessage(ByteString.copyFromUtf8(Wallet.CONTRACT_VALIDATE_ERROR + e.getMessage())); trxExtBuilder.setResult(retBuilder); logger.warn(CONTRACT_VALIDATE_EXCEPTION, e.getMessage()); } catch (RuntimeException e) { @@ -618,16 +620,7 @@ public void listExchanges(EmptyMessage request, @Override public void getTransactionCountByBlockNum(NumberMessage request, StreamObserver responseObserver) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - try { - Block block = chainBaseManager.getBlockByNum(request.getNum()).getInstance(); - builder.setNum(block.getTransactionsCount()); - } catch (StoreException e) { - logger.error(e.getMessage()); - builder.setNum(-1); - } - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); + getTransactionCountByBlockNumCommon(request, responseObserver); } @Override @@ -661,47 +654,24 @@ public void getTransactionInfoById(BytesMessage request, @Override public void generateAddress(EmptyMessage request, StreamObserver responseObserver) { - SignInterface cryptoEngine = SignUtils.getGeneratedRandomSign(Utils.getRandom(), - Args.getInstance().isECKeyCryptoEngine()); - byte[] priKey = cryptoEngine.getPrivateKey(); - byte[] address = cryptoEngine.getAddress(); - String addressStr = StringUtil.encode58Check(address); - String priKeyStr = Hex.encodeHexString(priKey); - AddressPrKeyPairMessage.Builder builder = AddressPrKeyPairMessage.newBuilder(); - builder.setAddress(addressStr); - builder.setPrivateKey(priKeyStr); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); + generateAddressCommon(request, responseObserver); } @Override public void getRewardInfo(BytesMessage request, StreamObserver responseObserver) { - try { - long value = dbManager.getDelegationService().queryReward(request.getValue().toByteArray()); - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(value); - responseObserver.onNext(builder.build()); - } catch (Exception e) { - responseObserver.onError(e); - } - responseObserver.onCompleted(); + getRewardInfoCommon(request, responseObserver); } @Override public void getBrokerageInfo(BytesMessage request, StreamObserver responseObserver) { - try { - long cycle = dbManager.getDynamicPropertiesStore().getCurrentCycleNumber(); - long value = dbManager.getDelegationStore() - .getBrokerage(cycle, request.getValue().toByteArray()); - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(value); - responseObserver.onNext(builder.build()); - } catch (Exception e) { - responseObserver.onError(e); - } - responseObserver.onCompleted(); + getBrokerageInfoCommon(request, responseObserver); + } + + @Override + public void getBurnTrx(EmptyMessage request, StreamObserver responseObserver) { + getBurnTrxCommon(request, responseObserver); } @Override @@ -887,7 +857,7 @@ public void getMarketPriceByPair(MarketOrderPair request, } @Override - public void getMarketOrderListByPair(MarketOrderPair request, + public void getMarketOrderListByPair(org.tron.protos.Protocol.MarketOrderPair request, StreamObserver responseObserver) { try { MarketOrderList orderPairList = wallet @@ -990,6 +960,34 @@ public void getAccountById(Account req, StreamObserver responseObserver responseObserver.onCompleted(); } + /** + * + */ + public void getAccountBalance(AccountBalanceRequest request, + StreamObserver responseObserver) { + try { + AccountBalanceResponse accountBalanceResponse = wallet.getAccountBalance(request); + responseObserver.onNext(accountBalanceResponse); + responseObserver.onCompleted(); + } catch (Exception e) { + responseObserver.onError(e); + } + } + + /** + * + */ + public void getBlockBalanceTrace(BlockBalanceTrace.BlockIdentifier request, + StreamObserver responseObserver) { + try { + BlockBalanceTrace blockBalanceTrace = wallet.getBlockBalance(request); + responseObserver.onNext(blockBalanceTrace); + responseObserver.onCompleted(); + } catch (Exception e) { + responseObserver.onError(e); + } + } + @Override public void createTransaction(TransferContract request, StreamObserver responseObserver) { @@ -1022,7 +1020,8 @@ private void createTransactionExtention(Message request, ContractType contractTy retBuilder.setResult(true).setCode(response_code.SUCCESS); } catch (ContractValidateException e) { retBuilder.setResult(false).setCode(response_code.CONTRACT_VALIDATE_ERROR) - .setMessage(ByteString.copyFromUtf8(CONTRACT_VALIDATE_ERROR + e.getMessage())); + .setMessage(ByteString + .copyFromUtf8(Wallet.CONTRACT_VALIDATE_ERROR + e.getMessage())); logger.debug(CONTRACT_VALIDATE_EXCEPTION, e.getMessage()); } catch (Exception e) { retBuilder.setResult(false).setCode(response_code.OTHER_ERROR) @@ -1582,16 +1581,7 @@ public void getBlockByNum2(NumberMessage request, @Override public void getTransactionCountByBlockNum(NumberMessage request, StreamObserver responseObserver) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - try { - Block block = chainBaseManager.getBlockByNum(request.getNum()).getInstance(); - builder.setNum(block.getTransactionsCount()); - } catch (StoreException e) { - logger.error(e.getMessage()); - builder.setNum(-1); - } - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); + getTransactionCountByBlockNumCommon(request, responseObserver); } @Override @@ -1908,7 +1898,8 @@ private void callContract(TriggerSmartContract request, trxExtBuilder.setResult(retBuilder); } catch (ContractValidateException | VMIllegalException e) { retBuilder.setResult(false).setCode(response_code.CONTRACT_VALIDATE_ERROR) - .setMessage(ByteString.copyFromUtf8(CONTRACT_VALIDATE_ERROR + e.getMessage())); + .setMessage(ByteString.copyFromUtf8(Wallet + .CONTRACT_VALIDATE_ERROR + e.getMessage())); trxExtBuilder.setResult(retBuilder); logger.warn(CONTRACT_VALIDATE_EXCEPTION, e.getMessage()); } catch (RuntimeException e) { @@ -2013,17 +2004,7 @@ public void getChainParameters(EmptyMessage request, @Override public void generateAddress(EmptyMessage request, StreamObserver responseObserver) { - SignInterface cryptoEngine = SignUtils.getGeneratedRandomSign(Utils.getRandom(), - Args.getInstance().isECKeyCryptoEngine()); - byte[] priKey = cryptoEngine.getPrivateKey(); - byte[] address = cryptoEngine.getAddress(); - String addressStr = StringUtil.encode58Check(address); - String priKeyStr = Hex.encodeHexString(priKey); - AddressPrKeyPairMessage.Builder builder = AddressPrKeyPairMessage.newBuilder(); - builder.setAddress(addressStr); - builder.setPrivateKey(priKeyStr); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); + generateAddressCommon(request, responseObserver); } @Override @@ -2091,7 +2072,8 @@ public void createShieldedTransaction(PrivateParameters request, retBuilder.setResult(true).setCode(response_code.SUCCESS); } catch (ContractValidateException | ZksnarkException e) { retBuilder.setResult(false).setCode(response_code.CONTRACT_VALIDATE_ERROR) - .setMessage(ByteString.copyFromUtf8(CONTRACT_VALIDATE_ERROR + e.getMessage())); + .setMessage(ByteString + .copyFromUtf8(Wallet.CONTRACT_VALIDATE_ERROR + e.getMessage())); logger.debug(CONTRACT_VALIDATE_EXCEPTION, e.getMessage()); } catch (Exception e) { retBuilder.setResult(false).setCode(response_code.OTHER_ERROR) @@ -2121,7 +2103,8 @@ public void createShieldedTransactionWithoutSpendAuthSig(PrivateParametersWithou retBuilder.setResult(true).setCode(response_code.SUCCESS); } catch (ContractValidateException | ZksnarkException e) { retBuilder.setResult(false).setCode(response_code.CONTRACT_VALIDATE_ERROR) - .setMessage(ByteString.copyFromUtf8(CONTRACT_VALIDATE_ERROR + e.getMessage())); + .setMessage(ByteString + .copyFromUtf8(Wallet.CONTRACT_VALIDATE_ERROR + e.getMessage())); logger.debug(CONTRACT_VALIDATE_EXCEPTION, e.getMessage()); } catch (Exception e) { retBuilder.setResult(false).setCode(response_code.OTHER_ERROR) @@ -2522,31 +2505,18 @@ public void getTriggerInputForShieldedTRC20Contract( @Override public void getRewardInfo(BytesMessage request, StreamObserver responseObserver) { - try { - long value = dbManager.getDelegationService().queryReward(request.getValue().toByteArray()); - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(value); - responseObserver.onNext(builder.build()); - } catch (Exception e) { - responseObserver.onError(e); - } - responseObserver.onCompleted(); + getRewardInfoCommon(request, responseObserver); } @Override public void getBrokerageInfo(BytesMessage request, StreamObserver responseObserver) { - try { - long cycle = dbManager.getDynamicPropertiesStore().getCurrentCycleNumber(); - long value = dbManager.getDelegationStore() - .getBrokerage(cycle, request.getValue().toByteArray()); - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(value); - responseObserver.onNext(builder.build()); - } catch (Exception e) { - responseObserver.onError(e); - } - responseObserver.onCompleted(); + getBrokerageInfoCommon(request, responseObserver); + } + + @Override + public void getBurnTrx(EmptyMessage request, StreamObserver responseObserver) { + getBurnTrxCommon(request, responseObserver); } @Override @@ -2668,7 +2638,76 @@ public void getStatsInfo(EmptyMessage request, responseObserver.onNext(metricsApiService.getMetricProtoInfo()); responseObserver.onCompleted(); } + } + + public void generateAddressCommon(EmptyMessage request, + StreamObserver responseObserver) { + SignInterface cryptoEngine = SignUtils.getGeneratedRandomSign(Utils.getRandom(), + Args.getInstance().isECKeyCryptoEngine()); + byte[] priKey = cryptoEngine.getPrivateKey(); + byte[] address = cryptoEngine.getAddress(); + String addressStr = StringUtil.encode58Check(address); + String priKeyStr = Hex.encodeHexString(priKey); + AddressPrKeyPairMessage.Builder builder = AddressPrKeyPairMessage.newBuilder(); + builder.setAddress(addressStr); + builder.setPrivateKey(priKeyStr); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } + + public void getRewardInfoCommon(BytesMessage request, + StreamObserver responseObserver) { + try { + long value = dbManager.getMortgageService().queryReward(request.getValue().toByteArray()); + NumberMessage.Builder builder = NumberMessage.newBuilder(); + builder.setNum(value); + responseObserver.onNext(builder.build()); + } catch (Exception e) { + responseObserver.onError(e); + } + responseObserver.onCompleted(); + } + public void getBurnTrxCommon(EmptyMessage request, + StreamObserver responseObserver) { + try { + long value = dbManager.getDynamicPropertiesStore().getBurnTrxAmount(); + NumberMessage.Builder builder = NumberMessage.newBuilder(); + builder.setNum(value); + responseObserver.onNext(builder.build()); + } catch (Exception e) { + responseObserver.onError(e); + } + responseObserver.onCompleted(); + } + + public void getBrokerageInfoCommon(BytesMessage request, + StreamObserver responseObserver) { + try { + long cycle = dbManager.getDynamicPropertiesStore().getCurrentCycleNumber(); + long value = dbManager.getDelegationStore() + .getBrokerage(cycle, request.getValue().toByteArray()); + NumberMessage.Builder builder = NumberMessage.newBuilder(); + builder.setNum(value); + responseObserver.onNext(builder.build()); + } catch (Exception e) { + responseObserver.onError(e); + } + responseObserver.onCompleted(); + } + public void getTransactionCountByBlockNumCommon(NumberMessage request, + StreamObserver responseObserver) { + NumberMessage.Builder builder = NumberMessage.newBuilder(); + try { + Block block = chainBaseManager.getBlockByNum(request.getNum()).getInstance(); + builder.setNum(block.getTransactionsCount()); + } catch (StoreException e) { + logger.error(e.getMessage()); + builder.setNum(-1); + } + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); } + } diff --git a/framework/src/main/java/org/tron/core/services/filter/HttpInterceptor.java b/framework/src/main/java/org/tron/core/services/filter/HttpInterceptor.java index ff69471ea84..4401f18cebf 100644 --- a/framework/src/main/java/org/tron/core/services/filter/HttpInterceptor.java +++ b/framework/src/main/java/org/tron/core/services/filter/HttpInterceptor.java @@ -15,6 +15,8 @@ public class HttpInterceptor implements Filter { private String endpoint; + private final int HTTP_NOT_FOUND = 404; + private final int HTTP_SUCCESS = 200; @Override public void init(FilterConfig filterConfig) { @@ -32,7 +34,7 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha HttpServletResponse resp = (HttpServletResponse) response; - if (resp.getStatus() != 404) { // correct endpoint + if (resp.getStatus() != HTTP_NOT_FOUND) { // correct endpoint String endpointQPS = MetricsKey.NET_API_DETAIL_QPS + endpoint; MetricsUtil.meterMark(MetricsKey.NET_API_QPS); MetricsUtil.meterMark(endpointQPS); @@ -43,7 +45,7 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha reposeContentSize); MetricsUtil.meterMark(endpointOutTraffic, reposeContentSize); - if (resp.getStatus() != 200) { //http fail + if (resp.getStatus() != HTTP_SUCCESS) { //http fail String endpointFailQPS = MetricsKey.NET_API_DETAIL_FAIL_QPS + endpoint; MetricsUtil.meterMark(MetricsKey.NET_API_FAIL_QPS); MetricsUtil.meterMark(endpointFailQPS); diff --git a/framework/src/main/java/org/tron/core/services/http/CreateAddressServlet.java b/framework/src/main/java/org/tron/core/services/http/CreateAddressServlet.java index 437a9efa2f5..7e52abddf6a 100644 --- a/framework/src/main/java/org/tron/core/services/http/CreateAddressServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/CreateAddressServlet.java @@ -43,10 +43,9 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String input = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(input); - boolean visible = Util.getVisiblePost(input); + PostParams params = PostParams.getPostParams(request); + boolean visible = params.isVisible(); + String input = params.getParams(); if (visible) { input = covertStringToHex(input); } diff --git a/framework/src/main/java/org/tron/core/services/http/CreateShieldedContractParametersWithoutAskServlet.java b/framework/src/main/java/org/tron/core/services/http/CreateShieldedContractParametersWithoutAskServlet.java index 37210b8cd31..80a8ba53bbc 100644 --- a/framework/src/main/java/org/tron/core/services/http/CreateShieldedContractParametersWithoutAskServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/CreateShieldedContractParametersWithoutAskServlet.java @@ -22,16 +22,14 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String contract = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(contract); - boolean visible = Util.getVisiblePost(contract); + PostParams params = PostParams.getPostParams(request); PrivateShieldedTRC20ParametersWithoutAsk.Builder build = PrivateShieldedTRC20ParametersWithoutAsk.newBuilder(); - JsonFormat.merge(contract, build, visible); + JsonFormat.merge(params.getParams(), build, params.isVisible()); ShieldedTRC20Parameters shieldedTRC20Parameters = wallet .createShieldedContractParametersWithoutAsk(build.build()); - response.getWriter().println(JsonFormat.printToString(shieldedTRC20Parameters, visible)); + response.getWriter().println(JsonFormat + .printToString(shieldedTRC20Parameters, params.isVisible())); } catch (Exception e) { Util.processError(e, response); } 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 8769d0c36eb..944379c8f42 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 @@ -228,6 +228,8 @@ public class FullNodeHttpApiService implements Service { @Autowired private BroadcastHexServlet broadcastHexServlet; @Autowired + private GetBurnTrxServlet getBurnTrxServlet; + @Autowired private GetBrokerageServlet getBrokerageServlet; @Autowired private GetRewardServlet getRewardServlet; @@ -268,6 +270,12 @@ public class FullNodeHttpApiService implements Service { @Autowired private GetMarketPairListServlet getMarketPairListServlet; + @Autowired + private GetAccountBalanceServlet getAccountBalanceServlet; + + @Autowired + private GetBlockBalanceServlet getBlockBalanceServlet; + @Autowired private LiteFnQueryHttpFilter liteFnQueryHttpFilter; @@ -505,6 +513,12 @@ public void start() { context.addServlet(new ServletHolder(getMarketPairListServlet), "/wallet/getmarketpairlist"); + context.addServlet(new ServletHolder(getAccountBalanceServlet), + "/wallet/getaccountbalance"); + context.addServlet(new ServletHolder(getBlockBalanceServlet), + "/wallet/getblockbalance"); + context.addServlet(new ServletHolder(getBurnTrxServlet), "/wallet/getburntrx"); + int maxHttpConnectNumber = Args.getInstance().getMaxHttpConnectNumber(); if (maxHttpConnectNumber > 0) { server.addBean(new ConnectionLimit(maxHttpConnectNumber, server)); @@ -513,7 +527,7 @@ public void start() { // filters the specified APIs // when node is lite fullnode and openHistoryQueryWhenLiteFN is false context.addFilter(new FilterHolder(liteFnQueryHttpFilter), "/*", - EnumSet.allOf(DispatcherType.class)); + EnumSet.allOf(DispatcherType.class)); // filter ServletHandler handler = new ServletHandler(); diff --git a/framework/src/main/java/org/tron/core/services/http/GetAccountBalanceServlet.java b/framework/src/main/java/org/tron/core/services/http/GetAccountBalanceServlet.java new file mode 100644 index 00000000000..159c3899666 --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/http/GetAccountBalanceServlet.java @@ -0,0 +1,44 @@ +package org.tron.core.services.http; + +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.Account; +import org.tron.protos.contract.BalanceContract; + + +@Component +@Slf4j(topic = "API") +public class GetAccountBalanceServlet extends RateLimiterServlet { + + @Autowired + private Wallet wallet; + + protected void doPost(HttpServletRequest request, HttpServletResponse response) { + try { + PostParams params = PostParams.getPostParams(request); + BalanceContract.AccountBalanceRequest.Builder builder + = BalanceContract.AccountBalanceRequest.newBuilder(); + JsonFormat.merge(params.getParams(), builder, params.isVisible()); + fillResponse(params.isVisible(), builder.build(), response); + } catch (Exception e) { + Util.processError(e, response); + } + } + + private void fillResponse(boolean visible, + BalanceContract.AccountBalanceRequest request, + HttpServletResponse response) + throws Exception { + BalanceContract.AccountBalanceResponse reply = wallet.getAccountBalance(request); + if (reply != null) { + response.getWriter().println(JsonFormat.printToString(reply, visible)); + } else { + response.getWriter().println("{}"); + } + } +} diff --git a/framework/src/main/java/org/tron/core/services/http/GetBlockBalanceServlet.java b/framework/src/main/java/org/tron/core/services/http/GetBlockBalanceServlet.java new file mode 100644 index 00000000000..0fc3256899c --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/http/GetBlockBalanceServlet.java @@ -0,0 +1,43 @@ +package org.tron.core.services.http; + +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.Account; +import org.tron.protos.contract.BalanceContract.BlockBalanceTrace; + + +@Component +@Slf4j(topic = "API") +public class GetBlockBalanceServlet extends RateLimiterServlet { + + @Autowired + private Wallet wallet; + + protected void doPost(HttpServletRequest request, HttpServletResponse response) { + try { + PostParams params = PostParams.getPostParams(request); + BlockBalanceTrace.BlockIdentifier.Builder builder = BlockBalanceTrace.BlockIdentifier + .newBuilder(); + JsonFormat.merge(params.getParams(), builder, params.isVisible()); + fillResponse(params.isVisible(), builder.build(), response); + } catch (Exception e) { + Util.processError(e, response); + } + } + + private void fillResponse(boolean visible, BlockBalanceTrace.BlockIdentifier request, + HttpServletResponse response) + throws Exception { + BlockBalanceTrace reply = wallet.getBlockBalance(request); + if (reply != null) { + response.getWriter().println(JsonFormat.printToString(reply, visible)); + } else { + response.getWriter().println("{}"); + } + } +} diff --git a/framework/src/main/java/org/tron/core/services/http/GetBurnTrxServlet.java b/framework/src/main/java/org/tron/core/services/http/GetBurnTrxServlet.java new file mode 100644 index 00000000000..e574affff6b --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/http/GetBurnTrxServlet.java @@ -0,0 +1,36 @@ +package org.tron.core.services.http; + +import java.io.IOException; +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.db.Manager; + + +@Component +@Slf4j(topic = "API") +public class GetBurnTrxServlet extends RateLimiterServlet { + + @Autowired + private Manager manager; + + protected void doGet(HttpServletRequest request, HttpServletResponse response) { + try { + long value = manager.getDynamicPropertiesStore().getBurnTrxAmount(); + response.getWriter().println("{\"burnTrxAmount\": " + value + "}"); + } catch (Exception e) { + logger.error("", e); + try { + response.getWriter().println(Util.printErrorMsg(e)); + } catch (IOException ioe) { + logger.debug("IOException: {}", ioe.getMessage()); + } + } + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) { + doGet(request, response); + } +} diff --git a/framework/src/main/java/org/tron/core/services/http/GetContractInfoServlet.java b/framework/src/main/java/org/tron/core/services/http/GetContractInfoServlet.java index 0761594376c..32aabca5eb8 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetContractInfoServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetContractInfoServlet.java @@ -45,10 +45,9 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String input = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(input); - boolean visible = Util.getVisiblePost(input); + PostParams params = PostParams.getPostParams(request); + String input = params.getParams(); + boolean visible = params.isVisible(); if (visible) { JSONObject jsonObject = JSONObject.parseObject(input); String value = jsonObject.getString(VALUE); diff --git a/framework/src/main/java/org/tron/core/services/http/GetDelegatedResourceServlet.java b/framework/src/main/java/org/tron/core/services/http/GetDelegatedResourceServlet.java index 930af3a2bf6..5787aba3c93 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetDelegatedResourceServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetDelegatedResourceServlet.java @@ -39,13 +39,10 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String input = - request.getReader().lines().collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(input); - boolean visible = Util.getVisiblePost(input); + PostParams params = PostParams.getPostParams(request); DelegatedResourceMessage.Builder build = DelegatedResourceMessage.newBuilder(); - JsonFormat.merge(input, build, visible); - fillResponse(visible, build.getFromAddress(), build.getToAddress(), response); + JsonFormat.merge(params.getParams(), build, params.isVisible()); + fillResponse(params.isVisible(), build.getFromAddress(), build.getToAddress(), response); } catch (Exception e) { Util.processError(e, response); } diff --git a/framework/src/main/java/org/tron/core/services/http/GetMarketOrderListByPairServlet.java b/framework/src/main/java/org/tron/core/services/http/GetMarketOrderListByPairServlet.java index 20900019840..963ea880033 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetMarketOrderListByPairServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetMarketOrderListByPairServlet.java @@ -31,13 +31,8 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { buyTokenId = Util.getHexString(buyTokenId); } - MarketOrderList reply = wallet.getMarketOrderListByPair(ByteArray.fromHexString(sellTokenId), - ByteArray.fromHexString(buyTokenId)); - if (reply != null) { - response.getWriter().println(JsonFormat.printToString(reply, visible)); - } else { - response.getWriter().println("{}"); - } + fillResponse(visible, ByteArray.fromHexString(sellTokenId), + ByteArray.fromHexString(buyTokenId), response); } catch (Exception e) { Util.processError(e, response); } @@ -53,15 +48,20 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) MarketOrderPair.Builder build = MarketOrderPair.newBuilder(); JsonFormat.merge(input, build, visible); - MarketOrderList reply = wallet.getMarketOrderListByPair(build.getSellTokenId().toByteArray(), - build.getBuyTokenId().toByteArray()); - if (reply != null) { - response.getWriter().println(JsonFormat.printToString(reply, visible)); - } else { - response.getWriter().println("{}"); - } + fillResponse(visible, build.getSellTokenId().toByteArray(), + build.getBuyTokenId().toByteArray(), response); } catch (Exception e) { Util.processError(e, response); } } + + private void fillResponse(boolean visible, byte[] sellTokenId, byte[] buyTokenId, + HttpServletResponse response) throws Exception { + MarketOrderList reply = wallet.getMarketOrderListByPair(sellTokenId, buyTokenId); + if (reply != null) { + response.getWriter().println(JsonFormat.printToString(reply, visible)); + } else { + response.getWriter().println("{}"); + } + } } diff --git a/framework/src/main/java/org/tron/core/services/http/GetMarketPairListServlet.java b/framework/src/main/java/org/tron/core/services/http/GetMarketPairListServlet.java index 6653f2db762..6cb9c5d868f 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetMarketPairListServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetMarketPairListServlet.java @@ -20,12 +20,7 @@ public class GetMarketPairListServlet extends RateLimiterServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) { try { boolean visible = Util.getVisible(request); - MarketOrderPairList reply = wallet.getMarketPairList(); - if (reply != null) { - response.getWriter().println(JsonFormat.printToString(reply, visible)); - } else { - response.getWriter().println("{}"); - } + fillResponse(visible, response); } catch (Exception e) { Util.processError(e, response); } @@ -41,15 +36,19 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) if (!"".equals(input)) { visible = Util.getVisiblePost(input); } - - MarketOrderPairList reply = wallet.getMarketPairList(); - if (reply != null) { - response.getWriter().println(JsonFormat.printToString(reply, visible)); - } else { - response.getWriter().println("{}"); - } + fillResponse(visible, response); } catch (Exception e) { Util.processError(e, response); } } + + private void fillResponse(boolean visible, HttpServletResponse response) + throws Exception { + MarketOrderPairList reply = wallet.getMarketPairList(); + if (reply != null) { + response.getWriter().println(JsonFormat.printToString(reply, visible)); + } else { + response.getWriter().println("{}"); + } + } } diff --git a/framework/src/main/java/org/tron/core/services/http/GetMarketPriceByPairServlet.java b/framework/src/main/java/org/tron/core/services/http/GetMarketPriceByPairServlet.java index 01db32a1fd0..b6d31e10936 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetMarketPriceByPairServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetMarketPriceByPairServlet.java @@ -31,13 +31,8 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { buyTokenId = Util.getHexString(buyTokenId); } - MarketPriceList reply = wallet.getMarketPriceByPair(ByteArray.fromHexString(sellTokenId), - ByteArray.fromHexString(buyTokenId)); - if (reply != null) { - response.getWriter().println(JsonFormat.printToString(reply, visible)); - } else { - response.getWriter().println("{}"); - } + fillResponse(visible, ByteArray.fromHexString(sellTokenId), + ByteArray.fromHexString(buyTokenId), response); } catch (Exception e) { Util.processError(e, response); } @@ -53,15 +48,20 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) MarketOrderPair.Builder build = MarketOrderPair.newBuilder(); JsonFormat.merge(input, build, visible); - MarketPriceList reply = wallet.getMarketPriceByPair(build.getSellTokenId().toByteArray(), - build.getBuyTokenId().toByteArray()); - if (reply != null) { - response.getWriter().println(JsonFormat.printToString(reply, visible)); - } else { - response.getWriter().println("{}"); - } + fillResponse(visible, build.getSellTokenId().toByteArray(), + build.getBuyTokenId().toByteArray(), response); } catch (Exception e) { Util.processError(e, response); } } -} + + private void fillResponse(boolean visible, byte[] sellTokenId, byte[] buyTokenId, + HttpServletResponse response) throws Exception { + MarketPriceList reply = wallet.getMarketPriceByPair(sellTokenId, buyTokenId); + if (reply != null) { + response.getWriter().println(JsonFormat.printToString(reply, visible)); + } else { + response.getWriter().println("{}"); + } + } +} \ No newline at end of file diff --git a/framework/src/main/java/org/tron/core/services/http/GetPaginatedAssetIssueListServlet.java b/framework/src/main/java/org/tron/core/services/http/GetPaginatedAssetIssueListServlet.java index dd4e00a1657..0246979e279 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetPaginatedAssetIssueListServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetPaginatedAssetIssueListServlet.java @@ -1,5 +1,6 @@ package org.tron.core.services.http; +import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; @@ -9,7 +10,6 @@ import org.tron.api.GrpcAPI.PaginatedMessage; import org.tron.core.Wallet; - @Component @Slf4j(topic = "API") public class GetPaginatedAssetIssueListServlet extends RateLimiterServlet { @@ -22,12 +22,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { boolean visible = Util.getVisible(request); long offset = Long.parseLong(request.getParameter("offset")); long limit = Long.parseLong(request.getParameter("limit")); - AssetIssueList reply = wallet.getAssetIssueList(offset, limit); - if (reply != null) { - response.getWriter().println(JsonFormat.printToString(reply, visible)); - } else { - response.getWriter().println("{}"); - } + fillResponse(offset, limit, visible, response); } catch (Exception e) { Util.processError(e, response); } @@ -40,14 +35,19 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) boolean visible = params.isVisible(); PaginatedMessage.Builder build = PaginatedMessage.newBuilder(); JsonFormat.merge(input, build, visible); - AssetIssueList reply = wallet.getAssetIssueList(build.getOffset(), build.getLimit()); - if (reply != null) { - response.getWriter().println(JsonFormat.printToString(reply, visible)); - } else { - response.getWriter().println("{}"); - } + fillResponse(build.getOffset(), build.getLimit(), visible, response); } catch (Exception e) { Util.processError(e, response); } } + + private void fillResponse(long offset, long limit, boolean visible, HttpServletResponse response) + throws IOException { + AssetIssueList reply = wallet.getAssetIssueList(offset, limit); + if (reply != null) { + response.getWriter().println(JsonFormat.printToString(reply, visible)); + } else { + response.getWriter().println("{}"); + } + } } diff --git a/framework/src/main/java/org/tron/core/services/http/GetPaginatedExchangeListServlet.java b/framework/src/main/java/org/tron/core/services/http/GetPaginatedExchangeListServlet.java index ea53d647197..28018497952 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetPaginatedExchangeListServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetPaginatedExchangeListServlet.java @@ -1,5 +1,6 @@ package org.tron.core.services.http; +import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; @@ -9,7 +10,6 @@ import org.tron.api.GrpcAPI.PaginatedMessage; import org.tron.core.Wallet; - @Component @Slf4j(topic = "API") public class GetPaginatedExchangeListServlet extends RateLimiterServlet { @@ -22,12 +22,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { boolean visible = Util.getVisible(request); long offset = Long.parseLong(request.getParameter("offset")); long limit = Long.parseLong(request.getParameter("limit")); - ExchangeList reply = wallet.getPaginatedExchangeList(offset, limit); - if (reply != null) { - response.getWriter().println(JsonFormat.printToString(reply, visible)); - } else { - response.getWriter().println("{}"); - } + fillResponse(offset, limit, visible, response); } catch (Exception e) { Util.processError(e, response); } @@ -38,14 +33,20 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) PostParams params = PostParams.getPostParams(request); PaginatedMessage.Builder build = PaginatedMessage.newBuilder(); JsonFormat.merge(params.getParams(), build, params.isVisible()); - ExchangeList reply = wallet.getPaginatedExchangeList(build.getOffset(), build.getLimit()); - if (reply != null) { - response.getWriter().println(JsonFormat.printToString(reply, params.isVisible())); - } else { - response.getWriter().println("{}"); - } + fillResponse(build.getOffset(), build.getLimit(), params.isVisible(), response); } catch (Exception e) { Util.processError(e, response); } } + + private void fillResponse(long offset, long limit, boolean visible, HttpServletResponse response) + throws IOException { + ExchangeList reply = wallet.getPaginatedExchangeList(offset, limit); + if (reply != null) { + response.getWriter().println(JsonFormat.printToString(reply, visible)); + } else { + response.getWriter().println("{}"); + } + } + } diff --git a/framework/src/main/java/org/tron/core/services/http/GetPaginatedProposalListServlet.java b/framework/src/main/java/org/tron/core/services/http/GetPaginatedProposalListServlet.java index ca290c6666d..11b2c57ff48 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetPaginatedProposalListServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetPaginatedProposalListServlet.java @@ -1,5 +1,6 @@ package org.tron.core.services.http; +import java.io.IOException; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -10,7 +11,6 @@ import org.tron.api.GrpcAPI.ProposalList; import org.tron.core.Wallet; - @Component @Slf4j(topic = "API") public class GetPaginatedProposalListServlet extends RateLimiterServlet { @@ -23,12 +23,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { boolean visible = Util.getVisible(request); long offset = Long.parseLong(request.getParameter("offset")); long limit = Long.parseLong(request.getParameter("limit")); - ProposalList reply = wallet.getPaginatedProposalList(offset, limit); - if (reply != null) { - response.getWriter().println(JsonFormat.printToString(reply, visible)); - } else { - response.getWriter().println("{}"); - } + fillResponse(offset, limit, visible, response); } catch (Exception e) { Util.processError(e, response); } @@ -42,14 +37,19 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) boolean visible = Util.getVisiblePost(input); PaginatedMessage.Builder build = PaginatedMessage.newBuilder(); JsonFormat.merge(input, build, visible); - ProposalList reply = wallet.getPaginatedProposalList(build.getOffset(), build.getLimit()); - if (reply != null) { - response.getWriter().println(JsonFormat.printToString(reply, visible)); - } else { - response.getWriter().println("{}"); - } + fillResponse(build.getOffset(), build.getLimit(), visible, response); } catch (Exception e) { Util.processError(e, response); } } + + private void fillResponse(long offset, long limit, boolean visible, HttpServletResponse response) + throws IOException { + ProposalList reply = wallet.getPaginatedProposalList(offset, limit); + if (reply != null) { + response.getWriter().println(JsonFormat.printToString(reply, visible)); + } else { + response.getWriter().println("{}"); + } + } } diff --git a/framework/src/main/java/org/tron/core/services/http/GetProposalByIdServlet.java b/framework/src/main/java/org/tron/core/services/http/GetProposalByIdServlet.java index 83987872b99..a903a5b4920 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetProposalByIdServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetProposalByIdServlet.java @@ -2,6 +2,8 @@ import com.alibaba.fastjson.JSONObject; import com.google.protobuf.ByteString; +import java.io.IOException; +import java.util.HashMap; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -25,12 +27,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { boolean visible = Util.getVisible(request); String input = request.getParameter("id"); long id = new Long(input); - Proposal reply = wallet.getProposalById(ByteString.copyFrom(ByteArray.fromLong(id))); - if (reply != null) { - response.getWriter().println(JsonFormat.printToString(reply, visible)); - } else { - response.getWriter().println("{}"); - } + fillResponse(ByteString.copyFrom(ByteArray.fromLong(id)), visible, response); } catch (Exception e) { Util.processError(e, response); } @@ -38,20 +35,22 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String input = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(input); - boolean visible = Util.getVisiblePost(input); - JSONObject jsonObject = JSONObject.parseObject(input); + PostParams params = PostParams.getPostParams(request); + JSONObject jsonObject = JSONObject.parseObject(params.getParams()); long id = Util.getJsonLongValue(jsonObject, "id", true); - Proposal reply = wallet.getProposalById(ByteString.copyFrom(ByteArray.fromLong(id))); - if (reply != null) { - response.getWriter().println(JsonFormat.printToString(reply, visible)); - } else { - response.getWriter().println("{}"); - } + fillResponse(ByteString.copyFrom(ByteArray.fromLong(id)), params.isVisible(), response); } catch (Exception e) { Util.processError(e, response); } } + + private void fillResponse(ByteString proposalId, boolean visible, HttpServletResponse response) + throws IOException { + Proposal reply = wallet.getProposalById(proposalId); + if (reply != null) { + response.getWriter().println(JsonFormat.printToString(reply, visible)); + } else { + response.getWriter().println("{}"); + } + } } \ No newline at end of file diff --git a/framework/src/main/java/org/tron/core/services/http/GetRewardServlet.java b/framework/src/main/java/org/tron/core/services/http/GetRewardServlet.java index 4a6a25fadc9..d1903a0fb2c 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetRewardServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetRewardServlet.java @@ -21,7 +21,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { long value = 0; byte[] address = Util.getAddress(request); if (address != null) { - value = manager.getDelegationService().queryReward(address); + value = manager.getMortgageService().queryReward(address); } response.getWriter().println("{\"reward\": " + value + "}"); } catch (Exception e) { diff --git a/framework/src/main/java/org/tron/core/services/http/GetSpendingKeyServlet.java b/framework/src/main/java/org/tron/core/services/http/GetSpendingKeyServlet.java index 4bfbbb2cf78..23c274566ca 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetSpendingKeyServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetSpendingKeyServlet.java @@ -28,14 +28,10 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String input = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(input); - boolean visible = Util.getVisiblePost(input); - + PostParams params = PostParams.getPostParams(request); BytesMessage reply = wallet.getSpendingKey(); if (reply != null) { - response.getWriter().println(JsonFormat.printToString(reply, visible)); + response.getWriter().println(JsonFormat.printToString(reply, params.isVisible())); } else { response.getWriter().println("{}"); } diff --git a/framework/src/main/java/org/tron/core/services/http/GetTransactionApprovedListServlet.java b/framework/src/main/java/org/tron/core/services/http/GetTransactionApprovedListServlet.java index a3ec98ed0aa..b225a770c21 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetTransactionApprovedListServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetTransactionApprovedListServlet.java @@ -24,14 +24,11 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String input = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(input); - boolean visible = Util.getVisiblePost(input); - Transaction transaction = Util.packTransaction(input, visible); + PostParams params = PostParams.getPostParams(request); + Transaction transaction = Util.packTransaction(params.getParams(), params.isVisible()); TransactionApprovedList reply = wallet.getTransactionApprovedList(transaction); if (reply != null) { - response.getWriter().println(Util.printTransactionApprovedList(reply, visible)); + response.getWriter().println(Util.printTransactionApprovedList(reply, params.isVisible())); } else { response.getWriter().println("{}"); } diff --git a/framework/src/main/java/org/tron/core/services/http/GetTransactionByIdServlet.java b/framework/src/main/java/org/tron/core/services/http/GetTransactionByIdServlet.java index 5d2a6a7f29d..49343da9070 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetTransactionByIdServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetTransactionByIdServlet.java @@ -33,13 +33,10 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String input = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(input); - boolean visible = Util.getVisiblePost(input); + PostParams params = PostParams.getPostParams(request); BytesMessage.Builder build = BytesMessage.newBuilder(); - JsonFormat.merge(input, build, visible); - fillResponse(build.getValue(), visible, response); + JsonFormat.merge(params.getParams(), build, params.isVisible()); + fillResponse(build.getValue(), params.isVisible(), response); } catch (Exception e) { Util.processError(e, response); } diff --git a/framework/src/main/java/org/tron/core/services/http/GetTransactionCountByBlockNumServlet.java b/framework/src/main/java/org/tron/core/services/http/GetTransactionCountByBlockNumServlet.java index 2908fc9e7dd..e096df507d7 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetTransactionCountByBlockNumServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetTransactionCountByBlockNumServlet.java @@ -29,12 +29,9 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String input = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(input); - boolean visible = Util.getVisiblePost(input); + PostParams params = PostParams.getPostParams(request); NumberMessage.Builder build = NumberMessage.newBuilder(); - JsonFormat.merge(input, build, visible); + JsonFormat.merge(params.getParams(), build, params.isVisible()); fillResponse(build.getNum(), response); } catch (Exception e) { Util.processError(e, response); diff --git a/framework/src/main/java/org/tron/core/services/http/GetTransactionInfoByIdServlet.java b/framework/src/main/java/org/tron/core/services/http/GetTransactionInfoByIdServlet.java index 32cb3b99ed3..580cb4a5b66 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetTransactionInfoByIdServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetTransactionInfoByIdServlet.java @@ -49,15 +49,12 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String input = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(input); - boolean visible = Util.getVisiblePost(input); + PostParams params = PostParams.getPostParams(request); BytesMessage.Builder build = BytesMessage.newBuilder(); - JsonFormat.merge(input, build, visible); + JsonFormat.merge(params.getParams(), build, params.isVisible()); TransactionInfo reply = wallet.getTransactionInfoById(build.getValue()); if (reply != null) { - response.getWriter().println(convertLogAddressToTronAddress(reply, visible)); + response.getWriter().println(convertLogAddressToTronAddress(reply, params.isVisible())); } else { response.getWriter().println("{}"); } diff --git a/framework/src/main/java/org/tron/core/services/http/GetTransactionSignWeightServlet.java b/framework/src/main/java/org/tron/core/services/http/GetTransactionSignWeightServlet.java index f91f5e783af..3ff3368730f 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetTransactionSignWeightServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetTransactionSignWeightServlet.java @@ -24,14 +24,11 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String input = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(input); - boolean visible = Util.getVisiblePost(input); - Transaction transaction = Util.packTransaction(input, visible); + PostParams params = PostParams.getPostParams(request); + Transaction transaction = Util.packTransaction(params.getParams(), params.isVisible()); TransactionSignWeight reply = transactionUtil.getTransactionSignWeight(transaction); if (reply != null) { - response.getWriter().println(Util.printTransactionSignWeight(reply, visible)); + response.getWriter().println(Util.printTransactionSignWeight(reply, params.isVisible())); } else { response.getWriter().println("{}"); } diff --git a/framework/src/main/java/org/tron/core/services/http/GetTriggerInputForShieldedTRC20ContractServlet.java b/framework/src/main/java/org/tron/core/services/http/GetTriggerInputForShieldedTRC20ContractServlet.java index ce1f1036b27..3a0bc4ed282 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetTriggerInputForShieldedTRC20ContractServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetTriggerInputForShieldedTRC20ContractServlet.java @@ -22,16 +22,13 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String input = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(input); - boolean visible = Util.getVisiblePost(input); + PostParams params = PostParams.getPostParams(request); ShieldedTRC20TriggerContractParameters.Builder builder = ShieldedTRC20TriggerContractParameters .newBuilder(); - JsonFormat.merge(input, builder, visible); + JsonFormat.merge(params.getParams(), builder, params.isVisible()); BytesMessage result = wallet.getTriggerInputForShieldedTRC20Contract(builder.build()); - response.getWriter().println(JsonFormat.printToString(result, visible)); + response.getWriter().println(JsonFormat.printToString(result, params.isVisible())); } catch (Exception e) { Util.processError(e, response); } 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 64df818f9b3..99fa55d9241 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 @@ -183,6 +183,9 @@ public class HttpSelfFormatFieldName { AddressFieldNameMap.put("protocol.DelegatedResourceAccountIndex.fromAccounts", 1); AddressFieldNameMap.put("protocol.DelegatedResourceAccountIndex.toAccounts", 1); + AddressFieldNameMap.put("protocol.AccountIdentifier.address", 1); + AddressFieldNameMap.put("protocol.TransactionBalanceTrace.Operation.address", 1); + //***** api.proto ***** //Return NameFieldNameMap.put("protocol.Return.message", 1); diff --git a/framework/src/main/java/org/tron/core/services/http/IsShieldedTRC20ContractNoteSpentServlet.java b/framework/src/main/java/org/tron/core/services/http/IsShieldedTRC20ContractNoteSpentServlet.java index 97b4f412d5d..9e01ec8fda1 100644 --- a/framework/src/main/java/org/tron/core/services/http/IsShieldedTRC20ContractNoteSpentServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/IsShieldedTRC20ContractNoteSpentServlet.java @@ -22,14 +22,11 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String input = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(input); - boolean visible = Util.getVisiblePost(input); + PostParams params = PostParams.getPostParams(request); NfTRC20Parameters.Builder build = NfTRC20Parameters.newBuilder(); - JsonFormat.merge(input, build, visible); + JsonFormat.merge(params.getParams(), build, params.isVisible()); GrpcAPI.NullifierResult result = wallet.isShieldedTRC20ContractNoteSpent(build.build()); - response.getWriter().println(JsonFormat.printToString(result, visible)); + response.getWriter().println(JsonFormat.printToString(result, params.isVisible())); } catch (Exception e) { Util.processError(e, response); } diff --git a/framework/src/main/java/org/tron/core/services/http/IsSpendServlet.java b/framework/src/main/java/org/tron/core/services/http/IsSpendServlet.java index 139db4b158e..46120a6611d 100644 --- a/framework/src/main/java/org/tron/core/services/http/IsSpendServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/IsSpendServlet.java @@ -24,11 +24,9 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String input = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(input); - boolean visible = Util.getVisiblePost(input); - + PostParams postParams = PostParams.getPostParams(request); + boolean visible = postParams.isVisible(); + String input = postParams.getParams(); NoteParameters.Builder build = NoteParameters.newBuilder(); JsonFormat.merge(input, build, visible); diff --git a/framework/src/main/java/org/tron/core/services/http/JsonFormat.java b/framework/src/main/java/org/tron/core/services/http/JsonFormat.java index cdb69d79ff0..c71d8e165e1 100644 --- a/framework/src/main/java/org/tron/core/services/http/JsonFormat.java +++ b/framework/src/main/java/org/tron/core/services/http/JsonFormat.java @@ -30,7 +30,9 @@ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT */ import com.alibaba.fastjson.JSON; +import com.google.common.collect.ImmutableSet; import com.google.protobuf.ByteString; +import com.google.protobuf.Descriptors; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.EnumDescriptor; import com.google.protobuf.Descriptors.EnumValueDescriptor; @@ -48,12 +50,15 @@ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Set; +import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.tron.common.utils.ByteArray; import org.tron.common.utils.Commons; import org.tron.common.utils.StringUtil; +import org.tron.protos.contract.BalanceContract; /** * Provide ascii text parsing and formatting support for proto2 instances. The implementation @@ -77,6 +82,14 @@ public class JsonFormat { private static final String EXPECTED_STRING = "Expected string."; private static final String MISSING_END_QUOTE = "String missing ending quote."; + public static final boolean ALWAYS_OUTPUT_DEFAULT_VALUE_FIELDS = true; + public static final Set> MESSAGES = ImmutableSet.of( + BalanceContract.AccountBalanceResponse.class, + BalanceContract.BlockBalanceTrace.class, + BalanceContract.TransactionBalanceTrace.Operation.class, + BalanceContract.TransactionBalanceTrace.class + ); + /** * Outputs a textual representation of the Protocol Message supplied into the parameter output. * (This representation is the new version of the classic "ProtocolPrinter" output from the @@ -103,7 +116,30 @@ public static void print(UnknownFieldSet fields, Appendable output, boolean self protected static void print(Message message, JsonGenerator generator, boolean selfType) throws IOException { - for (Iterator> iter = message.getAllFields().entrySet() + Map fieldsToPrint = new TreeMap<>(message.getAllFields()); + if (ALWAYS_OUTPUT_DEFAULT_VALUE_FIELDS && MESSAGES.contains(message.getClass())) { + for (FieldDescriptor field : message.getDescriptorForType().getFields()) { + if (field.isOptional()) { + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE + && !message.hasField(field)) { + // Always skip empty optional message fields. If not we will recurse indefinitely if + // a message has itself as a sub-field. + continue; + } + Descriptors.OneofDescriptor oneof = field.getContainingOneof(); + if (oneof != null && !message.hasField(field)) { + // Skip all oneof fields except the one that is actually set + continue; + } + } + if (!fieldsToPrint.containsKey(field)) { + fieldsToPrint.put(field, message.getField(field)); + } + } + } + + //for (Iterator> iter = message.getAllFields().entrySet() + for (Iterator> iter = fieldsToPrint.entrySet() .iterator(); iter.hasNext(); ) { Map.Entry field = iter.next(); printField(field.getKey(), field.getValue(), generator, selfType); diff --git a/framework/src/main/java/org/tron/core/services/http/MarketCancelOrderServlet.java b/framework/src/main/java/org/tron/core/services/http/MarketCancelOrderServlet.java index 814ff6b5314..8d19d60ce5c 100644 --- a/framework/src/main/java/org/tron/core/services/http/MarketCancelOrderServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/MarketCancelOrderServlet.java @@ -1,7 +1,6 @@ package org.tron.core.services.http; import com.alibaba.fastjson.JSONObject; -import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; @@ -25,11 +24,9 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String contract = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(contract); - - boolean visible = Util.getVisiblePost(contract); + PostParams params = PostParams.getPostParams(request); + String contract = params.getParams(); + boolean visible = params.isVisible(); MarketCancelOrderContract.Builder build = MarketCancelOrderContract.newBuilder(); JsonFormat.merge(contract, build, visible); diff --git a/framework/src/main/java/org/tron/core/services/http/ScanNoteByIvkServlet.java b/framework/src/main/java/org/tron/core/services/http/ScanNoteByIvkServlet.java index 00c7cae8971..c0076a705f8 100644 --- a/framework/src/main/java/org/tron/core/services/http/ScanNoteByIvkServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/ScanNoteByIvkServlet.java @@ -37,18 +37,15 @@ public static String convertOutput(GrpcAPI.DecryptNotes notes, boolean visible) protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String input = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(input); - boolean visible = Util.getVisiblePost(input); + PostParams params = PostParams.getPostParams(request); IvkDecryptParameters.Builder ivkDecryptParameters = IvkDecryptParameters.newBuilder(); - JsonFormat.merge(input, ivkDecryptParameters); + JsonFormat.merge(params.getParams(), ivkDecryptParameters); GrpcAPI.DecryptNotes notes = wallet .scanNoteByIvk(ivkDecryptParameters.getStartBlockIndex(), ivkDecryptParameters.getEndBlockIndex(), ivkDecryptParameters.getIvk().toByteArray()); - response.getWriter().println(convertOutput(notes, visible)); + response.getWriter().println(convertOutput(notes, params.isVisible())); } catch (Exception e) { Util.processError(e, response); } diff --git a/framework/src/main/java/org/tron/core/services/http/ScanNoteByOvkServlet.java b/framework/src/main/java/org/tron/core/services/http/ScanNoteByOvkServlet.java index cc17fa66114..1cf6363ba98 100644 --- a/framework/src/main/java/org/tron/core/services/http/ScanNoteByOvkServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/ScanNoteByOvkServlet.java @@ -20,19 +20,16 @@ public class ScanNoteByOvkServlet extends RateLimiterServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String input = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(input); - boolean visible = Util.getVisiblePost(input); + PostParams params = PostParams.getPostParams(request); OvkDecryptParameters.Builder ovkDecryptParameters = OvkDecryptParameters.newBuilder(); - JsonFormat.merge(input, ovkDecryptParameters); + JsonFormat.merge(params.getParams(), ovkDecryptParameters); GrpcAPI.DecryptNotes notes = wallet .scanNoteByOvk(ovkDecryptParameters.getStartBlockIndex(), ovkDecryptParameters.getEndBlockIndex(), ovkDecryptParameters.getOvk().toByteArray()); - response.getWriter().println(ScanNoteByIvkServlet.convertOutput(notes, visible)); + response.getWriter().println(ScanNoteByIvkServlet.convertOutput(notes, params.isVisible())); } catch (Exception e) { Util.processError(e, response); } diff --git a/framework/src/main/java/org/tron/core/services/http/ScanShieldedTRC20NotesByIvkServlet.java b/framework/src/main/java/org/tron/core/services/http/ScanShieldedTRC20NotesByIvkServlet.java index cbca20f06b4..2b52883f490 100644 --- a/framework/src/main/java/org/tron/core/services/http/ScanShieldedTRC20NotesByIvkServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/ScanShieldedTRC20NotesByIvkServlet.java @@ -29,7 +29,7 @@ public static String convertOutput(GrpcAPI.DecryptNotesTRC20 notes, boolean visi JSONArray array = jsonNotes.getJSONArray("noteTxs"); for (int index = 0; index < array.size(); index++) { JSONObject item = array.getJSONObject(index); - item.put("index", notes.getNoteTxs(index).getIndex()); //避免把0自动忽略 + item.put("index", notes.getNoteTxs(index).getIndex()); // Avoid automatically ignoring 0 } return jsonNotes.toJSONString(); } @@ -37,14 +37,10 @@ public static String convertOutput(GrpcAPI.DecryptNotesTRC20 notes, boolean visi protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String input = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(input); - - boolean visible = Util.getVisiblePost(input); + PostParams params = PostParams.getPostParams(request); IvkDecryptTRC20Parameters.Builder ivkDecryptTRC20Parameters = IvkDecryptTRC20Parameters .newBuilder(); - JsonFormat.merge(input, ivkDecryptTRC20Parameters, visible); + JsonFormat.merge(params.getParams(), ivkDecryptTRC20Parameters, params.isVisible()); GrpcAPI.DecryptNotesTRC20 notes = wallet .scanShieldedTRC20NotesByIvk(ivkDecryptTRC20Parameters.getStartBlockIndex(), @@ -54,7 +50,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) ivkDecryptTRC20Parameters.getAk().toByteArray(), ivkDecryptTRC20Parameters.getNk().toByteArray(), ivkDecryptTRC20Parameters.getEventsList()); - response.getWriter().println(convertOutput(notes, visible)); + response.getWriter().println(convertOutput(notes, params.isVisible())); } catch (Exception e) { Util.processError(e, response); } diff --git a/framework/src/main/java/org/tron/core/services/http/ScanShieldedTRC20NotesByOvkServlet.java b/framework/src/main/java/org/tron/core/services/http/ScanShieldedTRC20NotesByOvkServlet.java index 7a0423dece0..b5fbbab1625 100644 --- a/framework/src/main/java/org/tron/core/services/http/ScanShieldedTRC20NotesByOvkServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/ScanShieldedTRC20NotesByOvkServlet.java @@ -20,13 +20,10 @@ public class ScanShieldedTRC20NotesByOvkServlet extends RateLimiterServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String input = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(input); - boolean visible = Util.getVisiblePost(input); + PostParams params = PostParams.getPostParams(request); OvkDecryptTRC20Parameters.Builder ovkDecryptTRC20Parameters = OvkDecryptTRC20Parameters .newBuilder(); - JsonFormat.merge(input, ovkDecryptTRC20Parameters, visible); + JsonFormat.merge(params.getParams(), ovkDecryptTRC20Parameters, params.isVisible()); GrpcAPI.DecryptNotesTRC20 notes = wallet .scanShieldedTRC20NotesByOvk(ovkDecryptTRC20Parameters.getStartBlockIndex(), @@ -36,7 +33,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) ovkDecryptTRC20Parameters.getEventsList() ); response.getWriter() - .println(ScanShieldedTRC20NotesByIvkServlet.convertOutput(notes, visible)); + .println(ScanShieldedTRC20NotesByIvkServlet.convertOutput(notes, params.isVisible())); } catch (Exception e) { Util.processError(e, response); } 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 65ae2112c72..c038a3b39bb 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 @@ -45,10 +45,6 @@ protected void validateParameter(String contract) { || StringUtil.isNullOrEmpty(jsonObject.getString("contract_address"))) { throw new InvalidParameterException("contract_address isn't set."); } - if (!jsonObject.containsKey(functionSelector) - || StringUtil.isNullOrEmpty(jsonObject.getString(functionSelector))) { - throw new InvalidParameterException("function_selector isn't set."); - } } protected void doPost(HttpServletRequest request, HttpServletResponse response) @@ -65,10 +61,18 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) validateParameter(contract); JsonFormat.merge(contract, build, visible); JSONObject jsonObject = JSONObject.parseObject(contract); - String selector = jsonObject.getString(functionSelector); - String parameter = jsonObject.getString("parameter"); - String data = Util.parseMethod(selector, parameter); - build.setData(ByteString.copyFrom(ByteArray.fromHexString(data))); + + boolean isFunctionSelectorSet = jsonObject.containsKey(functionSelector) + && !StringUtil.isNullOrEmpty(jsonObject.getString(functionSelector)); + String data; + if (isFunctionSelectorSet) { + String selector = jsonObject.getString(functionSelector); + String parameter = jsonObject.getString("parameter"); + data = Util.parseMethod(selector, parameter); + build.setData(ByteString.copyFrom(ByteArray.fromHexString(data))); + } else { + build.setData(ByteString.copyFrom(new byte[0])); + } long feeLimit = Util.getJsonLongValue(jsonObject, "fee_limit"); TransactionCapsule trxCap = wallet @@ -101,4 +105,4 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) trxExtBuilder.setResult(retBuilder); response.getWriter().println(Util.printTransactionExtention(trxExtBuilder.build(), visible)); } -} \ No newline at end of file +} 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 2d95225e550..345475cbec5 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 @@ -45,10 +45,6 @@ protected void validateParameter(String contract) { || StringUtil.isNullOrEmpty(jsonObject.getString("contract_address"))) { throw new InvalidParameterException("contract_address isn't set."); } - if (!jsonObject.containsKey(functionSelector) - || StringUtil.isNullOrEmpty(jsonObject.getString(functionSelector))) { - throw new InvalidParameterException("function_selector isn't set."); - } } protected void doPost(HttpServletRequest request, HttpServletResponse response) @@ -57,7 +53,6 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) TransactionExtention.Builder trxExtBuilder = TransactionExtention.newBuilder(); Return.Builder retBuilder = Return.newBuilder(); boolean visible = false; - try { String contract = request.getReader().lines() .collect(Collectors.joining(System.lineSeparator())); @@ -66,10 +61,19 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) validateParameter(contract); JsonFormat.merge(contract, build, visible); JSONObject jsonObject = JSONObject.parseObject(contract); - String selector = jsonObject.getString(functionSelector); - String parameter = jsonObject.getString("parameter"); - String data = Util.parseMethod(selector, parameter); - build.setData(ByteString.copyFrom(ByteArray.fromHexString(data))); + + boolean isFunctionSelectorSet = jsonObject.containsKey(functionSelector) + && !StringUtil.isNullOrEmpty(jsonObject.getString(functionSelector)); + String data; + if (isFunctionSelectorSet) { + String selector = jsonObject.getString(functionSelector); + String parameter = jsonObject.getString("parameter"); + 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")); build.setTokenId(Util.getJsonLongValue(jsonObject, "token_id")); build.setCallValue(Util.getJsonLongValue(jsonObject, "call_value")); @@ -102,4 +106,4 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) trxExtBuilder.setResult(retBuilder); response.getWriter().println(Util.printTransactionExtention(trxExtBuilder.build(), visible)); } -} \ No newline at end of file +} diff --git a/framework/src/main/java/org/tron/core/services/http/UnFreezeAssetServlet.java b/framework/src/main/java/org/tron/core/services/http/UnFreezeAssetServlet.java index 3e4b075d101..6118b39f2cd 100644 --- a/framework/src/main/java/org/tron/core/services/http/UnFreezeAssetServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/UnFreezeAssetServlet.java @@ -26,18 +26,15 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String contract = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(contract); - boolean visible = Util.getVisiblePost(contract); + PostParams params = PostParams.getPostParams(request); UnfreezeAssetContract.Builder build = UnfreezeAssetContract.newBuilder(); - JsonFormat.merge(contract, build, visible); + JsonFormat.merge(params.getParams(), build, params.isVisible()); Transaction tx = wallet .createTransactionCapsule(build.build(), ContractType.UnfreezeAssetContract) .getInstance(); - JSONObject jsonObject = JSONObject.parseObject(contract); + JSONObject jsonObject = JSONObject.parseObject(params.getParams()); tx = Util.setTransactionPermissionId(jsonObject, tx); - response.getWriter().println(Util.printCreateTransaction(tx, visible)); + 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/UnFreezeBalanceServlet.java b/framework/src/main/java/org/tron/core/services/http/UnFreezeBalanceServlet.java index b03ef68076c..eb075b7139d 100644 --- a/framework/src/main/java/org/tron/core/services/http/UnFreezeBalanceServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/UnFreezeBalanceServlet.java @@ -26,18 +26,15 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String contract = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(contract); - boolean visible = Util.getVisiblePost(contract); + PostParams params = PostParams.getPostParams(request); UnfreezeBalanceContract.Builder build = UnfreezeBalanceContract.newBuilder(); - JsonFormat.merge(contract, build, visible); + JsonFormat.merge(params.getParams(), build, params.isVisible()); Transaction tx = wallet .createTransactionCapsule(build.build(), ContractType.UnfreezeBalanceContract) .getInstance(); - JSONObject jsonObject = JSONObject.parseObject(contract); + JSONObject jsonObject = JSONObject.parseObject(params.getParams()); tx = Util.setTransactionPermissionId(jsonObject, tx); - response.getWriter().println(Util.printCreateTransaction(tx, visible)); + 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/UpdateAccountServlet.java b/framework/src/main/java/org/tron/core/services/http/UpdateAccountServlet.java index d19a4bcd5ce..0251a46ec64 100644 --- a/framework/src/main/java/org/tron/core/services/http/UpdateAccountServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/UpdateAccountServlet.java @@ -26,18 +26,15 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String contract = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(contract); - boolean visible = Util.getVisiblePost(contract); + PostParams params = PostParams.getPostParams(request); AccountUpdateContract.Builder build = AccountUpdateContract.newBuilder(); - JsonFormat.merge(contract, build, visible); + JsonFormat.merge(params.getParams(), build, params.isVisible()); Transaction tx = wallet .createTransactionCapsule(build.build(), ContractType.AccountUpdateContract) .getInstance(); - JSONObject jsonObject = JSONObject.parseObject(contract); + JSONObject jsonObject = JSONObject.parseObject(params.getParams()); tx = Util.setTransactionPermissionId(jsonObject, tx); - response.getWriter().println(Util.printCreateTransaction(tx, visible)); + 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/UpdateAssetServlet.java b/framework/src/main/java/org/tron/core/services/http/UpdateAssetServlet.java index 3e08eaa9c8b..d3f467ff7a8 100644 --- a/framework/src/main/java/org/tron/core/services/http/UpdateAssetServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/UpdateAssetServlet.java @@ -26,18 +26,15 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String contract = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(contract); - boolean visible = Util.getVisiblePost(contract); + PostParams params = PostParams.getPostParams(request); UpdateAssetContract.Builder build = UpdateAssetContract.newBuilder(); - JsonFormat.merge(contract, build, visible); + JsonFormat.merge(params.getParams(), build, params.isVisible()); Transaction tx = wallet .createTransactionCapsule(build.build(), ContractType.UpdateAssetContract).getInstance(); - JSONObject jsonObject = JSONObject.parseObject(contract); + JSONObject jsonObject = JSONObject.parseObject(params.getParams()); tx = Util.setTransactionPermissionId(jsonObject, tx); - response.getWriter().println(Util.printCreateTransaction(tx, visible)); + 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/UpdateBrokerageServlet.java b/framework/src/main/java/org/tron/core/services/http/UpdateBrokerageServlet.java index 2b9015d83ac..23daaef6072 100644 --- a/framework/src/main/java/org/tron/core/services/http/UpdateBrokerageServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/UpdateBrokerageServlet.java @@ -22,18 +22,15 @@ public class UpdateBrokerageServlet extends RateLimiterServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String contract = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(contract); - boolean visible = Util.getVisiblePost(contract); + PostParams params = PostParams.getPostParams(request); UpdateBrokerageContract.Builder build = UpdateBrokerageContract.newBuilder(); - JsonFormat.merge(contract, build, visible); + JsonFormat.merge(params.getParams(), build, params.isVisible()); Transaction tx = wallet .createTransactionCapsule(build.build(), ContractType.UpdateBrokerageContract) .getInstance(); - JSONObject jsonObject = JSONObject.parseObject(contract); + JSONObject jsonObject = JSONObject.parseObject(params.getParams()); tx = Util.setTransactionPermissionId(jsonObject, tx); - response.getWriter().println(Util.printCreateTransaction(tx, visible)); + 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/UpdateEnergyLimitServlet.java b/framework/src/main/java/org/tron/core/services/http/UpdateEnergyLimitServlet.java index 8aef41780d1..aac6e8ff50e 100644 --- a/framework/src/main/java/org/tron/core/services/http/UpdateEnergyLimitServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/UpdateEnergyLimitServlet.java @@ -26,19 +26,16 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String contract = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(contract); - boolean visible = Util.getVisiblePost(contract); + PostParams params = PostParams.getPostParams(request); UpdateEnergyLimitContract.Builder build = UpdateEnergyLimitContract.newBuilder(); - JsonFormat.merge(contract, build, visible); + JsonFormat.merge(params.getParams(), build, params.isVisible()); Transaction tx = wallet .createTransactionCapsule(build.build(), ContractType.UpdateEnergyLimitContract) .getInstance(); - JSONObject jsonObject = JSONObject.parseObject(contract); + JSONObject jsonObject = JSONObject.parseObject(params.getParams()); tx = Util.setTransactionPermissionId(jsonObject, tx); - response.getWriter().println(Util.printCreateTransaction(tx, visible)); + 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/UpdateWitnessServlet.java b/framework/src/main/java/org/tron/core/services/http/UpdateWitnessServlet.java index 69d544b5e02..3584557d3b6 100644 --- a/framework/src/main/java/org/tron/core/services/http/UpdateWitnessServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/UpdateWitnessServlet.java @@ -26,20 +26,17 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { - String contract = request.getReader().lines() - .collect(Collectors.joining(System.lineSeparator())); - Util.checkBodySize(contract); - boolean visible = Util.getVisiblePost(contract); + PostParams params = PostParams.getPostParams(request); WitnessUpdateContract.Builder build = WitnessUpdateContract.newBuilder(); - JsonFormat.merge(contract, build, visible); + JsonFormat.merge(params.getParams(), build, params.isVisible()); Transaction tx = wallet .createTransactionCapsule(build.build(), ContractType.WitnessUpdateContract) .getInstance(); - JSONObject jsonObject = JSONObject.parseObject(contract); + JSONObject jsonObject = JSONObject.parseObject(params.getParams()); tx = Util.setTransactionPermissionId(jsonObject, tx); - response.getWriter().println(Util.printCreateTransaction(tx, visible)); + response.getWriter().println(Util.printCreateTransaction(tx, params.isVisible())); } catch (Exception e) { Util.processError(e, response); } } -} \ No newline at end of file +} diff --git a/framework/src/main/java/org/tron/core/services/http/ValidateAddressServlet.java b/framework/src/main/java/org/tron/core/services/http/ValidateAddressServlet.java index 9d6998f797d..a65e2ce2ee0 100644 --- a/framework/src/main/java/org/tron/core/services/http/ValidateAddressServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/ValidateAddressServlet.java @@ -77,4 +77,4 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) logger.debug("Exception: {}", e.getMessage()); } } -} \ No newline at end of file +} diff --git a/framework/src/main/java/org/tron/core/services/http/solidity/SolidityNodeHttpApiService.java b/framework/src/main/java/org/tron/core/services/http/solidity/SolidityNodeHttpApiService.java index 3cbf2e828d1..0a3ff9eef4f 100644 --- a/framework/src/main/java/org/tron/core/services/http/solidity/SolidityNodeHttpApiService.java +++ b/framework/src/main/java/org/tron/core/services/http/solidity/SolidityNodeHttpApiService.java @@ -22,6 +22,7 @@ import org.tron.core.services.http.GetBlockByLimitNextServlet; import org.tron.core.services.http.GetBlockByNumServlet; import org.tron.core.services.http.GetBrokerageServlet; +import org.tron.core.services.http.GetBurnTrxServlet; import org.tron.core.services.http.GetDelegatedResourceAccountIndexServlet; import org.tron.core.services.http.GetDelegatedResourceServlet; import org.tron.core.services.http.GetExchangeByIdServlet; @@ -127,7 +128,8 @@ public class SolidityNodeHttpApiService implements Service { private GetMarketOrderListByPairServlet getMarketOrderListByPairServlet; @Autowired private GetMarketPairListServlet getMarketPairListServlet; - + @Autowired + private GetBurnTrxServlet getBurnTrxServlet; @Autowired private GetBrokerageServlet getBrokerageServlet; @Autowired @@ -237,6 +239,7 @@ public void start() { context.addServlet(new ServletHolder(getNodeInfoServlet), "/wallet/getnodeinfo"); context.addServlet(new ServletHolder(getBrokerageServlet), "/walletsolidity/getBrokerage"); context.addServlet(new ServletHolder(getRewardServlet), "/walletsolidity/getReward"); + context.addServlet(new ServletHolder(getBurnTrxServlet), "/walletsolidity/getburntrx"); int maxHttpConnectNumber = Args.getInstance().getMaxHttpConnectNumber(); if (maxHttpConnectNumber > 0) { diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java index 2547d801197..8519d0bd6de 100755 --- a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java @@ -467,7 +467,7 @@ public void scanShieldedTRC20NotesByIvk(IvkDecryptTRC20Parameters request, StreamObserver responseObserver) { walletOnPBFT.futureGet( () -> rpcApiService.getWalletSolidityApi() - .scanShieldedTRC20NotesByIvk(request, responseObserver) + .scanShieldedTRC20NotesByIvk(request, responseObserver) ); } @@ -476,7 +476,7 @@ public void scanShieldedTRC20NotesByOvk(OvkDecryptTRC20Parameters request, StreamObserver responseObserver) { walletOnPBFT.futureGet( () -> rpcApiService.getWalletSolidityApi() - .scanShieldedTRC20NotesByOvk(request, responseObserver) + .scanShieldedTRC20NotesByOvk(request, responseObserver) ); } @@ -485,9 +485,15 @@ public void isShieldedTRC20ContractNoteSpent(NfTRC20Parameters request, StreamObserver responseObserver) { walletOnPBFT.futureGet( () -> rpcApiService.getWalletSolidityApi() - .isShieldedTRC20ContractNoteSpent(request, responseObserver) + .isShieldedTRC20ContractNoteSpent(request, responseObserver) ); } + @Override + public void getBurnTrx(EmptyMessage request, StreamObserver responseObserver) { + walletOnPBFT.futureGet( + () -> rpcApiService.getWalletSolidityApi().getBurnTrx(request, responseObserver) + ); + } } } diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetBurnTrxOnPBFTServlet.java b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetBurnTrxOnPBFTServlet.java new file mode 100644 index 00000000000..fb1654062c8 --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetBurnTrxOnPBFTServlet.java @@ -0,0 +1,26 @@ +package org.tron.core.services.interfaceOnPBFT.http; + +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.services.http.GetBurnTrxServlet; +import org.tron.core.services.interfaceOnPBFT.WalletOnPBFT; + + +@Component +@Slf4j(topic = "API") +public class GetBurnTrxOnPBFTServlet extends GetBurnTrxServlet { + + @Autowired + private WalletOnPBFT walletOnPBFT; + + protected void doGet(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doGet(request, response)); + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doPost(request, response)); + } +} diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/PBFT/HttpApiOnPBFTService.java b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/PBFT/HttpApiOnPBFTService.java index edc86a0d808..751d7d76c4f 100644 --- a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/PBFT/HttpApiOnPBFTService.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/PBFT/HttpApiOnPBFTService.java @@ -24,6 +24,7 @@ import org.tron.core.services.interfaceOnPBFT.http.GetBlockByLimitNextOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.GetBlockByNumOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.GetBrokerageOnPBFTServlet; +import org.tron.core.services.interfaceOnPBFT.http.GetBurnTrxOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.GetDelegatedResourceAccountIndexOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.GetDelegatedResourceOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.GetExchangeByIdOnPBFTServlet; @@ -141,6 +142,8 @@ public class HttpApiOnPBFTService implements Service { @Autowired private IsShieldedTRC20ContractNoteSpentOnPBFTServlet isShieldedTRC20ContractNoteSpentOnPBFTServlet; + @Autowired + private GetBurnTrxOnPBFTServlet getBurnTrxOnPBFTServlet; @Override public void init() { @@ -224,6 +227,8 @@ public void start() { "/scanshieldedtrc20notesbyovk"); context.addServlet(new ServletHolder(isShieldedTRC20ContractNoteSpentOnPBFTServlet), "/isshieldedtrc20contractnotespent"); + context.addServlet(new ServletHolder(getBurnTrxOnPBFTServlet), + "/getburntrx"); int maxHttpConnectNumber = Args.getInstance().getMaxHttpConnectNumber(); if (maxHttpConnectNumber > 0) { diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java index 29703ba6ceb..4099d101f4b 100755 --- a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java @@ -485,5 +485,11 @@ public void getMarketPairList(EmptyMessage request, ); } + @Override + public void getBurnTrx(EmptyMessage request, StreamObserver responseObserver) { + walletOnSolidity.futureGet( + () -> rpcApiService.getWalletSolidityApi().getBurnTrx(request, responseObserver) + ); + } } } diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/GetBurnTrxOnSolidityServlet.java b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/GetBurnTrxOnSolidityServlet.java new file mode 100644 index 00000000000..46435a92668 --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/GetBurnTrxOnSolidityServlet.java @@ -0,0 +1,26 @@ +package org.tron.core.services.interfaceOnSolidity.http; + +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.services.http.GetBurnTrxServlet; +import org.tron.core.services.interfaceOnSolidity.WalletOnSolidity; + + +@Component +@Slf4j(topic = "API") +public class GetBurnTrxOnSolidityServlet extends GetBurnTrxServlet { + + @Autowired + private WalletOnSolidity walletOnSolidity; + + protected void doGet(HttpServletRequest request, HttpServletResponse response) { + walletOnSolidity.futureGet(() -> super.doGet(request, response)); + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) { + walletOnSolidity.futureGet(() -> super.doPost(request, response)); + } +} diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java index 9a824c669f7..8165abbb275 100644 --- a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java @@ -24,6 +24,7 @@ import org.tron.core.services.interfaceOnSolidity.http.GetBlockByLimitNextOnSolidityServlet; import org.tron.core.services.interfaceOnSolidity.http.GetBlockByNumOnSolidityServlet; import org.tron.core.services.interfaceOnSolidity.http.GetBrokerageOnSolidityServlet; +import org.tron.core.services.interfaceOnSolidity.http.GetBurnTrxOnSolidityServlet; import org.tron.core.services.interfaceOnSolidity.http.GetDelegatedResourceAccountIndexOnSolidityServlet; import org.tron.core.services.interfaceOnSolidity.http.GetDelegatedResourceOnSolidityServlet; import org.tron.core.services.interfaceOnSolidity.http.GetExchangeByIdOnSolidityServlet; @@ -126,6 +127,8 @@ public class HttpApiOnSolidityService implements Service { @Autowired private GetRewardOnSolidityServlet getRewardServlet; @Autowired + private GetBurnTrxOnSolidityServlet getBurnTrxOnSolidityServlet; + @Autowired private TriggerConstantContractOnSolidityServlet triggerConstantContractOnSolidityServlet; @Autowired private GetTransactionInfoByBlockNumOnSolidityServlet @@ -239,11 +242,13 @@ public void start() { context.addServlet(new ServletHolder(getNodeInfoOnSolidityServlet), "/wallet/getnodeinfo"); context.addServlet(new ServletHolder(getBrokerageServlet), "/walletsolidity/getBrokerage"); context.addServlet(new ServletHolder(getRewardServlet), "/walletsolidity/getReward"); + context + .addServlet(new ServletHolder(getBurnTrxOnSolidityServlet), "/walletsolidity/getburntrx"); // filters the specified APIs // when node is lite fullnode and openHistoryQueryWhenLiteFN is false context.addFilter(new FilterHolder(liteFnQueryHttpFilter), "/*", - EnumSet.allOf(DispatcherType.class)); + EnumSet.allOf(DispatcherType.class)); int maxHttpConnectNumber = Args.getInstance().getMaxHttpConnectNumber(); if (maxHttpConnectNumber > 0) { diff --git a/framework/src/main/java/org/tron/core/zen/address/KeyIo.java b/framework/src/main/java/org/tron/core/zen/address/KeyIo.java index 9c7b445b575..9dc28b9ff03 100644 --- a/framework/src/main/java/org/tron/core/zen/address/KeyIo.java +++ b/framework/src/main/java/org/tron/core/zen/address/KeyIo.java @@ -79,7 +79,7 @@ private static byte[] convertBits( bits += fromBits; while (bits >= toBits) { bits -= toBits; - out.write((int) ((acc >>> bits) & maxv)); + out.write((acc >>> bits) & maxv); } } if (pad) { diff --git a/framework/src/main/java/org/tron/keystore/Wallet.java b/framework/src/main/java/org/tron/keystore/Wallet.java index 5c7618ce943..0139e3e56b0 100644 --- a/framework/src/main/java/org/tron/keystore/Wallet.java +++ b/framework/src/main/java/org/tron/keystore/Wallet.java @@ -24,6 +24,7 @@ import org.tron.common.utils.ByteArray; import org.tron.common.utils.StringUtil; import org.tron.core.config.args.Args; +import org.tron.core.exception.CipherException; /** *

Ethereum wallet file management. For reference, refer to diff --git a/framework/src/main/java/org/tron/keystore/WalletUtils.java b/framework/src/main/java/org/tron/keystore/WalletUtils.java index f78b31a75d2..8bcc68cbab0 100644 --- a/framework/src/main/java/org/tron/keystore/WalletUtils.java +++ b/framework/src/main/java/org/tron/keystore/WalletUtils.java @@ -18,6 +18,7 @@ import org.tron.common.crypto.SignUtils; import org.tron.common.utils.Utils; import org.tron.core.config.args.Args; +import org.tron.core.exception.CipherException; /** * Utility functions for working with Wallet files. diff --git a/framework/src/main/java/org/tron/program/FullNode.java b/framework/src/main/java/org/tron/program/FullNode.java index 0fba9be651d..3d3d0f9bd8e 100644 --- a/framework/src/main/java/org/tron/program/FullNode.java +++ b/framework/src/main/java/org/tron/program/FullNode.java @@ -22,6 +22,8 @@ @Slf4j(topic = "app") public class FullNode { + + public static final int dbVersion = 2; public static void load(String path) { try { @@ -82,7 +84,7 @@ public static void main(String[] args) { // full node and solidity node fuse together // provide solidity rpc and http server on the full node. - if (Args.getInstance().getStorage().getDbVersion() == 2) { + if (Args.getInstance().getStorage().getDbVersion() == dbVersion) { RpcApiServiceOnSolidity rpcApiServiceOnSolidity = context .getBean(RpcApiServiceOnSolidity.class); appT.addService(rpcApiServiceOnSolidity); @@ -94,7 +96,7 @@ public static void main(String[] args) { } // PBFT API (HTTP and GRPC) - if (Args.getInstance().getStorage().getDbVersion() == 2) { + if (Args.getInstance().getStorage().getDbVersion() == dbVersion) { RpcApiServiceOnPBFT rpcApiServiceOnPBFT = context .getBean(RpcApiServiceOnPBFT.class); appT.addService(rpcApiServiceOnPBFT); diff --git a/framework/src/main/java/org/tron/program/KeystoreFactory.java b/framework/src/main/java/org/tron/program/KeystoreFactory.java index d4a0ce9ba04..bfd2df22856 100755 --- a/framework/src/main/java/org/tron/program/KeystoreFactory.java +++ b/framework/src/main/java/org/tron/program/KeystoreFactory.java @@ -13,7 +13,7 @@ import org.tron.common.utils.Utils; import org.tron.core.Constant; import org.tron.core.config.args.Args; -import org.tron.keystore.CipherException; +import org.tron.core.exception.CipherException; import org.tron.keystore.Credentials; import org.tron.keystore.WalletUtils; diff --git a/framework/src/main/java/org/tron/program/Version.java b/framework/src/main/java/org/tron/program/Version.java index a8f9eadf3ca..2e145fe942c 100644 --- a/framework/src/main/java/org/tron/program/Version.java +++ b/framework/src/main/java/org/tron/program/Version.java @@ -2,12 +2,12 @@ public class Version { - public static final String versionName = "GreatVoyage-v4.1.0-1-g635526cc6"; - public static final String versionCode = "13215"; - private static final String version = "4.1.1"; + public static final String VERSION_NAME = "GreatVoyage-v4.1.0-1-g635526cc6"; + public static final String VERSION_CODE = "13215"; + private static final String VERSION = "4.1.1"; public static String getVersion() { - return version; + return VERSION; } } diff --git a/framework/src/main/java/org/tron/tool/litefullnode/LiteFullNodeTool.java b/framework/src/main/java/org/tron/tool/litefullnode/LiteFullNodeTool.java index aab841c7b16..fdf64ceb0ee 100644 --- a/framework/src/main/java/org/tron/tool/litefullnode/LiteFullNodeTool.java +++ b/framework/src/main/java/org/tron/tool/litefullnode/LiteFullNodeTool.java @@ -26,6 +26,7 @@ import org.tron.common.utils.ByteArray; import org.tron.common.utils.FileUtil; import org.tron.common.utils.PropUtil; +import org.tron.core.Constant; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.TransactionCapsule; import org.tron.core.db2.core.SnapshotManager; @@ -41,7 +42,6 @@ public class LiteFullNodeTool { private static final String SNAPSHOT_DIR_NAME = "snapshot"; private static final String HISTORY_DIR_NAME = "history"; private static final String INFO_FILE_NAME = "info.properties"; - private static final String SPLIT_BLOCK_NUM = "split_block_num"; private static final String BACKUP_DIR_PREFIX = ".bak_"; private static final String CHECKPOINT_DB = "tmp"; private static final long VM_NEED_RECENT_BLKS = 256; @@ -242,7 +242,7 @@ private void generateInfoProperties(String propertyfile, String databaseDir) if (!FileUtil.createFileIfNotExists(propertyfile)) { throw new RuntimeException("create properties file failed..."); } - if (!PropUtil.writeProperty(propertyfile, SPLIT_BLOCK_NUM, + if (!PropUtil.writeProperty(propertyfile, Constant.SPLIT_BLOCK_NUM, Long.toString(getLatestBlockHeaderNum(databaseDir)))) { throw new RuntimeException("write properties file failed..."); } @@ -376,8 +376,10 @@ private BlockNumInfo checkAndGetBlockNumInfo(String historyDir, String databaseD if (!FileUtil.isExists(historyInfo)) { throw new FileNotFoundException("history property file is not found."); } - long snapshotBlkNum = Long.parseLong(PropUtil.readProperty(snapshotInfo, SPLIT_BLOCK_NUM)); - long historyBlkNum = Long.parseLong(PropUtil.readProperty(historyInfo, SPLIT_BLOCK_NUM)); + long snapshotBlkNum = Long.parseLong(PropUtil.readProperty(snapshotInfo, Constant + .SPLIT_BLOCK_NUM)); + long historyBlkNum = Long.parseLong(PropUtil.readProperty(historyInfo, Constant + .SPLIT_BLOCK_NUM)); if (historyBlkNum < snapshotBlkNum) { logger.error("history latest block number is lower than snapshot, history: {}, snapshot: {}", historyBlkNum, snapshotBlkNum); diff --git a/framework/src/main/resources/config-localtest.conf b/framework/src/main/resources/config-localtest.conf index 47951cb8a6f..a9a56591800 100644 --- a/framework/src/main/resources/config-localtest.conf +++ b/framework/src/main/resources/config-localtest.conf @@ -5,7 +5,7 @@ net { storage { # Directory for storing persistent data - db.version = 1, + db.version = 2, db.directory = "database", index.directory = "index", @@ -277,6 +277,7 @@ committee = { allowTvmConstantinople = 1 allowTvmSolidity059 = 1 allowMarketTransaction = 1 + allowTransactionFeePool = 1 } log.level = { diff --git a/framework/src/main/resources/config.conf b/framework/src/main/resources/config.conf index efc0e04ac6c..2326876f17c 100644 --- a/framework/src/main/resources/config.conf +++ b/framework/src/main/resources/config.conf @@ -72,6 +72,8 @@ storage { bak2path = "bak2/database" frequency = 10000 // indicate backup db once every 10000 blocks processed. } + + balance.history.lookup = false } node.discovery = { 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 c39a3f57b5e..0578b76136f 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 @@ -27,5 +27,6 @@ public void destroy() { public void testConfig() { Assert.assertEquals(Args.getInstance().getMaxTransactionPendingSize(), 2000); Assert.assertEquals(Args.getInstance().getPendingTransactionTimeout(), 60_000); + Assert.assertEquals(Args.getInstance().getNodeDiscoveryPingTimeout(), 15_000); } } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/common/overlay/discover/node/NodeStatisticsTest.java b/framework/src/test/java/org/tron/common/overlay/discover/node/NodeStatisticsTest.java index 957d0c5565d..5d4cf3bbede 100644 --- a/framework/src/test/java/org/tron/common/overlay/discover/node/NodeStatisticsTest.java +++ b/framework/src/test/java/org/tron/common/overlay/discover/node/NodeStatisticsTest.java @@ -64,7 +64,7 @@ public void testNode() throws NoSuchFieldException, IllegalAccessException { this.nodeStatistics.resetTcpFlow(); this.nodeStatistics.discoverMessageLatency.add(10); this.nodeStatistics.discoverMessageLatency.add(20); - long avg = this.nodeStatistics.discoverMessageLatency.getAvrg(); + long avg = this.nodeStatistics.discoverMessageLatency.getAvg(); Assert.assertEquals(15, avg); } 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 a8cefc720a1..5054d4286d2 100644 --- a/framework/src/test/java/org/tron/common/runtime/ProgramResultTest.java +++ b/framework/src/test/java/org/tron/common/runtime/ProgramResultTest.java @@ -32,9 +32,11 @@ import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.DynamicPropertiesStore; import org.tron.protos.Protocol; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Transaction; +import org.tron.protos.Protocol.Transaction.Result.contractResult; @Slf4j @@ -93,14 +95,14 @@ public static void destroy() { * calledAddress.call(bytes4(keccak256("getZero()"))); return (address(c1),address(c2)); } } * contract A { address public calledAddress; constructor(address d) payable{ calledAddress = d; * } - * + *

* address public b1; address public b2; address public b3; address public b4; address public b5; * address public b6; address public b7; address public b8; - * + *

* function create(){ B b= new B(calledAddress); B bb = new B(calledAddress); b1 = address(b); b2 * = address(bb); (b3,b4)=b.setB(); (b5,b6)=bb.setB(); (b7,b8)=bb.setB(); * calledAddress.call(bytes4(keccak256("getZero()"))); } } - * + *

* contract calledContract { function getZero() returns(uint256){ return 0; } } */ @@ -265,7 +267,7 @@ private byte[] deployContractAAndGetItsAddress(byte[] calledContractAddress) /** * pragma solidity ^0.4.24; - * + *

* contract A{ uint256 public num = 0; constructor() public payable{} function transfer(address c, * bool isRevert) payable public returns(address){ B b = (new B).value(10)();//1 * address(b).transfer(5);//2 b.payC(c, isRevert);//3 // b.payC(c,isRevert); return address(b); } @@ -273,15 +275,15 @@ private byte[] deployContractAAndGetItsAddress(byte[] calledContractAddress) * = 0; function f() payable returns(bool) { return true; } constructor() public payable {} * function payC(address c, bool isRevert) public{ c.transfer(1);//4 if (isRevert) { revert(); } } * function getBalance() returns(uint256){ return this.balance; } function () payable{} } - * + *

* contract C{ constructor () public payable{} function () payable{} } */ @Test public void successAndFailResultTest() throws ContractExeException, ReceiptCheckErrException, VMIllegalException, ContractValidateException { - byte[] cContract = deployC(); - byte[] aContract = deployA(); + byte[] cContract = deployC("C"); + byte[] aContract = deployA("A"); //false String params = Hex.toHexString(new DataWord(new DataWord(cContract).getLast20Bytes()).getData()) @@ -374,10 +376,55 @@ public void successAndFailResultTest() checkTransactionInfo(traceFailed, trx2, null, internalTransactionsListFail); } - private byte[] deployC() + @Test + public void timeOutFeeTest() + throws ContractExeException, ReceiptCheckErrException, VMIllegalException, + ContractValidateException { + byte[] cContract = deployC("D"); + byte[] aContract = deployA("B"); + //false + String params = + Hex.toHexString(new DataWord(new DataWord(cContract).getLast20Bytes()).getData()) + + "0000000000000000000000000000000000000000000000000000000000000000"; + + // ======================================= Test Success ======================================= + byte[] triggerData1 = TvmTestUtils.parseAbi("transfer(address,bool)", params); + Transaction trx1 = TvmTestUtils + .generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), aContract, + triggerData1, 0, 100000000); + TransactionTrace traceSuccess = TvmTestUtils + .processTransactionAndReturnTrace(trx1, deposit, null); + + Assert.assertEquals(traceSuccess.getReceipt().getEnergyFee(), 12705900L); + + TransactionInfoCapsule trxInfoCapsule = + buildTransactionInfoInstance(new TransactionCapsule(trx1), null, traceSuccess); + Assert.assertEquals(trxInfoCapsule.getFee(), 12705900L); + Assert.assertEquals(trxInfoCapsule.getPackingFee(), 0L); + + DynamicPropertiesStore dynamicPropertiesStore = traceSuccess.getTransactionContext() + .getStoreFactory().getChainBaseManager().getDynamicPropertiesStore(); + dynamicPropertiesStore.saveAllowTransactionFeePool(1L); + + trxInfoCapsule = + buildTransactionInfoInstance(new TransactionCapsule(trx1), null, traceSuccess); + Assert.assertEquals(trxInfoCapsule.getFee(), 12705900L); + Assert.assertEquals(trxInfoCapsule.getPackingFee(), 12705900L); + + + traceSuccess.getReceipt().setResult(contractResult.OUT_OF_TIME); + + trxInfoCapsule = + buildTransactionInfoInstance(new TransactionCapsule(trx1), null, traceSuccess); + Assert.assertEquals(trxInfoCapsule.getFee(), 12705900L); + Assert.assertEquals(trxInfoCapsule.getPackingFee(), 0L); + + + } + + private byte[] deployC(String contractName) throws ContractExeException, ReceiptCheckErrException, ContractValidateException, VMIllegalException { - String contractName = "C"; byte[] address = Hex.decode(OWNER_ADDRESS); String ABI = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\"" @@ -394,10 +441,9 @@ private byte[] deployC() feeLimit, consumeUserResourcePercent, null, deposit, null); } - private byte[] deployA() + private byte[] deployA(String contractName) throws ContractExeException, ReceiptCheckErrException, ContractValidateException, VMIllegalException { - String contractName = "A"; byte[] address = Hex.decode(OWNER_ADDRESS); String ABI = "[{\"constant\":false,\"inputs\":[],\"name\":\"getBalance\",\"outputs\":[{\"name\"" @@ -449,7 +495,7 @@ private byte[] deployA() /** * pragma solidity ^0.4.24; - * + *

* contract A{ constructor () payable public{} function suicide(address toAddress) public payable{ * selfdestruct(toAddress); } function () payable public{} }s */ 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 new file mode 100644 index 00000000000..d58388c76bf --- /dev/null +++ b/framework/src/test/java/org/tron/common/runtime/vm/IsSRCandidateTest.java @@ -0,0 +1,273 @@ +package org.tron.common.runtime.vm; + +import java.util.Collections; +import lombok.extern.slf4j.Slf4j; +import org.junit.Test; +import org.spongycastle.util.encoders.Hex; +import org.testng.Assert; +import org.tron.common.runtime.InternalTransaction; +import org.tron.common.runtime.TvmTestUtils; +import org.tron.common.utils.StringUtil; +import org.tron.common.utils.WalletUtil; +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.store.StoreFactory; +import org.tron.core.vm.config.ConfigLoader; +import org.tron.core.vm.config.VMConfig; +import org.tron.core.vm.program.Program; +import org.tron.core.vm.program.invoke.ProgramInvoke; +import org.tron.core.vm.program.invoke.ProgramInvokeFactory; +import org.tron.core.vm.program.invoke.ProgramInvokeFactoryImpl; +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 { + + /* + pragma solidity ^0.5.0; + + contract ContractB{ + address others; + } + + contract TestIsSRCandidate{ + address user; + + ContractB contractB = new ContractB(); + + constructor() public { + user = msg.sender; + } + + function isSRCandidateTest(address addr) public returns (bool) { + return address(addr).isSRCandidate; + } + + function nullAddressTest() public returns (bool) { + return address(0x0).isSRCandidate; + } + + function localContractAddrTest() public returns (bool) { + address payable localContract = address(uint160(address(this))); + return localContract.isSRCandidate; + + return address(this).isSRCandidate; + } + + function otherContractAddrTest() public returns (bool) { + return address(contractB).isSRCandidate; + } + + function nonpayableAddrTest(address addr) public returns (bool) { + return addr.isSRCandidate; + } + + function payableAddrTest(address payable addr) public returns (bool) { + return addr.isSRCandidate; + } + } + */ + + @Test + public void testIsSRCandidate() + throws ContractExeException, ReceiptCheckErrException, VMIllegalException, + ContractValidateException { + ConfigLoader.disable = true; + VMConfig.initAllowTvmTransferTrc10(1); + VMConfig.initAllowTvmConstantinople(1); + VMConfig.initAllowTvmSolidity059(1); + VMConfig.initAllowTvmStake(1); + String contractName = "TestIsSRCandidate"; + byte[] address = Hex.decode(OWNER_ADDRESS); + String abi = + "[{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\"," + + "\"type\":\"constructor\"},{\"constant\":false," + + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"addr\"," + + "\"type\":\"address\"}],\"name\":\"isSRCandidateTest\"," + + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," + + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," + + "{\"constant\":false,\"inputs\":[],\"name\":\"localContractAddrTest\"," + + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," + + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," + + "{\"constant\":false,\"inputs\":[{\"internalType\":\"address\"," + + "\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"nonpayableAddrTest\"," + + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," + + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," + + "{\"constant\":false,\"inputs\":[],\"name\":\"nullAddressTest\"," + + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," + + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," + + "{\"constant\":false,\"inputs\":[],\"name\":\"otherContractAddrTest\"," + + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," + + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," + + "{\"constant\":false,\"inputs\":[{\"internalType\":\"address payable\"," + + "\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"payableAddrTest\"," + + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," + + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"; + + String factoryCode = + "60806040526040516100109061008b565b6" + + "04051809103906000f08015801561002c573d6000803e3d6" + + "000fd5b50600180546001600160a01b0319166001600160a" + + "01b039290921691909117905534801561005957600080fd5" + + "b50d3801561006657600080fd5b50d280156100735760008" + + "0fd5b50600080546001600160a01b0319163317905561009" + + "7565b6072806101c283390190565b61011c806100a660003" + + "96000f3fe6080604052348015600f57600080fd5b50d3801" + + "5601b57600080fd5b50d28015602757600080fd5b5060043" + + "61060725760003560e01c80632e48f1ac14607757806356b" + + "42994146077578063627bfa45146077578063af4a1105146" + + "0ae578063cb2d51cf1460b4578063d30a28ee1460ba575b6" + + "00080fd5b609a60048036036020811015608b57600080fd5" + + "b50356001600160a01b031660c0565b60408051911515825" + + "2519081900360200190f35b609a60cd565b609a60d3565b6" + + "09a60d8565b6001600160a01b0316d990565b6000d990565" + + "b30d990565b6001546001600160a01b0316d99056fea2647" + + "4726f6e5820509553fa5821ca76ddf8a0d074cd74dcb1f74" + + "e068ca148b983f1b0bea447b99f64736f6c634300050d003" + + "16080604052348015600f57600080fd5b50d38015601b576" + + "00080fd5b50d28015602757600080fd5b50603d806035600" + + "0396000f3fe6080604052600080fdfea26474726f6e58209" + + "afab2d7a84ca331e2eb33393a62310b1a53e77c37a287407" + + "53ae0a3a99980ba64736f6c634300050d0031"; + long value = 0; + long fee = 100000000; + long consumeUserResourcePercent = 0; + + Repository repository; + StoreFactory storeFactory = StoreFactory.getInstance(); + ProgramInvokeFactory programInvokeFactory = new ProgramInvokeFactoryImpl(); + VMConfig vmConfig = VMConfig.getInstance(); + + // deploy contract + Transaction trx = + TvmTestUtils.generateDeploySmartContractAndGetTransaction( + contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, null); + byte[] factoryAddress = WalletUtil.generateContractAddress(trx); + String factoryAddressStr = StringUtil.encode58Check(factoryAddress); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + Assert.assertNull(runtime.getRuntimeError()); + + // Trigger contract method: isSRCandidateTest(address) + String methodByAddr = "isSRCandidateTest(address)"; + String nonexistentAccount = "27k66nycZATHzBasFT9782nTsYWqVtxdtAc"; + byte[] nonexistentAddr = Hex.decode("A0E6773BBF60F97D22AA3BF73D2FE235E816A1964F"); + String hexInput = + AbiUtil.parseMethod(methodByAddr, Collections.singletonList(nonexistentAccount)); + + trx = + TvmTestUtils.generateTriggerSmartContractAndGetTransaction( + Hex.decode(OWNER_ADDRESS), factoryAddress, Hex.decode(hexInput), 0, fee); + InternalTransaction rootInternalTransaction = + new InternalTransaction(trx, InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + ProgramInvoke programInvoke = + programInvokeFactory.createProgramInvoke( + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, + trx, + 0, + 0, + null, + repository, + System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, + 3_000_000L); + Program program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + byte[] programResult = program.isSRCandidate(new DataWord(nonexistentAddr)).getData(); + Assert.assertEquals( + Hex.toHexString(programResult), + "0000000000000000000000000000000000000000000000000000000000000000"); + repository.commit(); + + // trigger deployed contract + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); + trx = + TvmTestUtils.generateTriggerSmartContractAndGetTransaction( + Hex.decode(OWNER_ADDRESS), factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = + new InternalTransaction(trx, InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = + programInvokeFactory.createProgramInvoke( + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, + trx, + 0, + 0, + null, + repository, + System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, + 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + programResult = program.isSRCandidate(new DataWord(factoryAddress)).getData(); + Assert.assertEquals( + Hex.toHexString(programResult), + "0000000000000000000000000000000000000000000000000000000000000000"); + repository.commit(); + + // trigger deployed contract + String witnessAccount = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; + byte[] witnessAddr = Hex.decode("a0299f3db80a24b20a254b89ce639d59132f157f13"); + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(witnessAccount)); + trx = + TvmTestUtils.generateTriggerSmartContractAndGetTransaction( + Hex.decode(OWNER_ADDRESS), factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = + new InternalTransaction(trx, InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = + programInvokeFactory.createProgramInvoke( + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, + trx, + 0, + 0, + null, + repository, + System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, + 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + programResult = program.isSRCandidate(new DataWord(witnessAddr)).getData(); + Assert.assertEquals( + Hex.toHexString(programResult), + "0000000000000000000000000000000000000000000000000000000000000001"); + repository.commit(); + + // Trigger contract method: nullAddressTest(address) + methodByAddr = "nullAddressTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = + TvmTestUtils.generateTriggerSmartContractAndGetTransaction( + Hex.decode(OWNER_ADDRESS), factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = + new InternalTransaction(trx, InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = + programInvokeFactory.createProgramInvoke( + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, + trx, + 0, + 0, + null, + repository, + System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, + 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + programResult = program.isSRCandidate(new DataWord()).getData(); + Assert.assertEquals( + Hex.toHexString(programResult), + "0000000000000000000000000000000000000000000000000000000000000000"); + repository.commit(); + + ConfigLoader.disable = false; + } +} 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 new file mode 100644 index 00000000000..e633a78a10e --- /dev/null +++ b/framework/src/test/java/org/tron/common/runtime/vm/RewardBalanceTest.java @@ -0,0 +1,262 @@ +package org.tron.common.runtime.vm; + +import java.util.Collections; +import lombok.extern.slf4j.Slf4j; +import org.junit.Test; +import org.spongycastle.util.encoders.Hex; +import org.testng.Assert; +import org.tron.common.runtime.InternalTransaction; +import org.tron.common.runtime.TVMTestResult; +import org.tron.common.runtime.TvmTestUtils; +import org.tron.common.utils.Base58; +import org.tron.common.utils.StringUtil; +import org.tron.common.utils.WalletUtil; +import org.tron.core.capsule.BlockCapsule; +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.store.StoreFactory; +import org.tron.core.vm.config.ConfigLoader; +import org.tron.core.vm.config.VMConfig; +import org.tron.core.vm.program.Program; +import org.tron.core.vm.program.invoke.ProgramInvoke; +import org.tron.core.vm.program.invoke.ProgramInvokeFactory; +import org.tron.core.vm.program.invoke.ProgramInvokeFactoryImpl; +import org.tron.core.vm.repository.Repository; +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 { + + /* + pragma solidity ^0.5.0; + + contract ContractB{ + address user; + } + + contract TestRewardBalance{ + address user; + address payable owner; + + ContractB contractB = new ContractB(); + + constructor() public { + user = msg.sender; + } + + function rewardBalanceTest(address addr) view public returns (uint256) { + return addr.rewardbalance; + } + + function nullAddressTest() view public returns (uint256) { + return address(0x0).rewardbalance; + } + + function localContractAddrTest() view public returns (uint256) { + address payable localContract = address(uint160(address(this))); + return localContract.rewardbalance; + } + + function otherContractAddrTest() view public returns (uint256) { + address payable localContract = address(uint160(address(contractB))); + return localContract.rewardbalance; + } + + function nonpayableAddrTest(address addr) view public returns (uint256) { + return addr.rewardbalance; + } + + function payableAddrTest(address payable addr) view public returns (uint256) { + return addr.rewardbalance; + } + } + */ + + @Test + public void testRewardBalance() + throws ContractExeException, ReceiptCheckErrException, VMIllegalException, + ContractValidateException { + ConfigLoader.disable = true; + VMConfig.initAllowTvmTransferTrc10(1); + VMConfig.initAllowTvmConstantinople(1); + VMConfig.initAllowTvmSolidity059(1); + VMConfig.initAllowTvmStake(1); + manager.getDynamicPropertiesStore().saveChangeDelegation(1); + StoreFactory storeFactory = StoreFactory.getInstance(); + Repository repository; + ProgramInvokeFactory programInvokeFactory = new ProgramInvokeFactoryImpl(); + VMConfig vmConfig = VMConfig.getInstance(); + + String contractName = "TestRewardBalance"; + byte[] address = Hex.decode(OWNER_ADDRESS); + String abi = "[{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\"," + + "\"type\":\"constructor\"},{\"constant\":false,\"inputs\":[]," + + "\"name\":\"localContractAddrTest\",\"outputs\":[{\"internalType\":\"uint256\"," + + "\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," + + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," + + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"addr\"," + + "\"type\":\"address\"}],\"name\":\"nonpayableAddrTest\"," + + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," + + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," + + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[]," + + "\"name\":\"nullAddressTest\",\"outputs\":[{\"internalType\":\"uint256\"," + + "\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," + + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," + + "\"inputs\":[],\"name\":\"otherContractAddrTest\"," + + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," + + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," + + "\"type\":\"function\"},{\"constant\":false," + + "\"inputs\":[{\"internalType\":\"address payable\",\"name\":\"addr\"," + + "\"type\":\"address\"}],\"name\":\"payableAddrTest\"," + + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," + + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," + + "\"type\":\"function\"},{\"constant\":false," + + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"addr\"," + + "\"type\":\"address\"}],\"name\":\"rewardBalanceTest\"," + + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," + + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," + + "\"type\":\"function\"}]"; + String factoryCode = "60806040526040516100109061008b565b604051" + + "809103906000f08015801561002c573d6000803e3d6000fd5b506" + + "00280546001600160a01b0319166001600160a01b039290921691" + + "909117905534801561005957600080fd5b50d3801561006657600" + + "080fd5b50d2801561007357600080fd5b50600080546001600160" + + "a01b03191633179055610097565b6072806101c083390190565b6" + + "1011a806100a66000396000f3fe6080604052348015600f576000" + + "80fd5b50d38015601b57600080fd5b50d28015602757600080fd5" + + "b506004361060725760003560e01c806356b42994146077578063" + + "627bfa45146077578063a223c65f146077578063af4a11051460a" + + "c578063cb2d51cf1460b2578063d30a28ee1460b8575b600080fd" + + "5b609a60048036036020811015608b57600080fd5b50356001600" + + "160a01b031660be565b60408051918252519081900360200190f3" + + "5b609a60cb565b609a60d1565b609a60d6565b6001600160a01b0" + + "316d890565b6000d890565b30d890565b6002546001600160a01b" + + "0316d89056fea26474726f6e5820717344fa5eb84d711be29808c" + + "dff30740d75dddee7a38e76042a46157370501c64736f6c634300" + + "050d00316080604052348015600f57600080fd5b50d38015601b5" + + "7600080fd5b50d28015602757600080fd5b50603d806035600039" + + "6000f3fe6080604052600080fdfea26474726f6e582090ab77a1a" + + "2f65b0d6f77854c390b03b33fe20cd15ed8f722d497f9c3070c96" + + "ef64736f6c634300050d0031"; + long value = 0; + long feeLimit = 100000000; + long consumeUserResourcePercent = 0; + + // deploy contract + Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + contractName, address, abi, factoryCode, value, feeLimit, consumeUserResourcePercent, + null); + byte[] factoryAddress = WalletUtil.generateContractAddress(trx); + String factoryAddressStr = StringUtil.encode58Check(factoryAddress); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + Assert.assertNull(runtime.getRuntimeError()); + + // Trigger contract method: rewardBalanceTest(address) + String methodByAddr = "rewardBalanceTest(address)"; + String nonexistentAccount = "27k66nycZATHzBasFT9782nTsYWqVtxdtAc"; + String hexInput = AbiUtil.parseMethod(methodByAddr, + Collections.singletonList(nonexistentAccount)); + BlockCapsule blockCap = new BlockCapsule(Protocol.Block.newBuilder().build()); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit); + InternalTransaction rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + ProgramInvoke programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + Program program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + byte[] result = program.getRewardBalance(new DataWord(Base58.decode(nonexistentAccount))) + .getData(); + + Assert.assertEquals(Hex.toHexString(result), + "0000000000000000000000000000000000000000000000000000000000000000"); + repository.commit(); + + // trigger deployed contract + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + result = program.getRewardBalance(new DataWord(Base58.decode(factoryAddressStr))).getData(); + Assert.assertEquals(Hex.toHexString(result), + "0000000000000000000000000000000000000000000000000000000000000000"); + repository.commit(); + + // trigger deployed contract + String witnessAccount = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(witnessAccount)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + result = program.getRewardBalance(new DataWord(Base58.decode(witnessAccount))).getData(); + Assert.assertEquals(Hex.toHexString(result), + "0000000000000000000000000000000000000000000000000000000000000000"); + repository.commit(); + + // Trigger contract method: nullAddressTest(address) + methodByAddr = "nullAddressTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + result = program.getRewardBalance(DataWord.ZERO()).getData(); + Assert.assertEquals(Hex.toHexString(result), + "0000000000000000000000000000000000000000000000000000000000000000"); + repository.commit(); + + // Trigger contract method: localContractAddrTest() + methodByAddr = "localContractAddrTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + result = program.getRewardBalance(new DataWord(Base58.decode(factoryAddressStr))).getData(); + Assert.assertEquals(Hex.toHexString(result), + "0000000000000000000000000000000000000000000000000000000000000000"); + repository.commit(); + + ConfigLoader.disable = false; + } +} + + diff --git a/framework/src/test/java/org/tron/common/runtime/vm/StakeTest.java b/framework/src/test/java/org/tron/common/runtime/vm/StakeTest.java new file mode 100644 index 00000000000..f83b9d0a05f --- /dev/null +++ b/framework/src/test/java/org/tron/common/runtime/vm/StakeTest.java @@ -0,0 +1,246 @@ +package org.tron.common.runtime.vm; + +import java.util.Arrays; +import lombok.extern.slf4j.Slf4j; +import org.junit.Before; +import org.junit.Test; +import org.spongycastle.util.encoders.Hex; +import org.testng.Assert; +import org.tron.common.runtime.InternalTransaction; +import org.tron.common.runtime.TVMTestResult; +import org.tron.common.runtime.TvmTestUtils; +import org.tron.common.utils.StringUtil; +import org.tron.common.utils.WalletUtil; +import org.tron.consensus.dpos.MaintenanceManager; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.WitnessCapsule; +import org.tron.core.consensus.ConsensusService; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.VM; +import org.tron.core.vm.config.ConfigLoader; +import org.tron.core.vm.config.VMConfig; +import org.tron.core.vm.program.Program; +import org.tron.core.vm.program.invoke.ProgramInvoke; +import org.tron.core.vm.program.invoke.ProgramInvokeFactory; +import org.tron.core.vm.program.invoke.ProgramInvokeFactoryImpl; +import org.tron.core.vm.program.invoke.ProgramInvokeMockImpl; +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 StakeTest extends VMTestBase { + + private MaintenanceManager maintenanceManager; + private StoreFactory storeFactory; + private Repository repository; + private ProgramInvokeFactory programInvokeFactory; + private VMConfig vmConfig; + + @Before + public void before() { + ConsensusService consensusService = context.getBean(ConsensusService.class); + consensusService.start(); + maintenanceManager = context.getBean(MaintenanceManager.class); + + ConfigLoader.disable = true; + VMConfig.initAllowTvmTransferTrc10(1); + VMConfig.initAllowTvmConstantinople(1); + VMConfig.initAllowTvmSolidity059(1); + VMConfig.initAllowTvmStake(1); + manager.getDynamicPropertiesStore().saveChangeDelegation(1); + + storeFactory = StoreFactory.getInstance(); + programInvokeFactory = new ProgramInvokeFactoryImpl(); + vmConfig = VMConfig.getInstance(); + } + + /* +pragma solidity ^0.5.0; +contract TestStake{ + +constructor() payable public{} + +function selfdestructTest(address payable target) public{ + selfdestruct(target); +} + +function selfdestructTest2(address sr, uint256 amount, address payable target) public{ + stake(sr, amount); + selfdestruct(target); +} + +function Stake(address sr, uint256 amount) public returns (bool result){ + return stake(sr, amount); +} +function UnStake() public returns (bool result){ + return unstake(); +} +} + */ + @Test + public void testStake() throws Exception { + String contractName = "TestStake"; + byte[] address = Hex.decode(OWNER_ADDRESS); + String abi = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":" + + "\"constructor\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\",\"name\"" + + ":\"sr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\"," + + "\"type\":\"uint256\"}],\"name\":\"Stake\",\"outputs\":[{\"internalType\":\"bool\"" + + ",\"name\":\"result\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"" + + "nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"" + + "UnStake\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"result\",\"type\":\"" + + "bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}" + + ",{\"constant\":false,\"inputs\":[{\"internalType\":\"address payable\",\"name\":\"" + + "target\",\"type\":\"address\"}],\"name\":\"selfdestructTest\",\"outputs\":[],\"" + + "payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant" + + "\":false,\"inputs\":[{\"internalType\":\"address\",\"name\":\"sr\",\"type\":\"address" + + "\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"" + + "internalType\":\"address payable\",\"name\":\"target\",\"type\":\"address\"}],\"name" + + "\":\"selfdestructTest2\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"" + + "nonpayable\",\"type\":\"function\"}]"; + String factoryCode = "608060405261024a806100136000396000f3fe608060405234801561001057600080f" + + "d5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50600436106100665760003560e01c8" + + "063377bdd4c1461006b57806338e8221f146100af578063ebedb8b31461011d578063ecb90615146101835" + + "75b600080fd5b6100ad6004803603602081101561008157600080fd5b81019080803573fffffffffffffff" + + "fffffffffffffffffffffffff1690602001909291905050506101a5565b005b61011b60048036036060811" + + "0156100c557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019" + + "092919080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909" + + "291905050506101be565b005b6101696004803603604081101561013357600080fd5b81019080803573fff" + + "fffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506101d" + + "b565b604051808215151515815260200191505060405180910390f35b61018b6101e8565b6040518082151" + + "51515815260200191505060405180910390f35b8073ffffffffffffffffffffffffffffffffffffffff16f" + + "f5b8183d5508073ffffffffffffffffffffffffffffffffffffffff16ff5b60008183d5905092915050565" + + "b6000d690509056fea26474726f6e582003e023985836e07a7f23202dfc410017c52159ee1ee3968435e99" + + "17f83f8d5a164736f6c637828302e352e31332d646576656c6f702e323032302e382e31332b636f6d6d697" + + "42e37633236393863300057"; + long feeLimit = 100000000; + + // deploy contract + Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + contractName, address, abi, factoryCode, 100000000, feeLimit, 0, + null); + byte[] factoryAddress = WalletUtil.generateContractAddress(trx); + String factoryAddressStr = StringUtil.encode58Check(factoryAddress); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + Assert.assertNull(runtime.getRuntimeError()); + + String methodByAddr = "Stake(address,uint256)"; + final String witnessAddrStr = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; + final byte[] witnessAddr = Hex.decode("a0299f3db80a24b20a254b89ce639d59132f157f13"); + BlockCapsule blockCap = new BlockCapsule(Protocol.Block.newBuilder().build()); + + // build program and trigger program.stake(witnessAddrStr, 10000000) + String hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList(witnessAddrStr, 10000000)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit); + InternalTransaction rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + ProgramInvoke programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + Program program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + boolean result = program.stake(new DataWord(witnessAddr), new DataWord(10000000)); + Assert.assertTrue(result); + + repository.commit(); + + maintenanceManager.doMaintenance(); + + AccountCapsule contract = manager.getAccountStore().get(factoryAddress); + WitnessCapsule witness = manager.getWitnessStore().get(witnessAddr); + Assert.assertEquals(contract.getFrozenCount(), 1); + Assert.assertEquals(contract.getFrozenBalance(), 10000000); + Assert.assertEquals(contract.getBalance(), 90000000); + Assert.assertEquals(contract.getVotesList().get(0).getVoteCount(), 10); + Assert.assertEquals(witness.getVoteCount(), 115); + + // program.stake(witnessAddrStr, 5000000) + hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList(witnessAddrStr, 5000000)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + result = program.stake(new DataWord(witnessAddr), new DataWord(5000000)); + Assert.assertTrue(result); + repository.commit(); + + contract = manager.getAccountStore().get(factoryAddress); + Assert.assertEquals(contract.getFrozenCount(), 1); + Assert.assertEquals(contract.getFrozenBalance(), 10000000); + Assert.assertEquals(contract.getVotesList().get(0).getVoteCount(), 5); + + // vote not exist witness + hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList( + "27k66nycZATHzBasFT9782nTsYWqVtxdtAc", 20000000)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + result = program + .stake(new DataWord("A0E6773BBF60F97D22AA3BF73D2FE235E816A1964F"), new DataWord(20000000)); + Assert.assertFalse(result); + repository.commit(); + + contract = manager.getAccountStore().get(factoryAddress); + Assert.assertEquals(contract.getBalance(), 90000000); + Assert.assertEquals(contract.getFrozenCount(), 1); + Assert.assertEquals(contract.getFrozenBalance(), 10000000); + + // param error + hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList( + "27k66nycZATHzBasFT9782nTsYWqVtxdtAc", -20000000)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + result = program + .stake(new DataWord("A0E6773BBF60F97D22AA3BF73D2FE235E816A1964F"), new DataWord(-20000000)); + Assert.assertFalse(result); + repository.commit(); + + // param error + hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList( + "27k66nycZATHzBasFT9782nTsYWqVtxdtAc", 2000000000)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + result = program.stake(new DataWord("A0E6773BBF60F97D22AA3BF73D2FE235E816A1964F"), + new DataWord(2000000000)); + Assert.assertFalse(result); + repository.commit(); + } +} diff --git a/framework/src/test/java/org/tron/common/runtime/vm/SuicideTest.java b/framework/src/test/java/org/tron/common/runtime/vm/SuicideTest.java new file mode 100644 index 00000000000..4f05b465693 --- /dev/null +++ b/framework/src/test/java/org/tron/common/runtime/vm/SuicideTest.java @@ -0,0 +1,447 @@ +package org.tron.common.runtime.vm; + +import java.util.Arrays; +import org.junit.Before; +import org.junit.Test; +import org.spongycastle.util.encoders.Hex; +import org.testng.Assert; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.runtime.InternalTransaction; +import org.tron.common.runtime.TVMTestResult; +import org.tron.common.runtime.TvmTestUtils; +import org.tron.common.utils.StringUtil; +import org.tron.common.utils.WalletUtil; +import org.tron.consensus.dpos.MaintenanceManager; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.VotesCapsule; +import org.tron.core.capsule.WitnessCapsule; +import org.tron.core.consensus.ConsensusService; +import org.tron.core.db.TransactionTrace; +import org.tron.core.store.AccountStore; +import org.tron.core.store.StoreFactory; +import org.tron.core.store.VotesStore; +import org.tron.core.store.WitnessStore; +import org.tron.core.vm.config.ConfigLoader; +import org.tron.core.vm.config.VMConfig; +import org.tron.core.vm.program.Program; +import org.tron.core.vm.program.invoke.ProgramInvoke; +import org.tron.core.vm.program.invoke.ProgramInvokeFactory; +import org.tron.core.vm.program.invoke.ProgramInvokeFactoryImpl; +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; + +public class SuicideTest extends VMTestBase { + + private MaintenanceManager maintenanceManager; + private AccountStore accountStore; + private WitnessStore witnessStore; + private VotesStore votesStore; + private StoreFactory storeFactory; + private Repository repository; + private ProgramInvokeFactory programInvokeFactory; + private VMConfig vmConfig; + + @Before + public void before() { + ConsensusService consensusService = context.getBean(ConsensusService.class); + consensusService.start(); + maintenanceManager = context.getBean(MaintenanceManager.class); + accountStore = manager.getAccountStore(); + witnessStore = manager.getWitnessStore(); + votesStore = manager.getVotesStore(); + + ConfigLoader.disable = true; + VMConfig.initAllowTvmTransferTrc10(1); + VMConfig.initAllowTvmConstantinople(1); + VMConfig.initAllowTvmSolidity059(1); + VMConfig.initAllowTvmStake(1); + manager.getDynamicPropertiesStore().saveChangeDelegation(1); + + CommonParameter.getInstance().setDebug(true); + + storeFactory = StoreFactory.getInstance(); + programInvokeFactory = new ProgramInvokeFactoryImpl(); + vmConfig = VMConfig.getInstance(); + } + + /* +pragma solidity ^0.5.0; +contract TestStake{ + +constructor() payable public{} + +function selfdestructTest(address payable target) public{ +selfdestruct(target); +} + +function selfdestructTest2(address sr, uint256 amount, address payable target) public{ +stake(sr, amount); +selfdestruct(target); +} + +function Stake(address sr, uint256 amount) public returns (bool result){ +return stake(sr, amount); +} +function UnStake() public returns (bool result){ +return unstake(); +} +} +*/ + @Test + public void testSuicide() throws Exception { + String contractName = "TestSuicide"; + byte[] ownerAddress = Hex.decode(OWNER_ADDRESS); + String abi = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\"" + + ":\"constructor\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\",\"" + + "name\":\"sr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount" + + "\",\"type\":\"uint256\"}],\"name\":\"Stake\",\"outputs\":[{\"internalType\":\"bool\"" + + ",\"name\":\"result\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"" + + "nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"" + + "UnStake\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"result\",\"type\":\"bool" + + "\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"" + + "constant\":false,\"inputs\":[{\"internalType\":\"address payable\",\"name\":\"target\"" + + ",\"type\":\"address\"}],\"name\":\"selfdestructTest\",\"outputs\":[],\"payable\":false" + + ",\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"" + + "inputs\":[{\"internalType\":\"address\",\"name\":\"sr\",\"type\":\"address\"},{\"" + + "internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"internalType\"" + + ":\"address payable\",\"name\":\"target\",\"type\":\"address\"}],\"name\":\"" + + "selfdestructTest2\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"" + + "nonpayable\",\"type\":\"function\"}]"; + String factoryCode = "608060405261024a806100136000396000f3fe608060405234801561001057600080" + + "fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50600436106100665760003560e01" + + "c8063377bdd4c1461006b57806338e8221f146100af578063ebedb8b31461011d578063ecb90615146101" + + "83575b600080fd5b6100ad6004803603602081101561008157600080fd5b81019080803573fffffffffff" + + "fffffffffffffffffffffffffffff1690602001909291905050506101a5565b005b61011b600480360360" + + "608110156100c557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906" + + "020019092919080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060" + + "2001909291905050506101be565b005b6101696004803603604081101561013357600080fd5b810190808" + + "03573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050" + + "50506101db565b604051808215151515815260200191505060405180910390f35b61018b6101e8565b604" + + "051808215151515815260200191505060405180910390f35b8073ffffffffffffffffffffffffffffffff" + + "ffffffff16ff5b8183d5508073ffffffffffffffffffffffffffffffffffffffff16ff5b60008183d5905" + + "092915050565b6000d690509056fea26474726f6e582003e023985836e07a7f23202dfc410017c52159ee" + + "1ee3968435e9917f83f8d5a164736f6c637828302e352e31332d646576656c6f702e323032302e382e313" + + "32b636f6d6d69742e37633236393863300057"; + long feeLimit = 100000000; + + String witnessAddrStr = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; + final byte[] witnessAddr = Hex.decode("a0299f3db80a24b20a254b89ce639d59132f157f13"); + final String obtainUserAddrStr = "27k66nycZATHzBasFT9782nTsYWqVtxdtAc"; + final byte[] obtainUserAddr = Hex.decode("A0E6773BBF60F97D22AA3BF73D2FE235E816A1964F"); + BlockCapsule blockCap = new BlockCapsule(Protocol.Block.newBuilder().build()); + + // suicide after stake (freeze not expire) + // deploy contract + Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + contractName, ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, + null); + byte[] factoryAddress = WalletUtil.generateContractAddress(trx); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + Assert.assertNull(runtime.getRuntimeError()); + + String hexInput = AbiUtil.parseMethod("Stake(address,uint256)", + Arrays.asList(witnessAddrStr, 10000000)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit); + InternalTransaction rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + ProgramInvoke programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + Program program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + boolean programResult = program.stake(new DataWord(witnessAddr), new DataWord(10000000)); + Assert.assertTrue(programResult); + repository.commit(); + + Protocol.Account.Frozen frozen1; + frozen1 = accountStore.get(factoryAddress).getFrozenList().get(0); + //do maintain + maintenanceManager.doMaintenance(); + hexInput = AbiUtil.parseMethod("selfdestructTest(address)", Arrays.asList(obtainUserAddrStr)); + TVMTestResult result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); + Assert.assertNull(result.getRuntime().getRuntimeError()); + AccountCapsule obtainAccount = accountStore.get(obtainUserAddr); + Assert.assertEquals(obtainAccount.getBalance(), 90000000); + Assert.assertEquals(obtainAccount.getFrozenBalance(), 10000000); + Assert.assertEquals(obtainAccount.getFrozenList().get(0).getExpireTime(), + frozen1.getExpireTime()); + Assert.assertFalse(accountStore.has(factoryAddress)); + maintenanceManager.doMaintenance(); + WitnessCapsule witnessCapsule = witnessStore.get(witnessAddr); + Assert.assertEquals(witnessCapsule.getVoteCount(), 105); + Assert.assertEquals(obtainAccount.getVotesList().size(), 0); + + // suicide to a staked account + trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + contractName, ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, + null); + factoryAddress = WalletUtil.generateContractAddress(trx); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + Assert.assertNull(runtime.getRuntimeError()); + + hexInput = AbiUtil.parseMethod("Stake(address,uint256)", + Arrays.asList(witnessAddrStr, 10000000)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + programResult = program.stake(new DataWord(witnessAddr), new DataWord(10000000)); + Assert.assertTrue(programResult); + repository.commit(); + + frozen1 = accountStore.get(factoryAddress).getFrozenList().get(0); + maintenanceManager.doMaintenance(); + Protocol.Account.Frozen frozen2; + frozen2 = accountStore.get(obtainUserAddr).getFrozenList().get(0); + hexInput = AbiUtil.parseMethod("selfdestructTest(address)", Arrays.asList(obtainUserAddrStr)); + result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); + Assert.assertNull(result.getRuntime().getRuntimeError()); + obtainAccount = accountStore.get(obtainUserAddr); + Assert.assertEquals(obtainAccount.getBalance(), 180000000); + Assert.assertEquals(obtainAccount.getFrozenBalance(), 20000000); + Assert.assertEquals(obtainAccount.getFrozenList().get(0).getExpireTime(), + (frozen1.getExpireTime() * frozen1.getFrozenBalance() + + frozen2.getExpireTime() * frozen2.getFrozenBalance()) + / (frozen1.getFrozenBalance() + frozen2.getFrozenBalance())); + + //test suicide to staked contract & suicide to itself + final long totalNetWeightStart = manager.getDynamicPropertiesStore().getTotalNetWeight(); + //deploy contract1 + trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + contractName, ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, + null); + factoryAddress = WalletUtil.generateContractAddress(trx); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + Assert.assertNull(runtime.getRuntimeError()); + //deploy contract obtain + trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + "contractObtain", ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, + null); + byte[] obtainContractAddr = WalletUtil.generateContractAddress(trx); + String obtainContractAddrStr; + obtainContractAddrStr = StringUtil.encode58Check(obtainContractAddr); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + Assert.assertNull(runtime.getRuntimeError()); + //factoryAddress Stake + hexInput = AbiUtil.parseMethod("Stake(address,uint256)", + Arrays.asList(witnessAddrStr, 10000000)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + programResult = program.stake(new DataWord(witnessAddr), new DataWord(10000000)); + Assert.assertTrue(programResult); + repository.commit(); + + //obtainContractAddr Stake + hexInput = AbiUtil.parseMethod("Stake(address,uint256)", + Arrays.asList(witnessAddrStr, 10000000)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + obtainContractAddr, Hex.decode(hexInput), 0, feeLimit); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + programResult = program.stake(new DataWord(witnessAddr), new DataWord(10000000)); + Assert.assertTrue(programResult); + repository.commit(); + + frozen1 = accountStore.get(factoryAddress).getFrozenList().get(0); + frozen2 = accountStore.get(obtainContractAddr).getFrozenList().get(0); + maintenanceManager.doMaintenance(); + //factoryAddress suicide + hexInput = AbiUtil.parseMethod("selfdestructTest(address)", + Arrays.asList(obtainContractAddrStr)); + result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); + Assert.assertNull(result.getRuntime().getRuntimeError()); + obtainAccount = accountStore.get(obtainContractAddr); + Assert.assertEquals(obtainAccount.getBalance(), 180000000); + Assert.assertEquals(obtainAccount.getFrozenBalance(), 20000000); + Assert.assertEquals(obtainAccount.getFrozenList().get(0).getExpireTime(), + (frozen1.getExpireTime() * frozen1.getFrozenBalance() + + frozen2.getExpireTime() * frozen2.getFrozenBalance()) + / (frozen1.getFrozenBalance() + frozen2.getFrozenBalance())); + Assert.assertEquals(manager.getDynamicPropertiesStore().getTotalNetWeight(), + totalNetWeightStart + 20); + + //obtainContractAddr suicide to itself + AccountCapsule blackHoleAccount; + blackHoleAccount = accountStore.getBlackhole(); + hexInput = AbiUtil.parseMethod("selfdestructTest(address)", + Arrays.asList(obtainContractAddrStr)); + result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + obtainContractAddr, Hex.decode(hexInput), 0, feeLimit, manager, null); + AccountCapsule blackHoleAccountAfter = accountStore.getBlackhole(); + Assert.assertNull(result.getRuntime().getRuntimeError()); + Assert.assertEquals(blackHoleAccountAfter.getBalance(), 200000000 + + blackHoleAccount.getBalance() + 25500); // 25500 for energy used for suicide + Assert.assertEquals(blackHoleAccountAfter.getFrozenBalance(), 0); + Assert.assertEquals(manager.getDynamicPropertiesStore().getTotalNetWeight(), + totalNetWeightStart); + + //test vote + final byte[] zeroAddr = TransactionTrace.convertToTronAddress(new byte[20]); + //deploy contract1 + trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + contractName, ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, + null); + factoryAddress = WalletUtil.generateContractAddress(trx); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + Assert.assertNull(runtime.getRuntimeError()); + //deploy contract obtain + trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + "contractObtain", ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, + null); + obtainContractAddr = WalletUtil.generateContractAddress(trx); + obtainContractAddrStr = StringUtil.encode58Check(obtainContractAddr); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + Assert.assertNull(runtime.getRuntimeError()); + //deploy contract2 + trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + "contractSuicide", ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, + null); + byte[] suicideContractAddr = WalletUtil.generateContractAddress(trx); + String suicideContractAddrStr = StringUtil.encode58Check(suicideContractAddr); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + Assert.assertNull(runtime.getRuntimeError()); + //factoryAddress Stake + hexInput = AbiUtil.parseMethod("Stake(address,uint256)", + Arrays.asList(witnessAddrStr, 10000000)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + programResult = program.stake(new DataWord(witnessAddr), new DataWord(10000000)); + Assert.assertTrue(programResult); + repository.commit(); + + //obtainContractAddr Stake + hexInput = AbiUtil.parseMethod("Stake(address,uint256)", + Arrays.asList(witnessAddrStr, 10000000)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + obtainContractAddr, Hex.decode(hexInput), 0, feeLimit); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + programResult = program.stake(new DataWord(witnessAddr), new DataWord(10000000)); + Assert.assertTrue(programResult); + repository.commit(); + + //suicideContractAddr Stake + hexInput = AbiUtil.parseMethod("Stake(address,uint256)", + Arrays.asList(witnessAddrStr, 10000000)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + suicideContractAddr, Hex.decode(hexInput), 0, feeLimit); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + programResult = program.stake(new DataWord(witnessAddr), new DataWord(10000000)); + Assert.assertTrue(programResult); + repository.commit(); + + maintenanceManager.doMaintenance(); + Assert.assertEquals(accountStore.get(factoryAddress).getVotesList().get(0).getVoteCount(), 10); + Assert.assertEquals(accountStore.get(obtainContractAddr) + .getVotesList().get(0).getVoteCount(), 10); + Assert.assertEquals(accountStore.get(suicideContractAddr) + .getVotesList().get(0).getVoteCount(), 10); + Assert.assertEquals(witnessStore.get(witnessAddr).getVoteCount(), 105 + 30); + //contract1 suicide + hexInput = AbiUtil.parseMethod("selfdestructTest(address)", + Arrays.asList(obtainContractAddrStr)); + result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); + Assert.assertNull(result.getRuntime().getRuntimeError()); + Assert.assertEquals(accountStore.get(obtainContractAddr).getBalance(), 180000000); + VotesCapsule zeroVotes = votesStore.get(zeroAddr); + Assert.assertEquals(zeroVotes.getOldVotes().get(0).getVoteCount(), 10); + Assert.assertEquals(zeroVotes.getNewVotes().size(), 0); + //suicideContractAddr Stake + hexInput = AbiUtil.parseMethod("Stake(address,uint256)", + Arrays.asList(witnessAddrStr, 5000000)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + suicideContractAddr, Hex.decode(hexInput), 0, feeLimit); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + programResult = program.stake(new DataWord(witnessAddr), new DataWord(5000000)); + Assert.assertTrue(programResult); + repository.commit(); + + VotesCapsule suicideContractVotes = votesStore.get(suicideContractAddr); + Assert.assertEquals(suicideContractVotes.getOldVotes().get(0).getVoteCount(), 10); + Assert.assertEquals(suicideContractVotes.getNewVotes().get(0).getVoteCount(), 5); + //suicideContractAddr suicide + hexInput = AbiUtil.parseMethod("selfdestructTest(address)", + Arrays.asList(obtainContractAddrStr)); + result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + suicideContractAddr, Hex.decode(hexInput), 0, feeLimit, manager, null); + Assert.assertNull(result.getRuntime().getRuntimeError()); + Assert.assertEquals(accountStore.get(obtainContractAddr).getBalance(), 270000000); + zeroVotes = votesStore.get(zeroAddr); + Assert.assertEquals(zeroVotes.getOldVotes().get(0).getVoteCount(), 20); + Assert.assertEquals(zeroVotes.getNewVotes().size(), 0); + Assert.assertFalse(votesStore.has(suicideContractAddr)); + maintenanceManager.doMaintenance(); + Assert.assertEquals(witnessStore.get(witnessAddr).getVoteCount(), 105 + 10); + } +} diff --git a/framework/src/test/java/org/tron/common/runtime/vm/Trc10InsTest.java b/framework/src/test/java/org/tron/common/runtime/vm/Trc10InsTest.java new file mode 100644 index 00000000000..253ef1bdadf --- /dev/null +++ b/framework/src/test/java/org/tron/common/runtime/vm/Trc10InsTest.java @@ -0,0 +1,175 @@ +package org.tron.common.runtime.vm; + +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; + +import com.google.protobuf.ByteString; +import java.io.File; +import java.util.Arrays; +import java.util.Objects; +import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.spongycastle.util.encoders.Hex; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.runtime.InternalTransaction; +import org.tron.common.runtime.TvmTestUtils; +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.BlockCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.db.TransactionTrace; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.program.Program; +import org.tron.core.vm.program.invoke.ProgramInvoke; +import org.tron.core.vm.program.invoke.ProgramInvokeFactory; +import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.repository.RepositoryImpl; +import org.tron.protos.Protocol; + +@Slf4j +public class Trc10InsTest { + + private String dbPath; + private TronApplicationContext context; + + @Before + public void init() { + dbPath = "output_" + this.getClass().getName(); + FileUtil.deleteDir(new File(dbPath)); + Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, "config-localtest.conf"); + context = new TronApplicationContext(DefaultConfig.class); + } + + // TODO: 2020/11/26 + // 1. convert string to DataWord, leading or ending + // 2. why asset id in account is not same as in asset issue, bytes vs string + // 3. for test, covert is hard to use + @Test + public void testTokenIssueAndUpdateAsset() throws ContractValidateException { + // construct ProgramInvoke instance + Repository deposit = RepositoryImpl.createRoot(StoreFactory.getInstance()); + byte[] ownerAddr = TransactionTrace.convertToTronAddress( + Hex.decode("abd4b9367799eaa3197fecb144eb71de1e049abc")); + byte[] contractAddr = TransactionTrace.convertToTronAddress( + Hex.decode("471fd3ad3e9eeadeec4608b92d16ce6b500704cc")); + Protocol.Transaction trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction( + ownerAddr, contractAddr, new byte[0], 0, 0); + ProgramInvoke invoke; + invoke = context.getBean(ProgramInvokeFactory.class).createProgramInvoke( + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_NORMAL_TYPE, + trx, + 0, + 0, + new BlockCapsule(Protocol.Block.newBuilder().build()).getInstance(), + deposit, + System.currentTimeMillis(), + System.currentTimeMillis() + 50000, + 3_000_000L); + + // add contract account + deposit.createAccount(contractAddr, Protocol.AccountType.Contract); + deposit.commit(); + + // 1. test token issue + // confirm contract exist and give it 1024 TRXs to issue asset + Assert.assertNotNull(deposit.getAccount(contractAddr)); + Assert.assertEquals(deposit.getBalance(contractAddr), 0); + + long balanceToAdd = deposit.getDynamicPropertiesStore().getAssetIssueFee(); + deposit.addBalance(contractAddr, balanceToAdd); + deposit.commit(); + + Assert.assertEquals(deposit.getBalance(contractAddr), balanceToAdd); + + long initialTokenId = deposit.getTokenIdNum(); + long initialBalanceOfBlackHole = deposit.getBalance(deposit.getBlackHoleAddress()); + + // construct Program instance + InternalTransaction interTrx = new InternalTransaction( + Protocol.Transaction.getDefaultInstance(), + InternalTransaction.TrxType.TRX_UNKNOWN_TYPE); + Program program = new Program(new byte[0], invoke, interTrx); + + // call tokenIssue by Program instance and assert stack top is not zero if call successful + program.tokenIssue(new DataWord(covertTo32BytesByEndingZero(ByteArray.fromString("Yang"))), + new DataWord(covertTo32BytesByEndingZero(ByteArray.fromString("YNX"))), + new DataWord(1000_000L * TRX_PRECISION), + new DataWord(5)); + Assert.assertNotEquals(0, program.stackPop().intValue()); + + // check global token id increased + Assert.assertEquals(initialTokenId + 1, deposit.getTokenIdNum()); + + // check asset issue inserted into repository + final String createdAssetId = String.valueOf(initialTokenId + 1); + byte[] createdAssetIdData = ByteArray.fromString(createdAssetId); + AssetIssueCapsule assetIssueCap = deposit.getAssetIssue(createdAssetIdData); + Assert.assertNotNull(assetIssueCap); + + // check contract account updated + AccountCapsule ownerAccountCap = deposit.getAccount(contractAddr); + Assert.assertEquals(ByteString.copyFrom( + Objects.requireNonNull(ByteArray.fromString(assetIssueCap.getId()))), + ownerAccountCap.getAssetIssuedID()); + Assert.assertEquals(assetIssueCap.getName(), ownerAccountCap.getAssetIssuedName()); + Assert.assertTrue(ownerAccountCap.getAssetMapV2().entrySet().stream().anyMatch( + e -> e.getKey().equals(createdAssetId))); + + // check balance of contract account and black hole account + Assert.assertEquals(initialBalanceOfBlackHole + balanceToAdd, + deposit.getBalance(deposit.getBlackHoleAddress())); + Assert.assertEquals(0, ownerAccountCap.getBalance()); + + // 2. test update asset + // save data of url and description to program memory + String url = "http://test.com"; + String desc = "This is a simple description."; + byte[] urlData = ByteArray.fromString(url); + byte[] descData = ByteArray.fromString(desc); + program.memorySave(new DataWord(0), new DataWord(Objects.requireNonNull(urlData).length)); + program.memorySave(DataWord.WORD_SIZE, urlData); + program.memorySave(new DataWord(2 * DataWord.WORD_SIZE), + new DataWord(Objects.requireNonNull(descData).length)); + program.memorySave(3 * DataWord.WORD_SIZE, descData); + + // call updateAsset by Program instance and assert stack top is not zero if call successful + program.updateAsset(new DataWord(0), new DataWord(2 * DataWord.WORD_SIZE)); + Assert.assertNotEquals(0, program.stackPop().intValue()); + + // check asset issue updated + assetIssueCap = deposit.getAssetIssue(createdAssetIdData); + Assert.assertEquals(url, assetIssueCap.getUrl().toStringUtf8()); + Assert.assertEquals(desc, assetIssueCap.getDesc().toStringUtf8()); + } + + @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."); + } + } + + private byte[] covertTo32BytesByEndingZero(byte[] data) { + if (data == null || data.length > 32) { + throw new IllegalArgumentException("bytes array length should not bigger than 32"); + } + if (data.length == 32) { + return data.clone(); + } + byte[] newData = new byte[32]; + Arrays.fill(newData, (byte) 0); + System.arraycopy(data, 0, newData, 0, data.length); + return newData; + } +} diff --git a/framework/src/test/java/org/tron/common/runtime/vm/UnstakeTest.java b/framework/src/test/java/org/tron/common/runtime/vm/UnstakeTest.java new file mode 100644 index 00000000000..5de195e1c94 --- /dev/null +++ b/framework/src/test/java/org/tron/common/runtime/vm/UnstakeTest.java @@ -0,0 +1,140 @@ +package org.tron.common.runtime.vm; + +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; + +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.spongycastle.util.encoders.Hex; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.runtime.InternalTransaction; +import org.tron.common.runtime.TvmTestUtils; +import org.tron.common.utils.Commons; +import org.tron.common.utils.FileUtil; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.db.TransactionTrace; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.program.Program; +import org.tron.core.vm.program.invoke.ProgramInvoke; +import org.tron.core.vm.program.invoke.ProgramInvokeFactory; +import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.repository.RepositoryImpl; +import org.tron.protos.Protocol; + +@Slf4j +public class UnstakeTest { + + private String dbPath; + private TronApplicationContext context; + + @Before + public void init() { + dbPath = "output_" + this.getClass().getName(); + FileUtil.deleteDir(new File(dbPath)); + Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, "config-localtest.conf"); + context = new TronApplicationContext(DefaultConfig.class); + } + + @Test + public void testUnstakeAfterStake() throws ContractValidateException { + // don`t check frozen time for test + CommonParameter.getInstance().setCheckFrozenTime(0); + + // construct ProgramInvoke instance + Repository deposit = RepositoryImpl.createRoot(StoreFactory.getInstance()); + byte[] ownerAddr = TransactionTrace.convertToTronAddress( + Hex.decode("abd4b9367799eaa3197fecb144eb71de1e049abc")); + byte[] contractAddr = TransactionTrace.convertToTronAddress( + Hex.decode("471fd3ad3e9eeadeec4608b92d16ce6b500704cc")); + Protocol.Transaction trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction( + ownerAddr, contractAddr, new byte[0], 0, 0); + ProgramInvoke invoke; + invoke = context.getBean(ProgramInvokeFactory.class).createProgramInvoke( + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_NORMAL_TYPE, + trx, + 0, + 0, + new BlockCapsule(Protocol.Block.newBuilder().build()).getInstance(), + deposit, + System.currentTimeMillis(), + System.currentTimeMillis() + 50000, + 3_000_000L); + + // add contract account + deposit.createAccount(contractAddr, Protocol.AccountType.Contract); + deposit.commit(); + + // confirm contract exist and add 100 TRXs to contract + Assert.assertNotNull(deposit.getAccount(contractAddr)); + Assert.assertEquals(deposit.getBalance(contractAddr), 0); + + long balanceToAdd = 100 * TRX_PRECISION; + deposit.addBalance(contractAddr, balanceToAdd); + deposit.commit(); + + Assert.assertEquals(deposit.getBalance(contractAddr), balanceToAdd); + + // witness from config.conf and get his vote count + byte[] witnessAddr = Commons.decodeFromBase58Check("TN3zfjYUmMFK3ZsHSsrdJoNRtGkQmZLBLz"); + long witnessVoteCount = deposit.getWitnessCapsule(witnessAddr).getVoteCount(); + + // check contract account doesn`t have any frozens and votes + AccountCapsule contractAccountCap; + contractAccountCap = deposit.getAccount(contractAddr); + Assert.assertEquals(contractAccountCap.getFrozenCount(), 0); + Assert.assertEquals(contractAccountCap.getInstance().getVotesCount(), 0); + + // construct Program instance + InternalTransaction interTrx = new InternalTransaction( + Protocol.Transaction.getDefaultInstance(), + InternalTransaction.TrxType.TRX_UNKNOWN_TYPE); + Program program = new Program(new byte[0], invoke, interTrx); + + // call stake by Program instance and assert its return is true + long voteAmount = 5; + long stakeAmount = voteAmount * TRX_PRECISION; + Assert.assertTrue(program.stake(new DataWord(witnessAddr), new DataWord(stakeAmount))); + + // confirm contract account changed + contractAccountCap = deposit.getAccount(contractAddr); + Assert.assertEquals(contractAccountCap.getBalance(), balanceToAdd - stakeAmount); + Assert.assertEquals(contractAccountCap.getFrozenCount(), 1); + Assert.assertEquals(contractAccountCap.getFrozenBalance(), stakeAmount); + Assert.assertEquals(contractAccountCap.getVotesList().size(), 1); + Assert.assertEquals(contractAccountCap.getVotesList().get(0).getVoteCount(), voteAmount); + //TODO why can`t witness get votes + //Assert.assertEquals(deposit.getWitnessCapsule(witnessAddr).getVoteCount(), + // witnessVoteCount + voteAmount); + + // call unstake by Program instance and assert its return is true + Assert.assertTrue(program.unstake()); + + // confirm contract account back to initial state + contractAccountCap = deposit.getAccount(contractAddr); + Assert.assertEquals(contractAccountCap.getBalance(), balanceToAdd); + Assert.assertEquals(contractAccountCap.getFrozenCount(), 0); + Assert.assertEquals(contractAccountCap.getFrozenBalance(), 0); + Assert.assertEquals(contractAccountCap.getVotesList().size(), 0); + Assert.assertEquals(deposit.getWitnessCapsule(witnessAddr).getVoteCount(), witnessVoteCount); + } + + @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/VMContractTestBase.java b/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java index 0f05b89d8c0..9d8936faabb 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java @@ -16,8 +16,8 @@ import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.consensus.ConsensusService; -import org.tron.core.db.DelegationService; import org.tron.core.db.Manager; +import org.tron.core.service.MortgageService; import org.tron.core.store.StoreFactory; import org.tron.core.store.WitnessStore; import org.tron.core.vm.repository.Repository; @@ -26,6 +26,7 @@ @Slf4j public class VMContractTestBase { + protected String dbPath; protected Runtime runtime; protected Manager manager; @@ -40,12 +41,12 @@ public class VMContractTestBase { protected static String WITNESS_SR1_ADDRESS; WitnessStore witnessStore; - DelegationService delegationService; + MortgageService mortgageService; static { // 27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1 (test.config) WITNESS_SR1_ADDRESS = - Constant.ADD_PRE_FIX_STRING_TESTNET + "299F3DB80A24B20A254B89CE639D59132F157F13"; + Constant.ADD_PRE_FIX_STRING_TESTNET + "299F3DB80A24B20A254B89CE639D59132F157F13"; } @Before @@ -68,7 +69,7 @@ public void init() { witnessStore = context.getBean(WitnessStore.class); consensusService = context.getBean(ConsensusService.class); maintenanceManager = context.getBean(MaintenanceManager.class); - delegationService = context.getBean(DelegationService.class); + mortgageService = context.getBean(MortgageService.class); consensusService.start(); } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/WithdrawRewardTest.java b/framework/src/test/java/org/tron/common/runtime/vm/WithdrawRewardTest.java new file mode 100644 index 00000000000..767e9f13d77 --- /dev/null +++ b/framework/src/test/java/org/tron/common/runtime/vm/WithdrawRewardTest.java @@ -0,0 +1,1188 @@ +package org.tron.common.runtime.vm; + +import com.google.protobuf.ByteString; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Collections; +import lombok.extern.slf4j.Slf4j; +import org.junit.Test; +import org.spongycastle.util.encoders.Hex; +import org.testng.Assert; +import org.tron.common.crypto.ECKey; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.runtime.InternalTransaction; +import org.tron.common.runtime.TVMTestResult; +import org.tron.common.runtime.TvmTestUtils; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.Sha256Hash; +import org.tron.common.utils.StringUtil; +import org.tron.common.utils.WalletUtil; +import org.tron.consensus.base.Param; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.WitnessCapsule; +import org.tron.core.exception.AccountResourceInsufficientException; +import org.tron.core.exception.BadBlockException; +import org.tron.core.exception.BadNumberBlockException; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.DupTransactionException; +import org.tron.core.exception.NonCommonBlockException; +import org.tron.core.exception.ReceiptCheckErrException; +import org.tron.core.exception.TaposException; +import org.tron.core.exception.TooBigTransactionException; +import org.tron.core.exception.TooBigTransactionResultException; +import org.tron.core.exception.TransactionExpirationException; +import org.tron.core.exception.UnLinkedBlockException; +import org.tron.core.exception.VMIllegalException; +import org.tron.core.exception.ValidateScheduleException; +import org.tron.core.exception.ValidateSignatureException; +import org.tron.core.exception.ZksnarkException; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.config.ConfigLoader; +import org.tron.core.vm.config.VMConfig; +import org.tron.core.vm.program.Program; +import org.tron.core.vm.program.invoke.ProgramInvoke; +import org.tron.core.vm.program.invoke.ProgramInvokeFactory; +import org.tron.core.vm.program.invoke.ProgramInvokeFactoryImpl; +import org.tron.core.vm.repository.Repository; +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 WithdrawRewardTest extends VMContractTestBase { + + /* + pragma solidity ^0.5.0; + + contract ContractB{ + address user; + + constructor() payable public { + user = msg.sender; + } + + function stakeTest(address sr, uint256 amount) public returns (bool) { + return stake(sr, amount); + } + + function withdrawRewardTest() public returns (uint) { + return withdrawreward(); + } + } + + contract TestRewardBalance{ + address user; + + ContractB contractB = new ContractB(); + + constructor() payable public { + user = msg.sender; + } + + function stakeTest(address sr, uint256 amount) public returns (bool) { + return stake(sr, amount); + } + + function unstakeTest() public { + unstake(); + } + + function contractBStakeTest(address sr, uint256 amount) public returns (bool) { + return contractB.stakeTest(sr, amount); + } + + function withdrawRewardTest() public returns (uint) { + return withdrawreward(); + } + + function rewardBalanceTest(address addr) public returns (uint) { + return addr.rewardbalance; + } + + function localContractAddrTest() view public returns (uint256) { + address payable localContract = address(uint160(address(this))); + return localContract.rewardbalance; + } + + function otherContractAddrTest() view public returns (uint256) { + address payable localContract = address(uint160(address(contractB))); + return localContract.rewardbalance; + } + + function contractBWithdrawRewardTest() public returns (uint) { + return contractB.withdrawRewardTest(); + } + + function getContractBAddressTest() public returns (address) { + return address(contractB); + } + } + */ + + public String getABI() { + String abi = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\"," + + "\"type\":\"constructor\"},{\"constant\":false," + + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"sr\"," + + "\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\"," + + "\"type\":\"uint256\"}],\"name\":\"contractBStakeTest\"," + + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," + + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," + + "{\"constant\":false,\"inputs\":[],\"name\":\"contractBWithdrawRewardTest\"," + + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," + + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," + + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[]," + + "\"name\":\"getContractBAddressTest\"," + + "\"outputs\":[{\"internalType\":\"address\",\"name\":\"\"," + + "\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," + + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[]," + + "\"name\":\"localContractAddrTest\",\"outputs\":[{\"internalType\":\"uint256\"," + + "\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," + + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," + + "\"inputs\":[],\"name\":\"otherContractAddrTest\"," + + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," + + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," + + "\"type\":\"function\"},{\"constant\":false," + + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"addr\"," + + "\"type\":\"address\"}],\"name\":\"rewardBalanceTest\"," + + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," + + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," + + "\"type\":\"function\"},{\"constant\":false," + + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"sr\"," + + "\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\"," + + "\"type\":\"uint256\"}],\"name\":\"stakeTest\"," + + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," + + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," + + "{\"constant\":false,\"inputs\":[],\"name\":\"unstakeTest\",\"outputs\":[]," + + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," + + "{\"constant\":false,\"inputs\":[],\"name\":\"withdrawRewardTest\"," + + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," + + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," + + "\"type\":\"function\"}]"; + + return abi; + } + + public String getFactoryCode() { + String factoryCode = "60806040526040516100109061005c565b604051809103906" + + "000f08015801561002c573d6000803e3d6000fd5b50600180546001600160a" + + "01b03929092166001600160a01b03199283161790556000805490911633179" + + "055610069565b6101108061039c83390190565b61032480610078600039600" + + "0f3fe608060405234801561001057600080fd5b50d3801561001d57600080f" + + "d5b50d2801561002a57600080fd5b50600436106100ad5760003560e01c806" + + "3b3e835e111610080578063b3e835e114610156578063c290120a146101605" + + "78063cb2d51cf14610168578063d30a28ee14610170578063e49de2d014610" + + "178576100ad565b806310198157146100b257806325a26c30146100d657806" + + "38db848f114610116578063a223c65f14610130575b600080fd5b6100ba610" + + "1a4565b604080516001600160a01b039092168252519081900360200190f35" + + "b610102600480360360408110156100ec57600080fd5b506001600160a01b0" + + "381351690602001356101b3565b60408051911515825251908190036020019" + + "0f35b61011e61023f565b60408051918252519081900360200190f35b61011" + + "e6004803603602081101561014657600080fd5b50356001600160a01b03166" + + "102b6565b61015e6102c3565b005b61011e6102c7565b61011e6102cf565b6" + + "1011e6102d4565b6101026004803603604081101561018e57600080fd5b506" + + "001600160a01b0381351690602001356102e4565b6001546001600160a01b0" + + "31690565b60015460408051630e49de2d60e41b81526001600160a01b03858" + + "1166004830152602482018590529151600093929092169163e49de2d091604" + + "48082019260209290919082900301818787803b15801561020c57600080fd5" + + "b505af1158015610220573d6000803e3d6000fd5b505050506040513d60208" + + "1101561023657600080fd5b50519392505050565b600154604080516361480" + + "90560e11b815290516000926001600160a01b03169163c290120a916004808" + + "30192602092919082900301818787803b15801561028557600080fd5b505af" + + "1158015610299573d6000803e3d6000fd5b505050506040513d60208110156" + + "102af57600080fd5b5051905090565b6001600160a01b0316d890565bd6505" + + "65b6000d7905090565b30d890565b6001546001600160a01b0316d890565b6" + + "0008183d5939250505056fea26474726f6e582064d946716e1b0c5f00dcf70" + + "b3ff065ea0587cd3719b2ba94783edeb58413020464736f6c634300050d003" + + "16080604052600080546001600160a01b0319163317905560ec80610024600" + + "0396000f3fe6080604052348015600f57600080fd5b50d38015601b5760008" + + "0fd5b50d28015602757600080fd5b5060043610604a5760003560e01c8063c" + + "290120a14604f578063e49de2d0146067575b600080fd5b605560a4565b604" + + "08051918252519081900360200190f35b609060048036036040811015607b5" + + "7600080fd5b506001600160a01b03813516906020013560ac565b604080519" + + "115158252519081900360200190f35b6000d7905090565b60008183d593925" + + "0505056fea26474726f6e5820f52f0d803d46c1926596c7faa3b969812b567" + + "66163eb8ca0270d34e3cff1d3b164736f6c634300050d0031"; + + return factoryCode; + } + + @Test + public void testWithdrawRewardInLocalContract() + throws ContractExeException, ReceiptCheckErrException, ValidateSignatureException, + BadNumberBlockException, ValidateScheduleException, ContractValidateException, + VMIllegalException, DupTransactionException, TooBigTransactionException, + TooBigTransactionResultException, BadBlockException, NonCommonBlockException, + TransactionExpirationException, UnLinkedBlockException, TaposException, + ZksnarkException, AccountResourceInsufficientException { + ConfigLoader.disable = true; + VMConfig.initAllowTvmTransferTrc10(1); + VMConfig.initAllowTvmConstantinople(1); + VMConfig.initAllowTvmSolidity059(1); + VMConfig.initAllowTvmStake(1); + manager.getDynamicPropertiesStore().saveChangeDelegation(1); + + Repository repository; + StoreFactory storeFactory = StoreFactory.getInstance(); + ProgramInvokeFactory programInvokeFactory = new ProgramInvokeFactoryImpl(); + VMConfig vmConfig = VMConfig.getInstance(); + + String contractName = "TestWithdrawReward"; + byte[] address = Hex.decode(OWNER_ADDRESS); + String abi = getABI(); + String factoryCode = getFactoryCode(); + + long value = 1000000000; + long fee = 100000000; + long consumeUserResourcePercent = 0; + + String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; + byte[] privateKey = ByteArray.fromHexString(key); + final ECKey ecKey = ECKey.fromPrivate(privateKey); + byte[] witnessAddress = ecKey.getAddress(); + + // deploy contract + Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, + null); + byte[] factoryAddress = WalletUtil.generateContractAddress(trx); + String factoryAddressStr = StringUtil.encode58Check(factoryAddress); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); + Assert.assertNull(runtime.getRuntimeError()); + + WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(witnessAddress)); + Protocol.Block firstBlock = getBlock(witnessCapsule.getAddress(), + System.currentTimeMillis(), privateKey); + + // Trigger contract method: stakeTest(address,uint256) + String methodByAddr = "stakeTest(address,uint256)"; + String witness = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; + byte[] witnessAddr = Hex.decode("a0299f3db80a24b20a254b89ce639d59132f157f13"); + String hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList(witness, 100000000)); + //BlockCapsule blockCap = new BlockCapsule(Protocol.Block.newBuilder().build()); + + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + InternalTransaction rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + ProgramInvoke programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, firstBlock, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + Program program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + boolean programResult = program.stake(new DataWord(witnessAddr), new DataWord(100000000)); + Assert.assertTrue(programResult); + repository.commit(); + + // Do Maintenance & Generate New Block + maintenanceManager.doMaintenance(); + + witnessCapsule = new WitnessCapsule(ByteString.copyFrom(witnessAddress)); + chainBaseManager.addWitness(ByteString.copyFrom(witnessAddress)); + Protocol.Block block = getSignedBlock(witnessCapsule.getAddress(), 1533529947843L, privateKey); + manager.pushBlock(new BlockCapsule(block));//cycle: 1 addReward + + // Trigger contract method: rewardBalanceTest(address) + methodByAddr = "rewardBalanceTest(address)"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + byte[] rewardBalance = program.getRewardBalance(new DataWord(factoryAddress)).getData(); + Assert.assertEquals(Hex.toHexString(rewardBalance), + "0000000000000000000000000000000000000000000000000000000000000000"); + repository.commit(); + + // Trigger contract method: localContractAddrTest() + methodByAddr = "localContractAddrTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + rewardBalance = program.getRewardBalance(new DataWord(factoryAddress)).getData(); + Assert.assertEquals(Hex.toHexString(rewardBalance), + "0000000000000000000000000000000000000000000000000000000000000000"); + repository.commit(); + + Protocol.Block newBlock = getBlock(witnessCapsule.getAddress(), + System.currentTimeMillis(), privateKey); + BlockCapsule blockCapsule = new BlockCapsule(newBlock); + blockCapsule.generatedByMyself = true; + + // Trigger contract method: withdrawRewardTest() + methodByAddr = "withdrawRewardTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCapsule.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + program.withdrawReward(); + Assert.assertEquals(Hex.toHexString(program.stackPop().getData()), + "0000000000000000000000000000000000000000000000000000000000000000"); + repository.commit(); + + // Execute Next Cycle + maintenanceManager.doMaintenance(); + WitnessCapsule localWitnessCapsule = manager.getWitnessStore() + .get(witnessAddr); + Assert.assertEquals(localWitnessCapsule.getVoteCount(), 205); + + // Trigger contract method: rewardBalanceTest(address) + methodByAddr = "rewardBalanceTest(address)"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + rewardBalance = program.getRewardBalance(new DataWord(factoryAddress)).getData(); + BigInteger reward = new BigInteger(Hex.toHexString(rewardBalance), 16); + repository.commit(); + + // Current Reward: Total Reward * Vote Rate + // BigInteger reward = new BigInteger(Hex.toHexString(returnValue), 16); + // byte[] sr1 = decodeFromBase58Check(witness); + // long totalReward = (long) ((double) rootRepository + // .getDelegationStore().getReward(1, sr1)); + // long totalVote = rootRepository.getDelegationStore().getWitnessVote(1, sr1); + // double voteRate = (double) 100 / totalVote; + // long curReward = (long) (totalReward * voteRate); + // Assert.assertEquals(reward.longValue(), curReward); + + //total reward: block reward + vote reward + long blockReward = 25600000; + long voteReward = 2186667; + long totalReward = blockReward + voteReward; + double voteRate = (double) 100 / 205; + long curReward = (long) (totalReward * voteRate); + Assert.assertEquals(reward.longValue(), curReward); + + // Trigger contract method: localContractAddrTest() + methodByAddr = "localContractAddrTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + rewardBalance = program.getRewardBalance(new DataWord(factoryAddress)).getData(); + Assert + .assertEquals((new BigInteger(Hex.toHexString(rewardBalance), 16)).longValue(), curReward); + repository.commit(); + + // Trigger contract method: withdrawRewardTest() + methodByAddr = "withdrawRewardTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCapsule.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + program.withdrawReward(); + Assert.assertEquals((new BigInteger(Hex.toHexString(program.stackPop().getData()), + 16)).longValue(), curReward); + repository.commit(); + + // Trigger contract method: rewardBalanceTest(address) + methodByAddr = "rewardBalanceTest(address)"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + rewardBalance = program.getRewardBalance(new DataWord(factoryAddress)).getData(); + Assert.assertEquals(Hex.toHexString(rewardBalance), + "0000000000000000000000000000000000000000000000000000000000000000"); + repository.commit(); + + // Trigger contract method: localContractAddrTest() + methodByAddr = "localContractAddrTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + rewardBalance = program.getRewardBalance(new DataWord(factoryAddress)).getData(); + Assert.assertEquals(Hex.toHexString(rewardBalance), + "0000000000000000000000000000000000000000000000000000000000000000"); + repository.commit(); + + // Trigger contract method: withdrawRewardTest() + methodByAddr = "withdrawRewardTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCapsule.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + program.withdrawReward(); + Assert.assertEquals((new BigInteger(Hex.toHexString(program.stackPop().getData()), + 16)).longValue(), 0); + repository.commit(); + + ConfigLoader.disable = false; + } + + @Test + public void testWithdrawRewardInAnotherContract() + throws ContractExeException, ReceiptCheckErrException, VMIllegalException, + ContractValidateException, DupTransactionException, TooBigTransactionException, + AccountResourceInsufficientException, BadBlockException, NonCommonBlockException, + TransactionExpirationException, UnLinkedBlockException, ZksnarkException, + TaposException, TooBigTransactionResultException, ValidateSignatureException, + BadNumberBlockException, ValidateScheduleException { + ConfigLoader.disable = true; + VMConfig.initAllowTvmTransferTrc10(1); + VMConfig.initAllowTvmConstantinople(1); + VMConfig.initAllowTvmSolidity059(1); + VMConfig.initAllowTvmStake(1); + manager.getDynamicPropertiesStore().saveChangeDelegation(1); + + Repository repository; + StoreFactory storeFactory = StoreFactory.getInstance(); + ProgramInvokeFactory programInvokeFactory = new ProgramInvokeFactoryImpl(); + VMConfig vmConfig = VMConfig.getInstance(); + + String contractName = "TestWithdrawRewardWithContract"; + byte[] address = Hex.decode(OWNER_ADDRESS); + String abi = getABI(); + String factoryCode = getFactoryCode(); + long value = 1000000000; + long fee = 100000000; + long consumeUserResourcePercent = 0; + + // deploy contract - 27kR8yXGYQykQ2fgH3h9sqfNBSeEh23ggja + Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, + null); + byte[] factoryAddress = WalletUtil.generateContractAddress(trx); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); + Assert.assertNull(runtime.getRuntimeError()); + + // Trigger contract method: getContractBAddressTest() + String methodByAddr = "getContractBAddressTest()"; + String hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + TVMTestResult result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); + Assert.assertNull(result.getRuntime().getRuntimeError()); + byte[] returnValue = result.getRuntime().getResult().getHReturn(); + + // Contract B Address: 27Wvtyhk4hHqRzogLPSJ21TjDdpuTJZWvQD" + String tmpAddress = "a0" + Hex.toHexString(returnValue).substring(24); + byte[] contractBAddrByte = ByteArray.fromHexString(tmpAddress); + String contractBAddress = StringUtil.encode58Check(contractBAddrByte); + rootRepository.addBalance(Hex.decode(tmpAddress), 30000000000000L); + rootRepository.commit(); + + // Trigger contract method: contractBStakeTest(address,uint256) + methodByAddr = "contractBStakeTest(address,uint256)"; + String witness = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; + byte[] witnessAddr = Hex.decode("a0299f3db80a24b20a254b89ce639d59132f157f13"); + hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList(witness, 200000000)); + + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + contractBAddrByte, Hex.decode(hexInput), 0, fee); + InternalTransaction rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + ProgramInvoke programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + Program program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + boolean programResult = program.stake(new DataWord(witnessAddr), new DataWord(200000000)); + Assert.assertTrue(programResult); + repository.commit(); + + // Do Maintenance & Generate New Block + maintenanceManager.doMaintenance(); + String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; + byte[] privateKey = ByteArray.fromHexString(key); + final ECKey ecKey = ECKey.fromPrivate(privateKey); + byte[] witnessAddress = ecKey.getAddress(); + WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(witnessAddress)); + chainBaseManager.addWitness(ByteString.copyFrom(witnessAddress)); + Protocol.Block block = getSignedBlock(witnessCapsule.getAddress(), 1533529947843L, privateKey); + manager.pushBlock(new BlockCapsule(block));//cycle: 1 addReward + + // Trigger contract method: rewardBalanceTest(address) + methodByAddr = "rewardBalanceTest(address)"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(contractBAddress)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + byte[] rewardBalance = program.getRewardBalance(new DataWord(contractBAddrByte)).getData(); + Assert.assertEquals(Hex.toHexString(rewardBalance), + "0000000000000000000000000000000000000000000000000000000000000000"); + repository.commit(); + + // Trigger contract method: otherContractAddrTest() + methodByAddr = "otherContractAddrTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + rewardBalance = program.getRewardBalance(new DataWord(contractBAddrByte)).getData(); + Assert.assertEquals(Hex.toHexString(rewardBalance), + "0000000000000000000000000000000000000000000000000000000000000000"); + repository.commit(); + + // Trigger contract method: contractBWithdrawRewardTest() + Protocol.Block newBlock = getBlock(witnessCapsule.getAddress(), + System.currentTimeMillis(), privateKey); + BlockCapsule blockCapsule = new BlockCapsule(newBlock); + blockCapsule.generatedByMyself = true; + + methodByAddr = "contractBWithdrawRewardTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + contractBAddrByte, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCapsule.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + program.withdrawReward(); + Assert.assertEquals((new BigInteger(Hex.toHexString(program.stackPop().getData()), + 16)).longValue(), 0); + repository.commit(); + + // Execute Next Cycle + maintenanceManager.doMaintenance(); + WitnessCapsule localWitnessCapsule = manager.getWitnessStore().get(witnessAddr); + Assert.assertEquals(localWitnessCapsule.getVoteCount(), 305); + + // Trigger contract method: rewardBalanceTest(address) + methodByAddr = "rewardBalanceTest(address)"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(contractBAddress)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + rewardBalance = program.getRewardBalance(new DataWord(contractBAddrByte)).getData(); + BigInteger reward = new BigInteger(Hex.toHexString(rewardBalance), 16); + repository.commit(); + + // Current Reward: Total Reward * Vote Rate + // byte[] sr1 = decodeFromBase58Check(witness); + // long totalReward = (long) ((double) rootRepository + // .getDelegationStore().getReward(1, sr1)); + // long totalVote = rootRepository.getDelegationStore().getWitnessVote(1, sr1); + // double voteRate = (double) 200 / totalVote; + // long curReward = (long) (totalReward * voteRate); + // Assert.assertEquals(curReward, reward.longValue()); + + //total reward: block reward + vote reward + long blockReward = 25600000; + long voteReward = 3003077; + long totalReward = blockReward + voteReward; + double voteRate = (double) 200 / 305; + long curReward = (long) (totalReward * voteRate); + Assert.assertEquals(reward.longValue(), curReward); + + // Trigger contract method: otherContractAddrTest() + methodByAddr = "otherContractAddrTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + contractBAddrByte, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + rewardBalance = program.getRewardBalance(new DataWord(contractBAddrByte)).getData(); + reward = new BigInteger(Hex.toHexString(rewardBalance), 16); + Assert.assertEquals(reward.longValue(), curReward); + repository.commit(); + + // Trigger contract method: contractBWithdrawRewardTest() + methodByAddr = "contractBWithdrawRewardTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + contractBAddrByte, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCapsule.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + program.withdrawReward(); + Assert.assertEquals((new BigInteger(Hex.toHexString(program.stackPop().getData()), + 16)).longValue(), curReward); + repository.commit(); + + // Trigger contract method: rewardBalanceTest(address) + methodByAddr = "rewardBalanceTest(address)"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(contractBAddress)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + rewardBalance = program.getRewardBalance(new DataWord(contractBAddrByte)).getData(); + reward = new BigInteger(Hex.toHexString(rewardBalance), 16); + Assert.assertEquals(reward.longValue(), 0); + repository.commit(); + + // Trigger contract method: otherContractAddrTest() + methodByAddr = "otherContractAddrTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + contractBAddrByte, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + rewardBalance = program.getRewardBalance(new DataWord(contractBAddrByte)).getData(); + reward = new BigInteger(Hex.toHexString(rewardBalance), 16); + Assert.assertEquals(reward.longValue(), 0); + repository.commit(); + + // Trigger contract method: contractBWithdrawRewardTest() + methodByAddr = "contractBWithdrawRewardTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + contractBAddrByte, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + program.withdrawReward(); + Assert.assertEquals((new BigInteger(Hex.toHexString(program.stackPop().getData()), + 16)).longValue(), 0); + repository.commit(); + + ConfigLoader.disable = false; + } + + 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 = manager + .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); + 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(); + + Protocol.Block signedBlock = block.toBuilder().setBlockHeader(blockHeader).build(); + + return signedBlock; + } + + public Protocol.Block getBlock(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 = manager + .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); + 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(ByteString.copyFromUtf8("")) + .build(); + Protocol.Block signedBlock = block.toBuilder().setBlockHeader(blockHeader).build(); + return signedBlock; + } + + @Test + public void testWithdrawRewardInLocalContractAfter24Hour() + throws ContractExeException, ReceiptCheckErrException, ValidateSignatureException, + BadNumberBlockException, ValidateScheduleException, ContractValidateException, + VMIllegalException, DupTransactionException, TooBigTransactionException, + TooBigTransactionResultException, BadBlockException, NonCommonBlockException, + TransactionExpirationException, UnLinkedBlockException, TaposException, + ZksnarkException, AccountResourceInsufficientException { + ConfigLoader.disable = true; + VMConfig.initAllowTvmTransferTrc10(1); + VMConfig.initAllowTvmConstantinople(1); + VMConfig.initAllowTvmSolidity059(1); + VMConfig.initAllowTvmStake(1); + manager.getDynamicPropertiesStore().saveChangeDelegation(1); + + Repository repository; + StoreFactory storeFactory = StoreFactory.getInstance(); + ProgramInvokeFactory programInvokeFactory = new ProgramInvokeFactoryImpl(); + VMConfig vmConfig = VMConfig.getInstance(); + + String contractName = "TestWithdrawReward"; + byte[] address = Hex.decode(OWNER_ADDRESS); + String abi = getABI(); + String factoryCode = getFactoryCode(); + long value = 1000000000; + long fee = 100000000; + long consumeUserResourcePercent = 0; + String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; + byte[] privateKey = ByteArray.fromHexString(key); + final ECKey ecKey = ECKey.fromPrivate(privateKey); + byte[] witnessAddress = ecKey.getAddress(); + + // deploy contract + Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, + null); + byte[] factoryAddress = WalletUtil.generateContractAddress(trx); + String factoryAddressStr = StringUtil.encode58Check(factoryAddress); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); + Assert.assertNull(runtime.getRuntimeError()); + + WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(witnessAddress)); + Protocol.Block firstBlock = getBlock(witnessCapsule.getAddress(), + System.currentTimeMillis(), privateKey); + + // Trigger contract method: stakeTest(address,uint256) + String methodByAddr = "stakeTest(address,uint256)"; + String witness = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; + byte[] witnessAddr = Hex.decode("a0299f3db80a24b20a254b89ce639d59132f157f13"); + String hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList(witness, 100000000)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + InternalTransaction rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + ProgramInvoke programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, firstBlock, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + Program program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + boolean programResult = program.stake(new DataWord(witnessAddr), new DataWord(100000000)); + Assert.assertTrue(programResult); + repository.commit(); + + // Do Maintenance & Generate New Block + maintenanceManager.doMaintenance(); + + witnessCapsule = new WitnessCapsule(ByteString.copyFrom(witnessAddress)); + chainBaseManager.addWitness(ByteString.copyFrom(witnessAddress)); + Protocol.Block block = getSignedBlock(witnessCapsule.getAddress(), + System.currentTimeMillis(), privateKey); + manager.pushBlock(new BlockCapsule(block));//cycle: 1 addReward + + // Trigger contract method: rewardBalanceTest(address) + methodByAddr = "rewardBalanceTest(address)"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + byte[] rewardBalance = program.getRewardBalance(new DataWord(factoryAddress)).getData(); + Assert.assertEquals(Hex.toHexString(rewardBalance), + "0000000000000000000000000000000000000000000000000000000000000000"); + repository.commit(); + + Protocol.Block newBlock = getBlock(witnessCapsule.getAddress(), + System.currentTimeMillis(), privateKey); + BlockCapsule blockCapsule = new BlockCapsule(newBlock); + blockCapsule.generatedByMyself = true; + + // Trigger contract method: withdrawRewardTest() + methodByAddr = "withdrawRewardTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCapsule.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + program.withdrawReward(); + Assert.assertEquals(Hex.toHexString(program.stackPop().getData()), + "0000000000000000000000000000000000000000000000000000000000000000"); + repository.commit(); + + // Execute Next Cycle + maintenanceManager.doMaintenance(); + WitnessCapsule localWitnessCapsule = manager.getWitnessStore() + .get(witnessAddr); + Assert.assertEquals(205, localWitnessCapsule.getVoteCount()); + + // Trigger contract method: rewardBalanceTest(address) + methodByAddr = "rewardBalanceTest(address)"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + rewardBalance = program.getRewardBalance(new DataWord(factoryAddress)).getData(); + repository.commit(); + BigInteger reward = new BigInteger(Hex.toHexString(rewardBalance), 16); + + // Current Reward: Total Reward * Vote Rate + // BigInteger reward = new BigInteger(Hex.toHexString(returnValue), 16); + // byte[] sr1 = decodeFromBase58Check(witness); + // long totalReward = (long) ((double) rootRepository + // .getDelegationStore().getReward(1, sr1)); + // long totalVote = rootRepository.getDelegationStore().getWitnessVote(1, sr1); + // double voteRate = (double) 100 / totalVote; + // long curReward = (long) (totalReward * voteRate); + // Assert.assertEquals(reward.longValue(), curReward); + + //total reward: block reward + vote reward + long blockReward = 25600000; + long voteReward = 2186667; + long totalReward = blockReward + voteReward; + double voteRate = (double) 100 / 205; + long curReward = (long) (totalReward * voteRate); + Assert.assertEquals(reward.longValue(), curReward); + + // Trigger contract method: localContractAddrTest() + methodByAddr = "localContractAddrTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + rewardBalance = program.getRewardBalance(new DataWord(factoryAddress)).getData(); + repository.commit(); + Assert + .assertEquals((new BigInteger(Hex.toHexString(rewardBalance), 16)).longValue(), curReward); + + // Trigger contract method: withdrawRewardTest() + methodByAddr = "withdrawRewardTest()"; + + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCapsule.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + program.withdrawReward(); + Assert.assertEquals((new BigInteger(Hex.toHexString(program.stackPop().getData()), 16)) + .longValue(), curReward); + repository.commit(); + + // Trigger contract method: rewardBalanceTest(address) + methodByAddr = "rewardBalanceTest(address)"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, null, repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + rewardBalance = program.getRewardBalance(new DataWord(factoryAddress)).getData(); + repository.commit(); + Assert.assertEquals((new BigInteger(Hex.toHexString(rewardBalance), 16)).longValue(), 0); + + // Trigger contract method: withdrawRewardTest() + methodByAddr = "withdrawRewardTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCapsule.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + program.withdrawReward(); + Assert.assertEquals((new BigInteger(Hex.toHexString(program.stackPop().getData()), 16)) + .longValue(), 0); + repository.commit(); + + // Within 24 Hours + long num = chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber(); + ByteString latestHeadHash = + chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderHash().getByteString(); + blockCapsule = + createTestBlockCapsule( + System.currentTimeMillis() + 80400000, + num + 1, + latestHeadHash); + manager.pushBlock(blockCapsule); + + // long currentTime = System.currentTimeMillis(); + // for (int i = 0; i < (86400 / 3 - 3); i++) { + // currentTime += 3000; + // ByteString latestHeadHash = chainBaseManager.getDynamicPropertiesStore() + // .getLatestBlockHeaderHash().getByteString(); + // blockCapsule = + // createTestBlockCapsule( + // currentTime, + // ++num, + // latestHeadHash, + // privateKey); + // manager.pushBlock(blockCapsule); + // } + + // Trigger contract method: withdrawRewardTest() + methodByAddr = "withdrawRewardTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCapsule.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + program.withdrawReward(); + Assert.assertEquals((new BigInteger(Hex.toHexString(program.stackPop().getData()), 16)) + .longValue(), 0); + repository.commit(); + + // After 24 Hours + num = chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber(); + latestHeadHash = + chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderHash().getByteString(); + blockCapsule = + createTestBlockCapsule( + System.currentTimeMillis() + 86400000 + 3000, + num + 1, + latestHeadHash); + manager.pushBlock(blockCapsule); + // for (int i = 0; i < 3; i++) { + // currentTime += 3000; + // ByteString latestHeadHash = chainBaseManager.getDynamicPropertiesStore() + // .getLatestBlockHeaderHash().getByteString(); + // blockCapsule = + // createTestBlockCapsule( + // currentTime, + // ++num, + // latestHeadHash, + // privateKey); + // manager.pushBlock(blockCapsule); + // } + + // Trigger contract method: withdrawRewardTest() + methodByAddr = "withdrawRewardTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + trx = TvmTestUtils.generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee); + rootInternalTransaction = new InternalTransaction(trx, + InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE); + repository = RepositoryImpl.createRoot(storeFactory); + programInvoke = programInvokeFactory + .createProgramInvoke(InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE, + InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, + 0, 0, blockCapsule.getInstance(), repository, System.nanoTime() / 1000, + System.nanoTime() / 1000 + 50000, 3_000_000L); + program = new Program(null, programInvoke, rootInternalTransaction, vmConfig); + program.withdrawReward(); + repository.commit(); + + curReward = repository.getDelegationStore().getReward(2, witnessAddr) * 100 / 205; + // Assert.assertEquals((new BigInteger(Hex.toHexString(program.stackPop().getData()), 16)) + // .longValue(), curReward); + + ConfigLoader.disable = false; + } + + private BlockCapsule createTestBlockCapsule(long time, + long number, ByteString hash) { + ByteString witnessAddress = dposSlot.getScheduledWitness(dposSlot.getSlot(time)); + BlockCapsule blockCapsule = new BlockCapsule(number, Sha256Hash.wrap(hash), time, + witnessAddress); + blockCapsule.generatedByMyself = true; + blockCapsule.setMerkleRoot(); + //blockCapsule.sign(privateKey); + //blockCapsule.sign(ByteArray.fromHexString(privateKey.get(witnessAddress))); + return blockCapsule; + } +} + + diff --git a/framework/src/test/java/org/tron/core/ShieldedTRC20BuilderTest.java b/framework/src/test/java/org/tron/core/ShieldedTRC20BuilderTest.java index 606a23a8b1f..f471d126d0c 100644 --- a/framework/src/test/java/org/tron/core/ShieldedTRC20BuilderTest.java +++ b/framework/src/test/java/org/tron/core/ShieldedTRC20BuilderTest.java @@ -132,7 +132,7 @@ public void createShieldedContractParametersForMint() Assert.assertEquals(1, result[31]); //update frontier and leafCount - //if slot == 0, frontier[0:31]=noteCommitment + int slot = result[63]; if (slot == 0) { System.arraycopy(inputData, 0, frontier, 0, 32); @@ -145,9 +145,12 @@ public void createShieldedContractParametersForMint() } } + /* + * With 1 mint, 1 spendNote, 1 receiveNote + * */ @Ignore @Test - public void createShieldedContractParametersForTransfer1v1() + public void createShieldedContractParametersForTransfer1to1() throws ZksnarkException, ContractValidateException, ContractExeException { int totalCountNum = 2; long leafCount = 0; @@ -245,6 +248,7 @@ public void createShieldedContractParametersForTransfer1v1() Assert.assertEquals(1, result[31]); //update frontier and leafCount + //if slot == 0, frontier[0:31]=noteCommitment int idx = 63; int slot = result[idx]; if (slot == 0) { @@ -272,9 +276,12 @@ public void createShieldedContractParametersForTransfer1v1() } } + /* + * With 1 mint, 1 spendNote, 2 receiveNote + * */ @Ignore @Test - public void createShieldedContractParametersForTransfer1v2() + public void createShieldedContractParametersForTransfer1to2() throws ZksnarkException, ContractValidateException, ContractExeException { int totalCountNum = 2; long leafCount = 0; @@ -386,6 +393,7 @@ public void createShieldedContractParametersForTransfer1v2() Assert.assertEquals(1, result[31]); //update frontier and leafCount + //if slot == 0, frontier[0:31]=noteCommitment int idx = 32; for (int i = 0; i < 2; i++) { idx += 31; @@ -418,9 +426,12 @@ public void createShieldedContractParametersForTransfer1v2() } } + /* + * With 2 mint, 2 spendNote, 1 receiveNote + * */ @Ignore @Test - public void createShieldedContractParametersForTransfer2v1() + public void createShieldedContractParametersForTransfer2to1() throws ZksnarkException, ContractValidateException, ContractExeException { int totalCountNum = 2; long leafCount = 0; @@ -574,6 +585,7 @@ public void createShieldedContractParametersForTransfer2v1() Assert.assertEquals(1, result[31]); //update frontier and leafCount + //if slot == 0, frontier[0:31]=noteCommitment int idx = 63; int slot = result[idx]; if (slot == 0) { @@ -602,10 +614,12 @@ public void createShieldedContractParametersForTransfer2v1() } } - + /* + * With 2 mint, 2 spendNote, 2 receiveNote + * */ @Ignore @Test - public void createShieldedContractParametersForTransfer2v2() + public void createShieldedContractParametersForTransfer2to2() throws ZksnarkException, ContractValidateException, ContractExeException { int totalCountNum = 2; long leafCount = 0; @@ -771,6 +785,7 @@ public void createShieldedContractParametersForTransfer2v2() Assert.assertEquals(1, result[31]); //update frontier and leafCount + //if slot == 0, frontier[0:31]=noteCommitment int idx = 32; for (int i = 0; i < 2; i++) { idx += 31; @@ -803,9 +818,12 @@ public void createShieldedContractParametersForTransfer2v2() } } + /* + * With 1 spendNote + */ @Ignore @Test - public void createShieldedContractParametersForBurn() + public void createShieldedContractParametersForBurn1() throws ZksnarkException, ContractValidateException, ContractExeException { int totalCountNum = 2; long leafCount = 0; @@ -896,9 +914,12 @@ public void createShieldedContractParametersForBurn() } } + /* + * With 1 spendNote, 1 receiveNote + */ @Ignore @Test - public void createShieldedContractParametersForBurn1v2() + public void createShieldedContractParametersForBurn1to1() throws ZksnarkException, ContractValidateException, ContractExeException { int totalCountNum = 2; long leafCount = 0; @@ -1015,10 +1036,12 @@ public void createShieldedContractParametersForBurn1v2() } } - + /* + * With 1 mint, 1 spendNote, 1 receiveNote + */ @Ignore @Test - public void createShieldedContractParametersWithouAskForTransfer1v1() + public void createShieldedContractParametersWithoutAskForTransfer1to1() throws Exception { int totalCountNum = 2; long leafCount = 0; @@ -1156,6 +1179,7 @@ public void createShieldedContractParametersWithouAskForTransfer1v1() Assert.assertEquals(1, result[31]); //update frontier and leafCount + //if slot == 0, frontier[0:31]=noteCommitment int idx = 63; int slot = result[idx]; if (slot == 0) { @@ -1185,9 +1209,12 @@ public void createShieldedContractParametersWithouAskForTransfer1v1() } } + /* + * With 1 mint, 1 spendNote, 2 receiveNote + */ @Ignore @Test - public void createShieldedContractParametersWithouAskForTransfer1v2() + public void createShieldedContractParametersWithoutAskForTransfer1to2() throws Exception { int totalCountNum = 2; long leafCount = 0; @@ -1338,6 +1365,7 @@ public void createShieldedContractParametersWithouAskForTransfer1v2() Assert.assertEquals(1, result[31]); //update frontier and leafCount + //if slot == 0, frontier[0:31]=noteCommitment int idx = 32; for (int i = 0; i < 2; i++) { idx += 31; @@ -1370,9 +1398,12 @@ public void createShieldedContractParametersWithouAskForTransfer1v2() } } + /* + * With 2 mint, 2 spendNote, 1 receiveNote + */ @Ignore @Test - public void createShieldedContractParametersWithouAskForTransfer2v1() + public void createShieldedContractParametersWithoutAskForTransfer2to1() throws Exception { int totalCountNum = 2; long leafCount = 0; @@ -1581,6 +1612,7 @@ public void createShieldedContractParametersWithouAskForTransfer2v1() Assert.assertEquals(1, result[31]); //update frontier and leafCount + //if slot == 0, frontier[0:31]=noteCommitment int idx = 63; int slot = result[idx]; if (slot == 0) { @@ -1609,9 +1641,12 @@ public void createShieldedContractParametersWithouAskForTransfer2v1() } } + /* + * With 2 mint, 2 spendNote, 2 receiveNote + */ @Ignore @Test - public void createShieldedContractParametersWithouAskForTransfer2v2() + public void createShieldedContractParametersWithoutAskForTransfer2to2() throws Exception { int totalCountNum = 2; long leafCount = 0; @@ -1833,6 +1868,7 @@ public void createShieldedContractParametersWithouAskForTransfer2v2() Assert.assertEquals(1, result[31]); //update frontier and leafCount + //if slot == 0, frontier[0:31]=noteCommitment int idx = 32; for (int i = 0; i < 2; i++) { idx += 31; @@ -1865,9 +1901,13 @@ public void createShieldedContractParametersWithouAskForTransfer2v2() } } + /* + * With 1 mint, 1 spendNote + * Burn to Transparent address + */ @Ignore @Test - public void createShieldedContractParametersWithoutAskForBurn() + public void createShieldedContractParametersWithoutAskForBurn1to1() throws Exception { int totalCountNum = 2; long leafCount = 0; @@ -1997,9 +2037,13 @@ public void createShieldedContractParametersWithoutAskForBurn() } } + /* + * With 1 mint, 1 spendNote, 1 receiveNote + * Burn to Transparent address and A change z-address + */ @Ignore @Test - public void createShieldedContractParametersWithoutAskForBurn1v2() + public void createShieldedContractParametersWithoutAskForBurn1to2() throws Exception { int totalCountNum = 2; long leafCount = 0; diff --git a/framework/src/test/java/org/tron/core/WalletTest.java b/framework/src/test/java/org/tron/core/WalletTest.java index 71d2b2a4c81..4c0ff5ed6c4 100644 --- a/framework/src/test/java/org/tron/core/WalletTest.java +++ b/framework/src/test/java/org/tron/core/WalletTest.java @@ -524,6 +524,5 @@ public void testChainParameters() { System.out.printf(builder.build().toString()); } - } 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 4b96f94015b..ef979d8acb9 100644 --- a/framework/src/test/java/org/tron/core/actuator/WithdrawBalanceActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/WithdrawBalanceActuatorTest.java @@ -100,7 +100,7 @@ public void testWithdrawBalance() { dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); byte[] address = ByteArray.fromHexString(OWNER_ADDRESS); try { - dbManager.getDelegationService() + dbManager.getMortgageService() .adjustAllowance(dbManager.getAccountStore(), address, allowance); } catch (BalanceInsufficientException e) { fail("BalanceInsufficientException"); @@ -247,7 +247,7 @@ public void isGR() { dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); try { - dbManager.getDelegationService() + dbManager.getMortgageService() .adjustAllowance(dbManager.getAccountStore(), address, allowance); } catch (BalanceInsufficientException e) { fail("BalanceInsufficientException"); @@ -290,7 +290,7 @@ public void notTimeToWithdraw() { byte[] address = ByteArray.fromHexString(OWNER_ADDRESS); try { - dbManager.getDelegationService() + dbManager.getMortgageService() .adjustAllowance(dbManager.getAccountStore(), address, allowance); } catch (BalanceInsufficientException e) { fail("BalanceInsufficientException"); @@ -345,7 +345,7 @@ public void commonErrorCheck() { dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); byte[] address = ByteArray.fromHexString(OWNER_ADDRESS); try { - dbManager.getDelegationService() + dbManager.getMortgageService() .adjustAllowance(dbManager.getAccountStore(), address, allowance); } catch (BalanceInsufficientException e) { fail("BalanceInsufficientException"); 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 cd35a1ecf4d..cfd71080e4a 100644 --- a/framework/src/test/java/org/tron/core/net/BaseNet.java +++ b/framework/src/test/java/org/tron/core/net/BaseNet.java @@ -27,6 +27,7 @@ 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.config.args.Args; import org.tron.core.net.peer.PeerConnection; @@ -69,7 +70,7 @@ protected void initChannel(Channel ch) throws Exception { }).option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 60000) .option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT); - return b.connect("127.0.0.1", port).sync().channel(); + return b.connect(Constant.LOCAL_HOST, port).sync().channel(); } @Before @@ -89,7 +90,7 @@ public void run() { CommonParameter parameter = Args.getInstance(); parameter.setNodeListenPort(port); parameter.getSeedNode().getIpList().clear(); - parameter.setNodeExternalIp("127.0.0.1"); + parameter.setNodeExternalIp(Constant.LOCAL_HOST); context = new TronApplicationContext(DefaultConfig.class); appT = ApplicationFactory.create(context); rpcApiService = context.getBean(RpcApiService.class); 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 6d2925f12f6..f5edf091a13 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,5 +1,7 @@ package org.tron.core.net.messagehandler; +import com.google.common.collect.ImmutableList; +import com.google.protobuf.ByteString; import java.util.List; import org.junit.After; import org.junit.Assert; @@ -11,6 +13,7 @@ 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; import org.tron.core.net.message.BlockMessage; @@ -51,10 +54,13 @@ public void testProcessMessage() { } try { - List transactionList = Lists.newArrayList(); - for (int i = 0; i < 1100000; i++) { - transactionList.add(Transaction.newBuilder().build()); - } + List transactionList = ImmutableList.of( + Transaction.newBuilder() + .setRawData(Transaction.raw.newBuilder() + .setData( + ByteString.copyFrom( + new byte[Parameter.ChainConstant.BLOCK_SIZE + Constant.ONE_THOUSAND]))) + .build()); blockCapsule = new BlockCapsule(1, Sha256Hash.ZERO_HASH.getByteString(), System.currentTimeMillis() + 10000, transactionList); msg = new BlockMessage(blockCapsule); 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 c8a9f89acea..dc99cb8f4af 100644 --- a/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java +++ b/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java @@ -14,19 +14,19 @@ import org.tron.common.application.TronApplicationContext; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.db.DelegationService; import org.tron.core.db.Manager; +import org.tron.core.service.MortgageService; import org.tron.protos.contract.StorageContract.UpdateBrokerageContract; @Slf4j public class DelegationServiceTest { private static String fullnode = "127.0.0.1:50051"; - private DelegationService delegationService; + private MortgageService mortgageService; private Manager manager; public DelegationServiceTest(TronApplicationContext context) { - delegationService = context.getBean(DelegationService.class); + mortgageService = context.getBean(MortgageService.class); manager = context.getBean(Manager.class); } @@ -56,7 +56,7 @@ private void testPay(int cycle) { } else if (cycle == 1) { rate = 0.2; } - delegationService.payStandbyWitness(); + mortgageService.payStandbyWitness(); Wallet.setAddressPreFixByte(ADD_PRE_FIX_BYTE_MAINNET); byte[] sr1 = decodeFromBase58Check("TLTDZBcPoJ8tZ6TTEeEqEvwYFk2wgotSfD"); long value = manager.getDelegationStore().getReward(cycle, sr1); @@ -69,7 +69,7 @@ private void testPay(int cycle) { long brokerageAmount = (long) (rate * expect); expect -= brokerageAmount; Assert.assertEquals(expect, value); - delegationService.payBlockReward(sr1, 32000000); + mortgageService.payBlockReward(sr1, 32000000); expect += 32000000; brokerageAmount = (long) (rate * 32000000); expect -= brokerageAmount; @@ -90,7 +90,7 @@ private void testWithdraw() { manager.getAccountStore().put(sr1, accountCapsule); // long allowance = accountCapsule.getAllowance(); - long value = delegationService.queryReward(sr1) - allowance; + long value = mortgageService.queryReward(sr1) - allowance; long reward1 = (long) ((double) manager.getDelegationStore().getReward(0, sr27) / 100000000 * 10000000); long reward2 = (long) ((double) manager.getDelegationStore().getReward(1, sr27) / 100000000 @@ -98,7 +98,7 @@ private void testWithdraw() { long reward = reward1 + reward2; System.out.println("testWithdraw:" + value + ", reward:" + reward); Assert.assertEquals(reward, value); - delegationService.withdrawReward(sr1); + mortgageService.withdrawReward(sr1); accountCapsule = manager.getAccountStore().get(sr1); allowance = accountCapsule.getAllowance() - allowance; System.out.println("withdrawReward:" + allowance); diff --git a/framework/src/test/java/org/tron/program/SolidityNodeTest.java b/framework/src/test/java/org/tron/program/SolidityNodeTest.java index d5cdcc037a8..307b44d0b9c 100755 --- a/framework/src/test/java/org/tron/program/SolidityNodeTest.java +++ b/framework/src/test/java/org/tron/program/SolidityNodeTest.java @@ -90,9 +90,9 @@ public void testSolidityGrpcCall() { DynamicProperties dynamicProperties = databaseGrpcClient.getDynamicProperties(); Assert.assertNotNull(dynamicProperties); - Block genisisBlock = databaseGrpcClient.getBlock(0); - Assert.assertNotNull(genisisBlock); - Assert.assertFalse(genisisBlock.getTransactionsList().isEmpty()); + Block genesisBlock = databaseGrpcClient.getBlock(0); + Assert.assertNotNull(genesisBlock); + Assert.assertFalse(genesisBlock.getTransactionsList().isEmpty()); } } diff --git a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount003.java b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount003.java index d4269b36b61..4baca5a5d6e 100644 --- a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount003.java +++ b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount003.java @@ -217,11 +217,7 @@ public Boolean createWitness(byte[] owner, byte[] url, String priKey) { } transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } + return response.getResult(); } /** diff --git a/framework/src/test/java/stest/tron/wallet/common/client/WalletClient.java b/framework/src/test/java/stest/tron/wallet/common/client/WalletClient.java index 3096c4679a8..b3dbcb11715 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/WalletClient.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/WalletClient.java @@ -29,7 +29,7 @@ import org.tron.common.utils.Sha256Hash; import org.tron.common.utils.Utils; import org.tron.core.exception.CancelException; -import org.tron.keystore.CipherException; +import org.tron.core.exception.CipherException; import org.tron.protos.Protocol.Account; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Block; diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/Base58.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/Base58.java index 56aa95a9363..6fd13777927 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/Base58.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/utils/Base58.java @@ -3,6 +3,7 @@ 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; public class Base58 { @@ -173,33 +174,13 @@ public static byte[] decodeFromBase58Check(String addressBase58) { + " !!"); return null; } - byte[] address = decode58Check(addressBase58); + byte[] address = Commons.decode58Check(addressBase58); if (!addressValid(address)) { return null; } return address; } - public static byte[] decode58Check(String input) { - byte[] decodeCheck = 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. */ 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 index b85dc31188f..ec4b061d1b7 100644 --- 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 @@ -1,12 +1,25 @@ 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 { @@ -17,6 +30,15 @@ public class DailyBuildReport extends TestListenerAdapter { 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) { @@ -58,6 +80,18 @@ public void onFinish(ITestContext testContext) { 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()); @@ -80,5 +114,54 @@ public void onFinish(ITestContext testContext) { } + /** + * 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/HttpMethed.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java index 52bf514c9f8..08093aff3c3 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java @@ -774,6 +774,20 @@ public static String triggerContractGetTxid(String httpNode, byte[] ownerAddress public static String triggerContractGetTxidWithVisibleTrue(String httpNode, String ownerAddress, String contractAddress, String functionSelector, String parameter, Long feeLimit, Long callValue, Integer tokenId, Long tokenValue, String fromKey) { + return triggerContractGetTxidWithVisibleTrue(httpNode, "", ownerAddress, + contractAddress, functionSelector, parameter, feeLimit, callValue, tokenId, tokenValue, + fromKey); + + } + + /** + * constructor. + */ + public static String triggerContractGetTxidWithVisibleTrue(String httpNode, + String anotherHttpNode, + String ownerAddress, + String contractAddress, String functionSelector, String parameter, Long feeLimit, + Long callValue, Integer tokenId, Long tokenValue, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/triggersmartcontract"; JsonObject userBaseObj2 = new JsonObject(); @@ -794,6 +808,9 @@ public static String triggerContractGetTxidWithVisibleTrue(String httpNode, Stri parseStringContent(transactionString).getString("transaction"), fromKey); logger.info(transactionSignString); response = broadcastTransaction(httpNode, transactionSignString); + if (!anotherHttpNode.isEmpty()) { + broadcastTransaction(anotherHttpNode, transactionSignString); + } } catch (Exception e) { e.printStackTrace(); httppost.releaseConnection(); @@ -850,6 +867,51 @@ public static HttpResponse triggerConstantContract(String httpNode, byte[] owner } } + /** + * constructor. + */ + public static HttpResponse triggerConstantContractFromSolidity(String httSoliditypNode, + byte[] ownerAddress, + String contractAddress, String functionSelector, String parameter) { + try { + final String requestUrl = + "http://" + httSoliditypNode + "/walletsolidity/triggerconstantcontract"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("function_selector", functionSelector); + userBaseObj2.addProperty("parameter", parameter); + response = createConnect(requestUrl, userBaseObj2); + return response; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** + * constructor. + */ + public static HttpResponse triggerConstantContractFromPbft(String httpPbftNode, + byte[] ownerAddress, + String contractAddress, String functionSelector, String parameter) { + try { + final String requestUrl = "http://" + httpPbftNode + "/walletpbft/triggerconstantcontract"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("function_selector", functionSelector); + userBaseObj2.addProperty("parameter", parameter); + response = createConnect(requestUrl, userBaseObj2); + return response; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + /** * constructor. */ @@ -1557,6 +1619,24 @@ public static HttpResponse getAssetIssueListByNameFromSolidity(String httpSolidi return response; } + /** + * constructor. + */ + public static HttpResponse getAssetIssueListByNameFromPbft(String httpPbftNode, + String name) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getassetissuelistbyname"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", str2hex(name)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + /** * constructor. */ @@ -1973,13 +2053,120 @@ public static HttpResponse getAccountReource(String httpNode, byte[] queryAddres return response; } + /** + * constructor. + */ + public static HttpResponse getAccountBalance(String httpNode, + byte[] queryAddress, Integer blockNum, String blockHash) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getaccountbalance"; + JsonObject addressObj = new JsonObject(); + addressObj.addProperty("address", Base58.encode58Check(queryAddress)); + JsonObject blockObj = new JsonObject(); + blockObj.addProperty("hash", blockHash); + blockObj.addProperty("number", blockNum); + JsonObject accountBalanceObj = new JsonObject(); + accountBalanceObj.add("account_identifier", addressObj); + accountBalanceObj.add("block_identifier", blockObj); + accountBalanceObj.addProperty("visible", true); + response = createConnect(requestUrl, accountBalanceObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getBlockBalance(String httpNode, Integer blockNum, String blockHash) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getblockbalance"; + JsonObject blockObj = new JsonObject(); + blockObj.addProperty("hash", blockHash); + blockObj.addProperty("number", blockNum); + blockObj.addProperty("visible", true); + response = createConnect(requestUrl, blockObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static Long getBurnTrx(String httpNode) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getburntrx"; + JsonObject blockObj = new JsonObject(); + response = createConnect(requestUrl, blockObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseResponseContent(response); + return responseContent.getLong("burnTrxAmount"); + } + + /** + * constructor. + */ + public static Long getBurnTrxFromSolidity(String httpNode) { + try { + final String requestUrl = "http://" + httpNode + "/walletsolidity/getburntrx"; + JsonObject blockObj = new JsonObject(); + response = createConnect(requestUrl, blockObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseResponseContent(response); + return responseContent.getLong("burnTrxAmount"); + } + + /** + * constructor. + */ + public static Long getBurnTrxFromPbft(String httpNode) { + try { + final String requestUrl = "http://" + httpNode + "/walletpbft/getburntrx"; + JsonObject blockObj = new JsonObject(); + response = createConnect(requestUrl, blockObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseResponseContent(response); + return responseContent.getLong("burnTrxAmount"); + } + + + + /** * constructor. */ public static HttpResponse getNowBlock(String httpNode) { + return getNowBlock(httpNode, false); + } + + /** + * constructor. + */ + public static HttpResponse getNowBlock(String httpNode, Boolean visible) { try { String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; - response = createConnect(requestUrl); + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); } catch (Exception e) { e.printStackTrace(); httppost.releaseConnection(); @@ -2135,10 +2322,18 @@ public static void waitToProduceOneBlockFromPbft(String httpNode, String httpSol * constructor. */ public static HttpResponse getBlockByNum(String httpNode, Integer blockNUm) { + return getBlockByNum(httpNode, blockNUm, false); + } + + /** + * constructor. + */ + public static HttpResponse getBlockByNum(String httpNode, Integer blockNUm, Boolean visible) { try { String requestUrl = "http://" + httpNode + "/wallet/getblockbynum"; JsonObject userBaseObj2 = new JsonObject(); userBaseObj2.addProperty("num", blockNUm); + userBaseObj2.addProperty("visible", visible); response = createConnect(requestUrl, userBaseObj2); } catch (Exception e) { e.printStackTrace(); @@ -2699,10 +2894,11 @@ public static HttpResponse getAssetIssueListFromPbft(String httpSolidityNode) { public static HttpResponse getPaginatedAssetissueList(String httpNode, Integer offset, Integer limit) { try { - String requestUrl = "http://" + httpNode + "/wallet/getpaginatedassetissuelist"; + final String requestUrl = "http://" + httpNode + "/wallet/getpaginatedassetissuelist"; JsonObject userBaseObj2 = new JsonObject(); userBaseObj2.addProperty("offset", offset); userBaseObj2.addProperty("limit", limit); + userBaseObj2.addProperty("visible", "true"); response = createConnect(requestUrl, userBaseObj2); } catch (Exception e) { e.printStackTrace(); @@ -4418,6 +4614,7 @@ public static HttpResponse getRewardFromPbft(String httpSolidityNode, byte[] add String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getReward"; JsonObject userBaseObj2 = new JsonObject(); userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + logger.info("userBaseObj2:" + userBaseObj2); response = createConnect(requestUrl, userBaseObj2); } catch (Exception e) { e.printStackTrace(); @@ -4576,4 +4773,400 @@ public static HttpResponse getBrokerageFromPbft(String httpSolidityNode, byte[] return response; } + /** + * constructor. + */ + public static String marketSellAssetGetTxId(String httpNode, byte[] ownerAddress, + String sellTokenId, + Long sellTokenQuantity, String buyTokenId, Long buyTokenQuantity, String fromKey, + String visible) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/marketsellasset"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("owner_address", Base58.encode58Check(ownerAddress)); + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("sell_token_quantity", sellTokenQuantity); + userBaseObj2.addProperty("buy_token_quantity", buyTokenQuantity); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + System.out.println("userBaseObj2: " + userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + System.out.println("transactionString: " + transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseStringContent(transactionSignString); + return responseContent.getString("txID"); + } + + /** + * constructor. + */ + public static HttpResponse getMarketOrderById(String httpNode, String orderId, String visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getmarketorderbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", orderId); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketOrderByIdFromSolidity(String httpSolidityNode, String orderId, + String visible) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", orderId); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketOrderByIdFromPbft(String httpPbftNode, String orderId, + String visible) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", orderId); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static String marketCancelOrder(String httpNode, byte[] ownerAddress, String orderId, + String fromKey, String visible) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/marketcancelorder"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("owner_address", Base58.encode58Check(ownerAddress)); + } else { + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + } + userBaseObj2.addProperty("order_id", orderId); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + System.out.println("userBaseObj2: " + userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + System.out.println("transactionString: " + transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseStringContent(transactionSignString); + return responseContent.getString("txID"); + } + + /** + * constructor. + */ + public static HttpResponse getMarketOrderByAccount(String httpNode, byte[] ownerAddress, + String visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getmarketorderbyaccount"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("value", Base58.encode58Check(ownerAddress)); + } else { + userBaseObj2.addProperty("value", ByteArray.toHexString(ownerAddress)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketOrderByAccountFromSolidity(String httpSolidityNode, + byte[] ownerAddress, String visible) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderbyaccount"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("value", Base58.encode58Check(ownerAddress)); + } else { + userBaseObj2.addProperty("value", ByteArray.toHexString(ownerAddress)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketOrderByAccountFromPbft(String httpPbftNode, + byte[] ownerAddress, String visible) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderbyaccount"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("value", Base58.encode58Check(ownerAddress)); + } else { + userBaseObj2.addProperty("value", ByteArray.toHexString(ownerAddress)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketPairList(String httpNode, String visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getmarketpairlist"; + 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 getMarketPairListFromSolidity(String httpSolidityNode, + String visible) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketpairlist"; + 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 getMarketPairListFromPbft(String httpPbftNode, String visible) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketpairlist"; + 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 getMarketOrderListByPair(String httpNode, String sellTokenId, + String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getmarketorderlistbypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketOrderListByPairFromSolidity(String httpSolidityNode, + String sellTokenId, + String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderlistbypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketOrderListByPairFromPbft(String httpPbftNode, + String sellTokenId, String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderlistbypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketPriceByPair(String httpNode, String sellTokenId, + String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getmarketpricebypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketPriceByPairFromSolidity(String httpSolidityNode, + String sellTokenId, + String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketpricebypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketPriceByPairFromPbft(String httpPbftNode, + String sellTokenId, String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketpricebypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(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/PublicMethed.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java index a098a118ad4..c60b9d2a868 100644 --- 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 @@ -38,6 +38,7 @@ 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; @@ -65,6 +66,7 @@ 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; @@ -73,6 +75,7 @@ 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; @@ -100,6 +103,7 @@ 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; @@ -107,6 +111,7 @@ 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; @@ -120,6 +125,7 @@ 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; @@ -147,6 +153,63 @@ public class PublicMethed { * 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, @@ -455,6 +518,10 @@ public static Account queryAccount(byte[] address, return blockingStubFull.getAccount(request); } + /** + * constructor. + */ + public static Account getAccountById(String accountId, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); @@ -518,6 +585,18 @@ public static Protocol.Block getBlock(long 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. */ @@ -1495,9 +1574,7 @@ public static Long getAssetBalanceByAssetId(ByteString assetId, String priKey, return assetOwnerAssetBalance; } - /** - * constructor. - */ + /* public static Optional getDeferredTransactionById(String txId, WalletGrpc.WalletBlockingStub blockingStubFull) { @@ -1844,6 +1921,43 @@ public static byte[] getFinalAddress(String priKey) { 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. */ @@ -2222,7 +2336,6 @@ public static boolean buyStorage(long quantity, byte[] address, String priKey, /** * constructor. */ - public static boolean sellStorage(long quantity, byte[] address, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); @@ -2261,6 +2374,123 @@ public static boolean sellStorage(long quantity, byte[] address, String priKey, 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. */ @@ -2389,6 +2619,18 @@ public static byte[] deployContract(String contractName, String abiString, Strin 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. */ @@ -2756,28 +2998,159 @@ public static SmartContract.ABI jsonStr2Abi(String jsonStr) { * 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; + public static SmartContract.ABI jsonStr2Abi2(String jsonStr) { + if (jsonStr == null) { + return null; } - } - - /** - * constructor. - */ - public static SmartContract.ABI.Entry.StateMutabilityType getStateMutability( - String stateMutability) { - switch (stateMutability) { + 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; + 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": @@ -2824,19 +3197,27 @@ public static SmartContract getContract(byte[] address, 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); } + /** + * 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("[,]"); @@ -3147,6 +3528,10 @@ public static Optional getTransactionInfoByIdFromSolidity(Strin return Optional.ofNullable(transactionInfo); } + + /** + * constructor. + */ public static Optional getTransactionInfoByBlockNum(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { NumberMessage.Builder builder = NumberMessage.newBuilder(); @@ -3156,6 +3541,9 @@ public static Optional getTransactionInfoByBlockNum(long bl return Optional.ofNullable(transactionInfoList); } + /** + * constructor. + */ public static Optional getTransactionInfoByBlockNumFromSolidity( long blockNum, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { NumberMessage.Builder builder = NumberMessage.newBuilder(); @@ -3197,7 +3585,10 @@ public static String triggerContract(byte[] contractAddress, String method, Stri } byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); + 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)); @@ -3947,9 +4338,8 @@ public static Optional getDelegatedResourceAccoun * constructor. */ public static Optional - getDelegatedResourceAccountIndexFromSolidity( - byte[] address, WalletSolidityGrpc - .WalletSolidityBlockingStub blockingStubFull) { + getDelegatedResourceAccountIndexFromSolidity(byte[] address, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString addressBs = ByteString.copyFrom(address); @@ -4079,6 +4469,17 @@ public static AssetIssueContract getAssetIssueByIdFromSolidity(String assetId, 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(); @@ -4696,8 +5097,8 @@ public static GrpcAPI.Return broadcastTransactionBoth(Transaction transaction, WalletGrpc.WalletBlockingStub blockingStubFull1) { int i = 10; waitProduceNextBlock(blockingStubFull1); - GrpcAPI.Return response1 = blockingStubFull1.broadcastTransaction(transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); + 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 { @@ -4769,9 +5170,10 @@ public static HashMap getBycodeAbi(String solFile, String contra logger.debug("solFile: " + solFile); logger.debug("outputPath: " + outputPath); String cmd = - compile + " --optimize --bin --abi --overwrite " + absolutePath + "/" + solFile + " -o " + compile + " --optimize --bin --abi --overwrite " + absolutePath + "/" + + solFile + " -o " + absolutePath + "/" + outputPath; - logger.debug("cmd: " + cmd); + logger.info("cmd: " + cmd); String byteCode = null; String abI = null; @@ -5117,6 +5519,11 @@ public static TransactionExtention triggerConstantContractForExtention(byte[] co 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)); @@ -5135,7 +5542,9 @@ public static TransactionExtention triggerConstantContractForExtention(byte[] co } - + /** + * constructor. + */ public static TransactionExtention triggerSolidityContractForExtention(byte[] contractAddress, String method, String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, @@ -6098,6 +6507,9 @@ public static String sendShieldCoinGetTxid(byte[] publicZenTokenOwnerAddress, lo transaction.getRawData().toByteArray())); } + /** + * constructor. + */ public static byte[] decode58Check(String input) { byte[] decodeCheck = org.tron.common.utils.Base58.decode(input); if (decodeCheck.length <= 4) { @@ -6115,12 +6527,18 @@ public static byte[] decode58Check(String input) { 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; @@ -6143,19 +6561,22 @@ public static String parametersString(List parameters) { return input; } + /** + * constructor. + */ public static String bytes32ToString(byte[] bytes) { if (bytes == null) { return "null"; } - int iMax = bytes.length - 1; - if (iMax == -1) { + 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) { + if (i == imax) { return b.toString(); } } @@ -6261,6 +6682,444 @@ public static Transaction sendcoinForTransaction(byte[] to, long amount, byte[] 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. */ @@ -6294,4 +7153,48 @@ public boolean updateBrokerage(byte[] owner, int brokerage, String priKey, 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); + + + } } 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 index 47b3f412550..50ee2f87c46 100644 --- 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 @@ -36,6 +36,7 @@ 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; @@ -74,6 +75,7 @@ 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; @@ -1073,7 +1075,7 @@ public static String transferAssetForTransactionId(byte[] to, byte[] assertName, transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); boolean result = broadcastTransaction(transaction, blockingStubFull); - if (result == false) { + if (!result) { return null; } else { return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() @@ -5239,4 +5241,95 @@ public static boolean updateBrokerage(byte[] owner, int brokerage, String priKey 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/ZenTrc20Base.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/ZenTrc20Base.java index 2475e754505..52381e9888b 100644 --- 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 @@ -54,7 +54,10 @@ public class ZenTrc20Base { 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); @@ -92,6 +95,7 @@ public void deployShieldTrc20DependContract() { .build(); blockingStubFull = WalletGrpc.newBlockingStub(channelFull); + getDailyBuildStartNum(); Assert.assertTrue(PublicMethed.sendcoin(zenTrc20TokenOwnerAddress, 10000000000000L, foundationAccountAddress, foundationAccountKey, blockingStubFull)); PublicMethed.waitProduceNextBlock(blockingStubFull); @@ -151,6 +155,15 @@ public void deployShieldTrc20DependContract() { } + /** + * constructor. + */ + public void getDailyBuildStartNum() { + DailyBuildReport.startBlockNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder() + .build()).getBlockHeader().getRawData().getNumber(); + System.out.println("!!!!!!! 222222222startnum:" + DailyBuildReport.startBlockNum); + } + /** * constructor. @@ -681,7 +694,7 @@ public GrpcAPI.DecryptNotesTRC20 scanShieldedTrc20NoteByIvk(ShieldedAddressInfo .newBuilder() .setStartBlockIndex(startNum) .setEndBlockIndex(endNum) - .setShieldedTRC20ContractAddress(ByteString.copyFrom(Base58.decode58Check(shieldAddress))) + .setShieldedTRC20ContractAddress(ByteString.copyFrom(Commons.decode58Check(shieldAddress))) .setIvk(ByteString.copyFrom(ByteArray.fromHexString(ivkString))) .setAk(ByteString.copyFrom(ByteArray.fromHexString(akString))) .setNk(ByteString.copyFrom(ByteArray.fromHexString(nkString))) @@ -743,7 +756,7 @@ public GrpcAPI.DecryptNotesTRC20 scanShieldedTrc20NoteByIvk(ShieldedAddressInfo .newBuilder() .setStartBlockIndex(startNum) .setEndBlockIndex(endNum) - .setShieldedTRC20ContractAddress(ByteString.copyFrom(Base58.decode58Check(shieldAddress))) + .setShieldedTRC20ContractAddress(ByteString.copyFrom(Commons.decode58Check(shieldAddress))) .setIvk(ByteString.copyFrom(ByteArray.fromHexString(ivkString))) .setAk(ByteString.copyFrom(ByteArray.fromHexString(akString))) .setNk(ByteString.copyFrom(ByteArray.fromHexString(nkString))) @@ -802,7 +815,8 @@ public GrpcAPI.DecryptNotesTRC20 scanShieldedTrc20NoteByIvkWithRange(ShieldedAdd .newBuilder() .setStartBlockIndex(startNum) .setEndBlockIndex(startNum + 99) - .setShieldedTRC20ContractAddress(ByteString.copyFrom(Base58.decode58Check(shieldAddress))) + .setShieldedTRC20ContractAddress(ByteString + .copyFrom(Commons.decode58Check(shieldAddress))) .setIvk(ByteString.copyFrom(ByteArray.fromHexString(ivkString))) .setAk(ByteString.copyFrom(ByteArray.fromHexString(akString))) .setNk(ByteString.copyFrom(ByteArray.fromHexString(nkString))) @@ -844,7 +858,7 @@ public GrpcAPI.DecryptNotesTRC20 scanShieldedTrc20NoteByOvk(ShieldedAddressInfo .setStartBlockIndex(startNum) .setEndBlockIndex(endNum) .setOvk(ByteString.copyFrom(ByteArray.fromHexString(ovkString))) - .setShieldedTRC20ContractAddress(ByteString.copyFrom(Base58.decode58Check(shieldAddress))) + .setShieldedTRC20ContractAddress(ByteString.copyFrom(Commons.decode58Check(shieldAddress))) .build(); try { @@ -878,7 +892,7 @@ public GrpcAPI.DecryptNotesTRC20 scanShieldedTrc20NoteByOvk(ShieldedAddressInfo .setStartBlockIndex(startNum) .setEndBlockIndex(endNum) .setOvk(ByteString.copyFrom(ByteArray.fromHexString(ovkString))) - .setShieldedTRC20ContractAddress(ByteString.copyFrom(Base58.decode58Check(shieldAddress))) + .setShieldedTRC20ContractAddress(ByteString.copyFrom(Commons.decode58Check(shieldAddress))) .build(); try { @@ -1376,6 +1390,43 @@ public static JSONArray scanShieldTrc20NoteByIvkOnSolidity(String httpNode, } } + /** + * 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. @@ -1441,6 +1492,39 @@ public static JSONArray scanShieldTrc20NoteByOvkOnSolidity(String httpNode, } } + /** + * 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. @@ -1561,6 +1645,33 @@ public static Boolean isShieldedTrc20ContractNoteSpentOnSolidity(String httpNode 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. 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 new file mode 100644 index 00000000000..fa3e1eca594 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/account/GetAccountBalance001.java @@ -0,0 +1,133 @@ +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"); + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + } + + /** + * 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 new file mode 100644 index 00000000000..58f0048057f --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/account/TransactionFee001.java @@ -0,0 +1,664 @@ +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.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; + + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + } + + /** + * 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, 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/assetissue/WalletExchange001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletExchange001.java index e679b532434..bdad3c765f5 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletExchange001.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletExchange001.java @@ -97,7 +97,7 @@ public void beforeClass() { blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); } - @Test(enabled = true) + @Test(enabled = true,description = "Create two asset issue to create exchange") public void test1CreateUsedAsset() { ecKey1 = new ECKey(Utils.getRandom()); exchange001Address = ecKey1.getAddress(); @@ -126,7 +126,7 @@ public void test1CreateUsedAsset() { PublicMethed.waitProduceNextBlock(blockingStubFull); } - @Test(enabled = true) + @Test(enabled = true,description = "Test create exchange") public void test2CreateExchange() { listExchange = PublicMethed.getExchangeList(blockingStubFull); final Integer beforeCreateExchangeNum = listExchange.get().getExchangesCount(); @@ -169,7 +169,7 @@ public void test2CreateExchange() { } - @Test(enabled = true) + @Test(enabled = true,description = "Test list exchange api") public void test3ListExchange() { listExchange = PublicMethed.getExchangeList(blockingStubFull); for (Integer i = 0; i < listExchange.get().getExchangesCount(); i++) { @@ -182,7 +182,7 @@ public void test3ListExchange() { } } - @Test(enabled = true) + @Test(enabled = true,description = "Test inject exchange") public void test4InjectExchange() { exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); @@ -233,7 +233,7 @@ public void test4InjectExchange() { == injectBalance * exchangeRate); } - @Test(enabled = true) + @Test(enabled = true,description = "Test withdraw exchange") public void test5WithdrawExchange() { exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); @@ -287,7 +287,7 @@ public void test5WithdrawExchange() { } - @Test(enabled = true) + @Test(enabled = true,description = "Test exchange transaction") public void test6TransactionExchange() { exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); @@ -340,7 +340,7 @@ public void test6TransactionExchange() { == beforeToken2Balance - afterToken2Balance); } - @Test(enabled = true) + @Test(enabled = true,description = "Test GetExchangeListPaginated api") public void test7GetExchangeListPaginated() { PaginatedMessage.Builder pageMessageBuilder = PaginatedMessage.newBuilder(); pageMessageBuilder.setOffset(0); @@ -363,7 +363,7 @@ public void test7GetExchangeListPaginated() { /** * constructor. */ - @Test(enabled = true) + @Test(enabled = true,description = "Test get exchange list from pbft") public void test8GetExchangeListFromPbft() { //Pbft support listexchange listExchange = PublicMethed.getExchangeList(blockingStubPbft); @@ -373,7 +373,7 @@ public void test8GetExchangeListFromPbft() { /** * constructor. */ - @Test(enabled = true) + @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)); 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 index 1588eff3269..3dd88b630be 100644 --- 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 @@ -311,26 +311,22 @@ public void test5Grammar006() { final String txid2 = PublicMethed.triggerContract(contractAddress, "d(uint256)", number, false, 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(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); - PublicMethed.waitProduceNextBlock(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); - PublicMethed.waitProduceNextBlock(blockingStubFull); final String txid8 = PublicMethed.triggerContract(contractAddress, "d6(uint256)", number, false, 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); PublicMethed.waitProduceNextBlock(blockingStubFull1); Optional infoById1 = PublicMethed @@ -340,6 +336,7 @@ public void test5Grammar006() { 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); 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 index 2cef19ad570..dc6bc8dd223 100644 --- 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 @@ -87,6 +87,7 @@ 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); 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 new file mode 100644 index 00000000000..55c11bb04c3 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset001.java @@ -0,0 +1,217 @@ +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.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; + private String fullnode = 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); + + 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 = 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 new file mode 100644 index 00000000000..95082986179 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset002.java @@ -0,0 +1,374 @@ +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()), + "contract validate error : Order is not active!"); + + + } + +} 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 new file mode 100644 index 00000000000..51cdc78d824 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset003.java @@ -0,0 +1,152 @@ +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),"contract validate error : Order is not active!"); + + + } + +} 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 new file mode 100644 index 00000000000..2a911540df4 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset004.java @@ -0,0 +1,113 @@ +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 new file mode 100644 index 00000000000..951c404c6f0 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset005.java @@ -0,0 +1,160 @@ +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 new file mode 100644 index 00000000000..830795dfded --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset006.java @@ -0,0 +1,288 @@ +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/EventQuery002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery002.java index 5ca394caf7d..4d2b0a99c5d 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery002.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery002.java @@ -113,7 +113,10 @@ public void run() { "triggerUintEvent()", "#", false, 0, maxFeeLimit, event001Address, event001Key, blockingStubFull); logger.info(txid); - sendTransaction = false; + if (PublicMethed.getTransactionInfoById(txid,blockingStubFull).get() + .getResultValue() == 0) { + sendTransaction = false; + } } if (message != null) { 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 index 3fcfc896074..9eaa3442844 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery003.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery003.java @@ -124,7 +124,10 @@ public void run() { "triggerUintEvent()", "#", false, 0, maxFeeLimit, event001Address, event001Key, blockingStubFull); logger.info(txid); - sendTransaction = false; + if (PublicMethed.getTransactionInfoById(txid,blockingStubFull).get() + .getResultValue() == 0) { + sendTransaction = false; + } } if (message != null) { @@ -166,7 +169,7 @@ public void run() { req.setReceiveTimeOut(10000); String transactionMessage = ""; Boolean sendTransaction = true; - Integer retryTimes = 20; + Integer retryTimes = 40; while (retryTimes-- > 0) { byte[] message = req.recv(); @@ -175,7 +178,10 @@ public void run() { "triggerUintEvent()", "#", false, 0, maxFeeLimit, event001Address, event001Key, blockingStubFull); logger.info(txid); - sendTransaction = false; + if (PublicMethed.getTransactionInfoById(txid,blockingStubFull).get() + .getResultValue() == 0) { + sendTransaction = false; + } } if (message != null) { 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 index 2af83a30057..7ff4649509f 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery004.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery004.java @@ -31,6 +31,11 @@ public class EventQuery004 { 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") @@ -43,12 +48,6 @@ public class EventQuery004 { private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; 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()); @BeforeSuite public void beforeSuite() { @@ -123,7 +122,10 @@ public void run() { "depositForLog()", "#", false, 1L, 100000000L, event001Address, event001Key, blockingStubFull); logger.info(txid); - sendTransaction = false; + if (PublicMethed.getTransactionInfoById(txid,blockingStubFull).get() + .getResultValue() == 0) { + sendTransaction = false; + } } if (message != null) { @@ -165,16 +167,29 @@ public void run() { req.setReceiveTimeOut(10000); String transactionMessage = ""; Boolean sendTransaction = true; - Integer retryTimes = 20; + Integer retryTimes = 40; + String txid1 = ""; + String txid2 = ""; + String txid3 = ""; while (retryTimes-- > 0) { byte[] message = req.recv(); if (sendTransaction) { - txid = PublicMethed.triggerContract(contractAddress, + 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); - sendTransaction = false; + if (PublicMethed.getTransactionInfoById(txid,blockingStubFull).get() + .getResultValue() == 0) { + sendTransaction = false; + } + } if (message != null) { @@ -191,8 +206,9 @@ public void run() { JSONObject blockObject = JSONObject.parseObject(transactionMessage); Assert.assertTrue(blockObject.containsKey("timeStamp")); Assert.assertEquals(blockObject.getString("triggerName"), "solidityLogTrigger"); + txid = blockObject.getString("transactionId"); - Assert.assertEquals(blockObject.getString("transactionId"), txid); + Assert.assertTrue(txid1.equals(txid) || txid2.equals(txid) || txid3.equals(txid)); } 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 index 3042b37ba52..f091e8f4b05 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestBlock001.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestBlock001.java @@ -24,6 +24,7 @@ public class HttpTestBlock001 { .getStringList("httpnode.ip.list").get(4); private Integer currentBlockNum; private JSONObject blockContent; + private JSONObject blockContentWithVisibleTrue; private String blockId; @@ -113,6 +114,13 @@ public void get04BlockByNum() { 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")); + } /** 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 index 8eecb3c6195..41040cc8e97 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestClearAbiContract001.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestClearAbiContract001.java @@ -40,6 +40,10 @@ public class HttpTestClearAbiContract001 { 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. @@ -115,6 +119,27 @@ public void test3TriggerConstantContract() { 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\"]"); } /** 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 index 2f5bd001abe..ce06d8f9f39 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestExchange001.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestExchange001.java @@ -271,14 +271,20 @@ public void test11GetAssetIssueListByName() { /** * constructor. */ - @Test(enabled = true, description = "Get asset issue list by name from solidity by http") - public void test12GetAssetIssueListByNameFromSolidity() { + @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); } /** 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 new file mode 100644 index 00000000000..d698e5dd94a --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestGetAccountBalance001.java @@ -0,0 +1,192 @@ +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() { + Long beforeBurnTrxAmount = HttpMethed.getBurnTrx(httpnode); + ECKey ecKey2 = new ECKey(Utils.getRandom()); + byte[] assetOwnerAddress = ecKey2.getAddress(); + + HttpMethed.sendCoin(httpnode,fromAddress,assetOwnerAddress,amount,"",testKey002); + HttpMethed.waitToProduceOneBlockFromSolidity(httpnode,httpSolidityNode); + Long afterBurnTrxAmount = HttpMethed.getBurnTrx(httpnode); + Assert.assertTrue(afterBurnTrxAmount - beforeBurnTrxAmount == 100000L); + + Assert.assertEquals(afterBurnTrxAmount,HttpMethed.getBurnTrxFromSolidity(httpSolidityNode)); + Assert.assertEquals(afterBurnTrxAmount,HttpMethed.getBurnTrxFromPbft(httpPbftNode)); + } + + /** + * 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 new file mode 100644 index 00000000000..8dfe0701288 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMarket001.java @@ -0,0 +1,533 @@ +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 new file mode 100644 index 00000000000..91217ff06ea --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMarket002.java @@ -0,0 +1,534 @@ +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/internaltransaction/ContractInternalTransaction003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction003.java index 80c15d79364..3be9601f593 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction003.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction003.java @@ -1,7 +1,5 @@ package stest.tron.wallet.dailybuild.internaltransaction; -import static org.tron.protos.Protocol.TransactionInfo.code.FAILED; - import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import java.util.ArrayList; @@ -23,7 +21,6 @@ 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.CommonConstant; @@ -505,43 +502,44 @@ public void testInternalTransaction018() { Optional infoById = null; infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); logger.info("InfoById:" + infoById); - if (infoById.get().getResultValue() == 0) { - 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); - } else if (infoById.get().getResultValue() == 1) { - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert - .assertEquals(infoById.get().getContractResult(0).toStringUtf8(), - ""); - Assert.assertEquals(contractResult.OUT_OF_TIME, infoById.get().getReceipt().getResult()); - Assert.assertEquals("CPU timeout for 'PUSH1' operation executing", - infoById.get().getResMessage().toStringUtf8()); + + // retry 1 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-1" + ": " + 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); } /** 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 index a077f45c2d2..75361fe5b58 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestBlock002.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestBlock002.java @@ -236,8 +236,14 @@ public void test07GetNowBlockFromPbft() { 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); } @@ -286,6 +292,21 @@ public void test08GetBlockByNumFromPbft() { 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"); + } diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign017.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest.java similarity index 98% rename from framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign017.java rename to framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest.java index defe1880e31..195c613ab91 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign017.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest.java @@ -23,7 +23,7 @@ import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; @Slf4j -public class WalletTestMutiSign017 { +public class MutiSignAccountPermissionUpdateTest { private static final long now = System.currentTimeMillis(); private static final long totalSupply = now; @@ -75,7 +75,7 @@ public void beforeSuite() { * constructor. */ - @BeforeClass(enabled = false) + @BeforeClass(enabled = true) public void beforeClass() { channelFull = ManagedChannelBuilder.forTarget(fullnode) .usePlaintext(true) @@ -83,7 +83,7 @@ public void beforeClass() { blockingStubFull = WalletGrpc.newBlockingStub(channelFull); } - @Test(enabled = false) + @Test(enabled = true) public void testMutiSign1UpdatePermission() { ecKey1 = new ECKey(Utils.getRandom()); manager1Address = ecKey1.getAddress(); @@ -185,7 +185,7 @@ public void testMutiSign1UpdatePermission() { /** * constructor. */ - @AfterClass(enabled = false) + @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/WalletTestMutiSign011.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest002.java similarity index 98% rename from framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign011.java rename to framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest002.java index 3f433ab5d59..6f4e11f7653 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign011.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest002.java @@ -23,7 +23,7 @@ import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; @Slf4j -public class WalletTestMutiSign011 { +public class MutiSignAccountPermissionUpdateTest002 { private static final long now = System.currentTimeMillis(); private static final long totalSupply = now; @@ -75,7 +75,7 @@ public void beforeSuite() { * constructor. */ - @BeforeClass(enabled = false) + @BeforeClass(enabled = true) public void beforeClass() { channelFull = ManagedChannelBuilder.forTarget(fullnode) .usePlaintext(true) @@ -83,7 +83,7 @@ public void beforeClass() { blockingStubFull = WalletGrpc.newBlockingStub(channelFull); } - @Test(enabled = false) + @Test(enabled = true) public void testMutiSign1UpdatePermission() { ecKey1 = new ECKey(Utils.getRandom()); manager1Address = ecKey1.getAddress(); @@ -185,7 +185,7 @@ public void testMutiSign1UpdatePermission() { /** * constructor. */ - @AfterClass(enabled = false) + @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/WalletTestMutiSign013.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest.java similarity index 98% rename from framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign013.java rename to framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest.java index 0100db4e78b..3b90a790da3 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign013.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest.java @@ -26,7 +26,7 @@ import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; @Slf4j -public class WalletTestMutiSign013 { +public class MutiSignAccountTest { private final String testKey002 = Configuration.getByPath("testng.conf") .getString("foundationAccount.key1"); @@ -83,7 +83,7 @@ public void beforeSuite() { * constructor. */ - @BeforeClass(enabled = false) + @BeforeClass(enabled = true) public void beforeClass() { channelFull = ManagedChannelBuilder.forTarget(fullnode) .usePlaintext(true) @@ -91,7 +91,7 @@ public void beforeClass() { blockingStubFull = WalletGrpc.newBlockingStub(channelFull); } - @Test(enabled = false) + @Test(enabled = true) public void testMutiSignForAccount() { ecKey1 = new ECKey(Utils.getRandom()); manager1Address = ecKey1.getAddress(); @@ -210,7 +210,7 @@ public void testMutiSignForAccount() { /** * constructor. */ - @AfterClass(enabled = false) + @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/WalletTestMutiSign007.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest002.java similarity index 98% rename from framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign007.java rename to framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest002.java index dc92fc7e8b2..dab4208dcfe 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign007.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest002.java @@ -26,7 +26,7 @@ import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; @Slf4j -public class WalletTestMutiSign007 { +public class MutiSignAccountTest002 { private final String testKey002 = Configuration.getByPath("testng.conf") .getString("foundationAccount.key1"); @@ -83,7 +83,7 @@ public void beforeSuite() { * constructor. */ - @BeforeClass(enabled = false) + @BeforeClass(enabled = true) public void beforeClass() { channelFull = ManagedChannelBuilder.forTarget(fullnode) .usePlaintext(true) @@ -91,7 +91,7 @@ public void beforeClass() { blockingStubFull = WalletGrpc.newBlockingStub(channelFull); } - @Test(enabled = false) + @Test(enabled = true) public void testMutiSignForAccount() { ecKey1 = new ECKey(Utils.getRandom()); manager1Address = ecKey1.getAddress(); @@ -210,7 +210,7 @@ public void testMutiSignForAccount() { /** * constructor. */ - @AfterClass(enabled = false) + @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/WalletTestMutiSign012.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest.java similarity index 98% rename from framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign012.java rename to framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest.java index 953247c6a7b..fe3389ad0f6 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign012.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest.java @@ -24,7 +24,7 @@ import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; @Slf4j -public class WalletTestMutiSign012 { +public class MutiSignAssetTest { private static final long now = System.currentTimeMillis(); private static final long totalSupply = now; @@ -76,7 +76,7 @@ public void beforeSuite() { * constructor. */ - @BeforeClass(enabled = false) + @BeforeClass(enabled = true) public void beforeClass() { channelFull = ManagedChannelBuilder.forTarget(fullnode) .usePlaintext(true) @@ -84,7 +84,7 @@ public void beforeClass() { blockingStubFull = WalletGrpc.newBlockingStub(channelFull); } - @Test(enabled = false) + @Test(enabled = true) public void testMutiSign1CreateAssetissue() { ecKey1 = new ECKey(Utils.getRandom()); manager1Address = ecKey1.getAddress(); @@ -184,7 +184,7 @@ public void testMutiSign1CreateAssetissue() { * constructor. */ - @Test(enabled = false) + @Test(enabled = true) public void testMutiSign2TransferAssetissue() { PublicMethed.waitProduceNextBlock(blockingStubFull); PublicMethed.printAddress(manager1Key); @@ -222,7 +222,7 @@ public void testMutiSign2TransferAssetissue() { * constructor. */ - @Test(enabled = false) + @Test(enabled = true) public void testMutiSign3ParticipateAssetissue() { ecKey4 = new ECKey(Utils.getRandom()); participateAddress = ecKey4.getAddress(); @@ -305,7 +305,7 @@ public void testMutiSign3ParticipateAssetissue() { * constructor. */ - @Test(enabled = false) + @Test(enabled = true) public void testMutiSign4updateAssetissue() { url = "MutiSign001_update_url" + Long.toString(now); ownerKeyString[0] = ownerKey; @@ -341,7 +341,7 @@ public void testMutiSign4updateAssetissue() { /** * constructor. */ - @AfterClass(enabled = false) + @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/WalletTestMutiSign006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest002.java similarity index 98% rename from framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign006.java rename to framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest002.java index 063294db818..b454eba34fa 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign006.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest002.java @@ -24,7 +24,7 @@ import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; @Slf4j -public class WalletTestMutiSign006 { +public class MutiSignAssetTest002 { private static final long now = System.currentTimeMillis(); private static final long totalSupply = now; @@ -76,7 +76,7 @@ public void beforeSuite() { * constructor. */ - @BeforeClass(enabled = false) + @BeforeClass(enabled = true) public void beforeClass() { channelFull = ManagedChannelBuilder.forTarget(fullnode) .usePlaintext(true) @@ -84,7 +84,7 @@ public void beforeClass() { blockingStubFull = WalletGrpc.newBlockingStub(channelFull); } - @Test(enabled = false) + @Test(enabled = true) public void testMutiSign1CreateAssetissue() { ecKey1 = new ECKey(Utils.getRandom()); manager1Address = ecKey1.getAddress(); @@ -184,7 +184,7 @@ public void testMutiSign1CreateAssetissue() { * constructor. */ - @Test(enabled = false) + @Test(enabled = true) public void testMutiSign2TransferAssetissue() { PublicMethed.waitProduceNextBlock(blockingStubFull); PublicMethed.printAddress(manager1Key); @@ -222,7 +222,7 @@ public void testMutiSign2TransferAssetissue() { * constructor. */ - @Test(enabled = false) + @Test(enabled = true) public void testMutiSign3ParticipateAssetissue() { ecKey4 = new ECKey(Utils.getRandom()); participateAddress = ecKey4.getAddress(); @@ -305,7 +305,7 @@ public void testMutiSign3ParticipateAssetissue() { * constructor. */ - @Test(enabled = false) + @Test(enabled = true) public void testMutiSign4updateAssetissue() { url = "MutiSign001_update_url" + Long.toString(now); ownerKeyString[0] = ownerKey; @@ -341,7 +341,7 @@ public void testMutiSign4updateAssetissue() { /** * constructor. */ - @AfterClass(enabled = false) + @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/WalletTestMutiSign018.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignClearContractAbiTest.java similarity index 97% rename from framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign018.java rename to framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignClearContractAbiTest.java index ecc26cdfa94..078d4204d3e 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign018.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignClearContractAbiTest.java @@ -28,7 +28,7 @@ import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; @Slf4j -public class WalletTestMutiSign018 { +public class MutiSignClearContractAbiTest { private final String testKey002 = Configuration.getByPath("testng.conf") .getString("foundationAccount.key1"); @@ -78,7 +78,7 @@ public void beforeSuite() { * constructor. */ - @BeforeClass(enabled = false) + @BeforeClass(enabled = true) public void beforeClass() { channelFull = ManagedChannelBuilder.forTarget(fullnode) .usePlaintext(true) @@ -90,7 +90,7 @@ public void beforeClass() { blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); } - @Test(enabled = false, threadPoolSize = 1, invocationCount = 1) + @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) public void test1MutiSignForClearContractAbi() { ecKey1 = new ECKey(Utils.getRandom()); manager1Address = ecKey1.getAddress(); @@ -167,7 +167,7 @@ public void test1MutiSignForClearContractAbi() { PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, ownerAddress, blockingStubFull)); } - @Test(enabled = false, threadPoolSize = 1, invocationCount = 1) + @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) public void test2MutiSignForClearContractAbiForDefault() { ecKey1 = new ECKey(Utils.getRandom()); manager1Address = ecKey1.getAddress(); @@ -205,14 +205,13 @@ public void test2MutiSignForClearContractAbiForDefault() { PublicMethed.waitProduceNextBlock(blockingStubFull); ownerKeyString[0] = ownerKey; ownerKeyString[1] = manager1Key; - String operationsDefault = "7fff1fc0034e0100000000000000000000000000000000000000000000000000"; 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\":\"" + operationsDefault + "\"," + + "\"operations\":\"" + operations + "\"," + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" @@ -246,7 +245,7 @@ public void test2MutiSignForClearContractAbiForDefault() { } - @Test(enabled = false, threadPoolSize = 1, invocationCount = 1) + @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) public void test3MutiSignForClearContractAbiForDefault() { ecKey3 = new ECKey(Utils.getRandom()); ownerAddress = ecKey3.getAddress(); diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign016.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest.java similarity index 97% rename from framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign016.java rename to framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest.java index 10472f02b05..058aeba48a0 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign016.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest.java @@ -26,7 +26,7 @@ import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; @Slf4j -public class WalletTestMutiSign016 { +public class MutiSignExchangeContractTest { private static final long now = System.currentTimeMillis(); private static final long totalSupply = 1000000001L; @@ -87,7 +87,7 @@ public void beforeSuite() { * constructor. */ - @BeforeClass(enabled = false) + @BeforeClass(enabled = true) public void beforeClass() { channelFull = ManagedChannelBuilder.forTarget(fullnode) .usePlaintext(true) @@ -100,7 +100,7 @@ public void beforeClass() { blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); } - @Test(enabled = false, description = "MutiSign for create token") + @Test(enabled = true, description = "MutiSign for create token") public void test1CreateUsedAsset() { ecKey1 = new ECKey(Utils.getRandom()); exchange001Address = ecKey1.getAddress(); @@ -134,7 +134,7 @@ public void test1CreateUsedAsset() { PublicMethed.waitProduceNextBlock(blockingStubFull); } - @Test(enabled = false, description = "MutiSign for create exchange") + @Test(enabled = true, description = "MutiSign for create exchange") public void test2CreateExchange() { ecKey3 = new ECKey(Utils.getRandom()); manager1Address = ecKey3.getAddress(); @@ -217,7 +217,7 @@ public void test2CreateExchange() { } - @Test(enabled = false, description = "Mutisign for inject exchange") + @Test(enabled = true, description = "Mutisign for inject exchange") public void test4InjectExchange() { exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); @@ -276,7 +276,7 @@ public void test4InjectExchange() { Assert.assertEquals(balanceBefore - balanceAfter, needCoin); } - @Test(enabled = false, description = "MutiSign for withdraw exchange") + @Test(enabled = true, description = "MutiSign for withdraw exchange") public void test5WithdrawExchange() { final long needCoin = multiSignFee; Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) @@ -338,7 +338,7 @@ public void test5WithdrawExchange() { } - @Test(enabled = false, description = "MutiSign for transaction exchange") + @Test(enabled = true, description = "MutiSign for transaction exchange") public void test6TransactionExchange() { final long needCoin = multiSignFee; Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign010.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest002.java similarity index 97% rename from framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign010.java rename to framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest002.java index 335a8d6d0c1..6008437120a 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign010.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest002.java @@ -26,7 +26,7 @@ import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; @Slf4j -public class WalletTestMutiSign010 { +public class MutiSignExchangeContractTest002 { private static final long now = System.currentTimeMillis(); private static final long totalSupply = 1000000001L; @@ -87,7 +87,7 @@ public void beforeSuite() { * constructor. */ - @BeforeClass(enabled = false) + @BeforeClass(enabled = true) public void beforeClass() { channelFull = ManagedChannelBuilder.forTarget(fullnode) .usePlaintext(true) @@ -100,7 +100,7 @@ public void beforeClass() { blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); } - @Test(enabled = false, description = "MutiSign for create token") + @Test(enabled = true, description = "MutiSign for create token") public void test1CreateUsedAsset() { ecKey1 = new ECKey(Utils.getRandom()); exchange001Address = ecKey1.getAddress(); @@ -134,7 +134,7 @@ public void test1CreateUsedAsset() { PublicMethed.waitProduceNextBlock(blockingStubFull); } - @Test(enabled = false, description = "MutiSign for create exchange") + @Test(enabled = true, description = "MutiSign for create exchange") public void test2CreateExchange() { ecKey3 = new ECKey(Utils.getRandom()); manager1Address = ecKey3.getAddress(); @@ -217,7 +217,7 @@ public void test2CreateExchange() { } - @Test(enabled = false, description = "Mutisign for inject exchange") + @Test(enabled = true, description = "Mutisign for inject exchange") public void test4InjectExchange() { exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); @@ -276,7 +276,7 @@ public void test4InjectExchange() { Assert.assertEquals(balanceBefore - balanceAfter, needCoin); } - @Test(enabled = false, description = "MutiSign for withdraw exchange") + @Test(enabled = true, description = "MutiSign for withdraw exchange") public void test5WithdrawExchange() { final long needCoin = multiSignFee; Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) @@ -338,7 +338,7 @@ public void test5WithdrawExchange() { } - @Test(enabled = false, description = "MutiSign for transaction exchange") + @Test(enabled = true, description = "MutiSign for transaction exchange") public void test6TransactionExchange() { final long needCoin = multiSignFee; Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) 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 new file mode 100644 index 00000000000..5dd79a0d7e5 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignMarketAssetTest.java @@ -0,0 +1,221 @@ +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); + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + } + + /** + * 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/WalletTestMutiSign015.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest.java similarity index 99% rename from framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign015.java rename to framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest.java index 9cdc6a41065..7ff737456ef 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign015.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest.java @@ -26,7 +26,7 @@ @Slf4j -public class WalletTestMutiSign015 { +public class MutiSignProposalTest { private static final long now = System.currentTimeMillis(); private final String testKey002 = Configuration.getByPath("testng.conf") @@ -82,7 +82,7 @@ public void beforeClass() { blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); } - @Test(enabled = false) + @Test(enabled = true) public void testMutiSignForProposal() { long needcoin = updateAccountPermissionFee + multiSignFee * 5; Assert.assertTrue(PublicMethed.sendcoin(witness001Address, needcoin + 10000000L, diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign009.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest002.java similarity index 99% rename from framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign009.java rename to framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest002.java index aa897e35194..72086e16e1d 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign009.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest002.java @@ -26,7 +26,7 @@ @Slf4j -public class WalletTestMutiSign009 { +public class MutiSignProposalTest002 { private static final long now = System.currentTimeMillis(); private final String testKey002 = Configuration.getByPath("testng.conf") @@ -82,7 +82,7 @@ public void beforeClass() { blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); } - @Test(enabled = false) + @Test(enabled = true) public void testMutiSignForProposal() { long needcoin = updateAccountPermissionFee + multiSignFee * 3; Assert.assertTrue(PublicMethed.sendcoin(witness001Address, needcoin + 10000000L, diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign014.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest.java similarity index 98% rename from framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign014.java rename to framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest.java index 542721abaac..d09b54e38e5 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign014.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest.java @@ -27,7 +27,7 @@ import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; @Slf4j -public class WalletTestMutiSign014 { +public class MutiSignSmartContractTest { private final String testKey002 = Configuration.getByPath("testng.conf") .getString("foundationAccount.key1"); @@ -77,7 +77,7 @@ public void beforeSuite() { * constructor. */ - @BeforeClass(enabled = false) + @BeforeClass(enabled = true) public void beforeClass() { channelFull = ManagedChannelBuilder.forTarget(fullnode) .usePlaintext(true) @@ -89,7 +89,7 @@ public void beforeClass() { blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); } - @Test(enabled = false, threadPoolSize = 1, invocationCount = 1) + @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) public void testMutiSignForSmartContract() { ecKey1 = new ECKey(Utils.getRandom()); manager1Address = ecKey1.getAddress(); diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign008.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest002.java similarity index 98% rename from framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign008.java rename to framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest002.java index 494528c6481..776816729dd 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign008.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest002.java @@ -27,7 +27,7 @@ import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; @Slf4j -public class WalletTestMutiSign008 { +public class MutiSignSmartContractTest002 { private final String testKey002 = Configuration.getByPath("testng.conf") .getString("foundationAccount.key1"); @@ -77,7 +77,7 @@ public void beforeSuite() { * constructor. */ - @BeforeClass(enabled = false) + @BeforeClass(enabled = true) public void beforeClass() { channelFull = ManagedChannelBuilder.forTarget(fullnode) .usePlaintext(true) @@ -89,7 +89,7 @@ public void beforeClass() { blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); } - @Test(enabled = false, threadPoolSize = 1, invocationCount = 1) + @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) public void testMutiSignForSmartContract() { ecKey1 = new ECKey(Utils.getRandom()); manager1Address = ecKey1.getAddress(); diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign019.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignUpdataBrokerageTest.java similarity index 99% rename from framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign019.java rename to framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignUpdataBrokerageTest.java index 98c0dffb77b..ef6211ceab6 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/WalletTestMutiSign019.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignUpdataBrokerageTest.java @@ -22,7 +22,7 @@ @Slf4j -public class WalletTestMutiSign019 { +public class MutiSignUpdataBrokerageTest { private static final long now = System.currentTimeMillis(); private final String testKey002 = Configuration.getByPath("testng.conf") @@ -74,7 +74,7 @@ public void beforeClass() { blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); } - @Test(enabled = false) + @Test(enabled = true) public void testMutiSignForUpdateBrokerage() { long needcoin = updateAccountPermissionFee * 2 + multiSignFee * 5; Assert.assertTrue(PublicMethed 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 index 8c8b476a6b5..ad1a1d83123 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken011.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken011.java @@ -91,7 +91,7 @@ public void beforeClass() { } @Test(enabled = true, description = "TransferToken with correct value, deploy transfer contract") - public void test01DeployTransferTokenContract() { + public void test01DeployTransferTokenContract001() { Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 15048_000_000L, fromAddress, testKey002, blockingStubFull)); Assert.assertTrue(PublicMethed.sendcoin(user001Address, 14048_000_000L, fromAddress, @@ -192,7 +192,7 @@ public void test01DeployTransferTokenContract() { @Test(enabled = true, description = "TransferToken with correct value, deploy receive contract") - public void test02DeployRevContract() { + public void test02DeployRevContract002() { Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 50000L, blockingStubFull), 0, 1, @@ -263,7 +263,7 @@ public void test02DeployRevContract() { } @Test(enabled = true, description = "TransferToken with correct value, transfer to a contract") - public void test03TriggerContract() { + public void test03TriggerContract003() { Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, @@ -387,7 +387,7 @@ public void test03TriggerContract() { } @Test(enabled = true, description = "TransferToken with correct value, get contract tokenBalance") - public void test04TriggerTokenBalanceContract() { + public void test04TriggerTokenBalanceContract004() { Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 1000_000_000L, 0, 1, user001Key, blockingStubFull)); PublicMethed.waitProduceNextBlock(blockingStubFull); @@ -477,7 +477,7 @@ public void test04TriggerTokenBalanceContract() { } @Test(enabled = true, description = "TransferToken after get transaction info by blocknum") - public void test05GetTransactionInfoByBlocknum() { + public void test05GetTransactionInfoByBlocknum005() { Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, blockingStubFull), 0, 1, @@ -524,7 +524,7 @@ public void test05GetTransactionInfoByBlocknum() { } @Test(enabled = true, description = "get transaction info by blocknum from solidity") - public void test06GetTransactionInfoByBlocknumFromSolidity() { + public void test06GetTransactionInfoByBlocknumFromSolidity006() { Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, blockingStubFull), 0, 1, 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 index 75944cea276..9bdf877a295 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken026.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken026.java @@ -80,7 +80,7 @@ public void beforeClass() { } @Test(enabled = true, description = "Deploy transferToken contract") - public void deploy01TransferTokenContract() { + public void deploy01TransferTokenContract001() { Assert .assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, fromAddress, @@ -154,7 +154,7 @@ public void deploy01TransferTokenContract() { } @Test(enabled = true, description = "Multistage call transferToken use right tokenID") - public void deploy02TransferTokenContract() { + public void deploy02TransferTokenContract002() { Account info; AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(dev001Address, blockingStubFull); @@ -262,7 +262,7 @@ public void deploy02TransferTokenContract() { } @Test(enabled = true, description = "Multistage call transferToken use fake tokenID") - public void deploy03TransferTokenContract() { + public void deploy03TransferTokenContract003() { Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(dev001Address, blockingStubFull); @@ -372,7 +372,7 @@ public void deploy03TransferTokenContract() { } @Test(enabled = true, description = "Multistage call transferToken token value not enough") - public void deploy04TransferTokenContract() { + public void deploy04TransferTokenContract004() { Account infoafter1 = PublicMethed.queryAccount(dev001Address, blockingStubFull); AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(dev001Address, blockingStubFull); @@ -467,7 +467,7 @@ public void deploy04TransferTokenContract() { } @Test(enabled = true, description = "Multistage call transferToken calltoken ID not exist") - public void deploy05TransferTokenContract() { + public void deploy05TransferTokenContract005() { Account infoafter2 = PublicMethed.queryAccount(dev001Address, blockingStubFull); AccountResourceMessage resourceInfoafter2 = PublicMethed.getAccountResource(dev001Address, blockingStubFull); @@ -565,7 +565,7 @@ public void deploy05TransferTokenContract() { } @Test(enabled = true, description = "Multistage call transferToken calltoken value not enough") - public void deploy06TransferTokenContract() { + public void deploy06TransferTokenContract006() { Account infoafter3 = PublicMethed.queryAccount(dev001Address, blockingStubFull); AccountResourceMessage resourceInfoafter3 = PublicMethed.getAccountResource(dev001Address, blockingStubFull); @@ -662,7 +662,7 @@ public void deploy06TransferTokenContract() { } @Test(enabled = true, description = "Multistage call transferToken use right tokenID,tokenvalue") - public void deploy07TransferTokenContract() { + public void deploy07TransferTokenContract007() { Account infoafter4 = PublicMethed.queryAccount(dev001Address, blockingStubFull); AccountResourceMessage resourceInfoafter4 = PublicMethed.getAccountResource(dev001Address, blockingStubFull); 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 index d4033136621..16411b25166 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken039.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken039.java @@ -150,7 +150,8 @@ public void deploy01TransferTokenContract() { PublicMethed.waitProduceNextBlock(blockingStubFull); } - @Test(enabled = true, description = "Trigger Proxy contract use AddressA") + @Test(enabled = true, dependsOnMethods = "deploy01TransferTokenContract", + description = "Trigger Proxy contract use AddressA") public void deploy02TransferTokenContract() { Account info; AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(dev001Address, @@ -260,7 +261,8 @@ public void deploy02TransferTokenContract() { Assert.assertTrue(afterAssetIssueBAddress == beforeAssetIssueBAddress); } - @Test(enabled = true, description = "Trigger Proxy contract use AddressB") + @Test(enabled = true,dependsOnMethods = "deploy02TransferTokenContract", + description = "Trigger Proxy contract use AddressB") public void deploy03TransferTokenContract() { Account info1; AccountResourceMessage resourceInfo1 = PublicMethed.getAccountResource(dev001Address, 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 index 9b4f034c494..3265a996fe5 100644 --- 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 @@ -102,7 +102,7 @@ public void test01Correct16signatures() { 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", + + ": CPU timeout for 'ISZERO' operation executing", transactionExtention.getResult().getMessage().toStringUtf8()); } else { Assert.assertEquals("11111111111111110000000000000000", @@ -134,10 +134,8 @@ public void test02Incorrect1stSignatures() { 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()); + 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())); @@ -167,10 +165,8 @@ public void test03Incorrect1stAddress() { 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()); + 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())); @@ -179,7 +175,7 @@ public void test03Incorrect1stAddress() { } } - @Test(enabled = false, description = "16 signatures with 15th incorrect signatures" + @Test(enabled = true, description = "16 signatures with 15th incorrect signatures" + " test pure multivalidatesign") public void test04Incorrect15thSignatures() { List signatures = new ArrayList<>(); @@ -204,10 +200,8 @@ public void test04Incorrect15thSignatures() { 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()); + 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())); @@ -216,7 +210,7 @@ public void test04Incorrect15thSignatures() { } } - @Test(enabled = false, description = "15 signatures with 10th-15th incorrect address" + @Test(enabled = true, description = "15 signatures with 10th-15th incorrect address" + " test pure multivalidatesign") public void test05Incorrect15thTo30thAddress() { List signatures = new ArrayList<>(); @@ -239,10 +233,8 @@ public void test05Incorrect15thTo30thAddress() { 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()); + 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())); @@ -251,7 +243,7 @@ public void test05Incorrect15thTo30thAddress() { } } - @Test(enabled = true, description = "16 signatures with 2nd、16th incorrect signatures" + @Test(enabled = true, description = "16 signatures with 2nd/16th incorrect signatures" + " test pure multivalidatesign") public void test06Incorrect2ndAnd32ndIncorrectSignatures() { List signatures = new ArrayList<>(); @@ -276,10 +268,8 @@ public void test06Incorrect2ndAnd32ndIncorrectSignatures() { 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()); + 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())); @@ -288,7 +278,7 @@ public void test06Incorrect2ndAnd32ndIncorrectSignatures() { } } - @Test(enabled = true, description = "16 signatures with 6th、9th、11th、13nd incorrect address" + @Test(enabled = true, description = "16 signatures with 6th/9th/11th/13nd incorrect address" + " test pure multivalidatesign") public void test07IncorrectAddress() { List signatures = new ArrayList<>(); @@ -312,10 +302,8 @@ public void test07IncorrectAddress() { 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()); + 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())); @@ -352,10 +340,8 @@ public void test08IncorrectHash() { 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()); + 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())); 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 index 7474dd117c8..bd83ff46804 100644 --- 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 @@ -120,9 +120,8 @@ public void test01Correct16signatures() { Assert.assertEquals("11111111111111110000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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(); @@ -192,9 +191,8 @@ public void test02Incorrect1stSignatures() { Assert.assertEquals("01111111111111000000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") + || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); PublicMethed.waitProduceNextBlock(blockingStubFull); } @@ -264,9 +262,8 @@ public void test03Incorrect1stAddress() { Assert.assertEquals("01111111111110000000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") + || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); PublicMethed.waitProduceNextBlock(blockingStubFull); } @@ -407,9 +404,8 @@ public void test05Incorrect15thTo30thAddress() { Assert.assertEquals("11111111100000100000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") + || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); PublicMethed.waitProduceNextBlock(blockingStubFull); } @@ -483,9 +479,8 @@ public void test06Incorrect2ndAnd32ndIncorrectSignatures() { Assert.assertEquals("10111111111111100000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") + || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); PublicMethed.waitProduceNextBlock(blockingStubFull); } @@ -516,7 +511,7 @@ public void test06Incorrect2ndAnd32ndIncorrectSignatures() { Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); } - @Test(enabled = true, description = "16 signatures with 6th、9th、11th、13nd incorrect address" + @Test(enabled = true, description = "16 signatures with 6th/9th/11th/13nd incorrect address" + " test multivalidatesign") public void test07IncorrectAddress() { GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed @@ -558,9 +553,8 @@ public void test07IncorrectAddress() { Assert.assertEquals("11111011010101110000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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(); @@ -632,9 +626,8 @@ public void test08IncorrectHash() { Assert.assertEquals("00000000000000000000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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(); 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 index 941127adfc4..5204f09d2cd 100644 --- 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 @@ -103,10 +103,8 @@ public void test01With25SignaturesAnd24Address() { 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()); + 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())); @@ -135,10 +133,8 @@ public void test02With15SignaturesAnd16Address() { 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()); + 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())); @@ -166,10 +162,8 @@ public void test03With150SignaturesAnd1Address() { 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()); + 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())); @@ -197,10 +191,8 @@ public void test04With1SignaturesAnd160Address() { 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()); + 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())); @@ -229,10 +221,8 @@ public void test05With32SignaturesAnd33Address() { 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()); + 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())); @@ -262,10 +252,8 @@ public void test06With33SignaturesAnd32Address() { 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()); + 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())); 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 index b57a4e4895e..6dfef29f07d 100644 --- 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 @@ -188,9 +188,8 @@ public void test02With15SignaturesAnd16Address() { Assert.assertEquals("00000000000000000000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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(); @@ -257,9 +256,8 @@ public void test03With40SignaturesAnd1Address() { Assert.assertEquals("00000000000000000000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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(); @@ -326,9 +324,8 @@ public void test04With1SignaturesAnd50Address() { Assert.assertEquals("00000000000000000000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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(); @@ -396,9 +393,8 @@ public void test05With32SignaturesAnd33Address() { Assert.assertEquals("00000000000000000000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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(); @@ -467,9 +463,8 @@ public void test06With33SignaturesAnd32Address() { Assert.assertEquals("00000000000000000000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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(); 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 index 4aee90b92e2..3ec33ef164c 100644 --- 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 @@ -103,10 +103,8 @@ public void test01HashIsEmpty() { 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()); + 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())); @@ -133,10 +131,8 @@ public void test02AddressIsEmpty() { 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()); + 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())); @@ -163,10 +159,8 @@ public void test03SignaturesIsEmpty() { 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()); + 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())); @@ -188,10 +182,8 @@ public void test04SignaturesAndAddressesAreEmpty() { 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()); + 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())); @@ -213,10 +205,8 @@ public void test05AllEmpty() { 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()); + 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())); 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 index f16c323f3a7..c8af1fbb218 100644 --- 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 @@ -123,9 +123,8 @@ public void test01HashIsEmpty() { Assert.assertEquals("00000000000000000000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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(); @@ -190,9 +189,8 @@ public void test02AddressIsEmpty() { Assert.assertEquals("00000000000000000000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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(); @@ -257,9 +255,8 @@ public void test03SignaturesIsEmpty() { Assert.assertEquals("00000000000000000000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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(); @@ -319,9 +316,8 @@ public void test04SignaturesAndAddressesAreEmpty() { Assert.assertEquals("00000000000000000000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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(); @@ -381,9 +377,8 @@ public void test05AllEmpty() { Assert.assertEquals("00000000000000000000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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(); 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 index 4dbc596f641..c552001fc4c 100644 --- 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 @@ -146,9 +146,8 @@ public void test01Constructor() { Assert.assertEquals("11111111111111110000000000000000", PublicMethed.bytes32ToString(infoById2.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById2.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById2.get().getResMessage().toStringUtf8())); + 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(); 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 index 0294b763ee4..291f1393e60 100644 --- 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 @@ -99,10 +99,8 @@ public void test01Correct50Signatures() { 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()); + 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())); @@ -133,10 +131,8 @@ public void test02Incorrect1stSignatures() { 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()); + 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())); @@ -166,10 +162,8 @@ public void test03Incorrect1stAddress() { 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()); + 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())); @@ -200,10 +194,8 @@ public void test04Incorrect15thSignatures() { 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()); + 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())); @@ -235,10 +227,8 @@ public void test05Incorrect15thTo30thAddress() { 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()); + 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())); @@ -247,7 +237,7 @@ public void test05Incorrect15thTo30thAddress() { } } - @Test(enabled = true, description = "150 signatures with 2nd、32nd incorrect signatures" + @Test(enabled = true, description = "150 signatures with 2nd/32nd incorrect signatures" + " test multivalidatesign") public void test06Incorrect2ndAnd32ndIncorrectSignatures() { List signatures = new ArrayList<>(); @@ -272,10 +262,8 @@ public void test06Incorrect2ndAnd32ndIncorrectSignatures() { 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()); + 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())); @@ -284,7 +272,7 @@ public void test06Incorrect2ndAnd32ndIncorrectSignatures() { } } - @Test(enabled = true, description = "88 signatures with 9th、11th、28th、32nd incorrect address" + @Test(enabled = true, description = "88 signatures with 9th/11th/28th/32nd incorrect address" + " test multivalidatesign") public void test07IncorrectAddress() { List signatures = new ArrayList<>(); @@ -308,10 +296,8 @@ public void test07IncorrectAddress() { 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()); + 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())); @@ -344,10 +330,8 @@ public void test08IncorrectHash() { 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()); + 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())); 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 index 60fe4937b09..848afd5cdb5 100644 --- 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 @@ -143,9 +143,8 @@ public void test01Correct33Signatures() { PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); Assert.assertTrue(afterBalance + fee == beforeBalance); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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, @@ -197,9 +196,8 @@ public void test02Incorrect1stSignatures() { Assert.assertEquals("01111111111111000000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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(); @@ -268,9 +266,8 @@ public void test03Incorrect1stAddress() { Assert.assertEquals("01111111000000000000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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(); @@ -340,9 +337,8 @@ public void test04Incorrect15thSignatures() { Assert.assertEquals("11011100000000000000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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(); @@ -413,9 +409,8 @@ public void test05Incorrect15thTo30thAddress() { Assert.assertEquals("11111100011000000000000000000000", PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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(); @@ -513,9 +508,8 @@ public void test06Incorrect2ndAnd32ndIncorrectSignatures() { PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); Assert.assertTrue(afterBalance + fee == beforeBalance); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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, @@ -527,7 +521,7 @@ public void test06Incorrect2ndAnd32ndIncorrectSignatures() { Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); } - @Test(enabled = true, description = "44 signatures with 9th、11th、28th、32nd incorrect address" + @Test(enabled = true, description = "44 signatures with 9th/11th/28th/32nd incorrect address" + " test multivalidatesign") public void test07IncorrectAddress() { GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed @@ -592,9 +586,8 @@ public void test07IncorrectAddress() { PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); Assert.assertTrue(afterBalance + fee == beforeBalance); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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, @@ -671,9 +664,8 @@ public void test08IncorrectHash() { PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); Assert.assertTrue(afterBalance + fee == beforeBalance); } else { - Assert.assertTrue("CPU timeout for 'PUSH1' operation executing" - .equals(infoById.get().getResMessage().toStringUtf8()) || "Already Time Out" - .equals(infoById.get().getResMessage().toStringUtf8())); + 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, 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 index c132db6c8e7..f635f22a5b0 100644 --- 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 @@ -280,10 +280,8 @@ public void test03TriggerCreate2ToDeployTestContract2() { 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")); + // Istanbul change create2 algorithm + Assert.assertEquals(0, infoById.get().getResultValue()); } @Test(enabled = true, description = "Trigger create2 command without meta data hash in bytecode") 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 index 024662ee5c9..15f90ce3baf 100644 --- 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 @@ -533,7 +533,8 @@ public void test05TriggerCreate2ToDeployTestContract() { Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); } - @Test(enabled = true, description = "Trigger create2 with salt f * 64") + // 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, 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 index 190ada0f79c..164bb833da3 100644 --- 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 @@ -332,7 +332,8 @@ public void test02TriggerCreate2ToDeployTestContractAgain() { containsString("Not enough energy for 'SWAP1' operation executing")); } - @Test(enabled = true, description = "Same code, salt and address," + // 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, @@ -532,7 +533,8 @@ public void test04TriggerTest1Contract() { logger.info("ConsumeURPercent: " + consumeUserPercent); } - @Test(enabled = true, description = "Trigger test2 contract") + // Istanbul change create2 algorithm + @Test(enabled = false, description = "Trigger test2 contract") public void test05TriggerTest2Contract() { Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 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 index f90b6012631..cda4af19ff8 100644 --- 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 @@ -58,10 +58,10 @@ public class Create2Test021 { .getStringList("fullnode.ip.list").get(1); private String soliditynode = Configuration.getByPath("testng.conf") .getStringList("solidityNode.ip.list").get(0); - private byte[] contractExcAddress = PublicMethed - .getFinalAddress("9fc9b78370cdeab1bc11ba5e387e5e4f205f17d1957b1bebf4ce6d0330a448a4"); - private String contractExcKey = - "9fc9b78370cdeab1bc11ba5e387e5e4f205f17d1957b1bebf4ce6d0330a448a4"; + + ECKey ecKey3 = new ECKey(Utils.getRandom()); + private byte[] contractExcAddress = ecKey3.getAddress(); + private String contractExcKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); @BeforeSuite public void beforeSuite() { @@ -93,7 +93,7 @@ public void beforeClass() { } - @Test(enabled = true, description = "TriggerContract a constant function created by create2") + @Test(enabled = true, description = "resource delegate with create2 contract, and suicide ") public void test1TriggerContract() { Assert.assertTrue(PublicMethed .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, @@ -134,60 +134,13 @@ public void test1TriggerContract() { logger.info("beforeNetUsed:" + beforeNetUsed); logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - bytes = ByteArray.fromHexString("416CED4D6BF0AE10676347961BEFB7F47A8664AE36"); - - String param2 = "\"" + Base58.encode58Check(contractExcAddress) + "\""; - String txidn = PublicMethed - .triggerContract(bytes, - "testSuicideNonexistentTarget(address)", param2, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - 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); - 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); - final Long beforeExcAccountBalance = PublicMethed + Long beforeExcAccountBalance = PublicMethed .queryAccount(resourceOnwerAddress, blockingStubFull).getBalance(); - Assert.assertTrue(PublicMethed.getAccountResource(bytes, blockingStubFull).getNetLimit() > 0); - Assert - .assertTrue(PublicMethed.getAccountResource(bytes, blockingStubFull).getEnergyLimit() > 0); - + // create2 TestContract String contractName1 = "TestConstract"; HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = "6080604052600160005534801561001557600080fd5b50d3801561002257600080fd5b50" - + "d2801561002f57600080fd5b506101fd8061003f6000396000f3fe60806040526004361061005b577" - + "c01000000000000000000000000000000000000000000000000000000006000350463040821fc8114" - + "61006057806317b6ad5b1461007f578063cc133e94146100b2578063e5aa3d58146100d5575b60008" - + "0fd5b61007d6004803603602081101561007657600080fd5b5035610116565b005b61007d60048036" - + "03602081101561009557600080fd5b503573ffffffffffffffffffffffffffffffffffffffff16610" - + "147565b61007d600480360360408110156100c857600080fd5b5080359060200135610160565b3480" - + "156100e157600080fd5b50d380156100ee57600080fd5b50d280156100fb57600080fd5b506101046" - + "101cb565b60408051918252519081900360200190f35b604051339082156108fc0290839060008181" - + "81858888f19350505050158015610143573d6000803e3d6000fd5b5050565b8073fffffffffffffff" - + "fffffffffffffffffffffffff16ff5b3382156108fc0283838015801561017657600080fd5b508067" - + "80000000000000001115801561018e57600080fd5b5080620f4240101580156101a157600080fd5b5" - + "0604051600081818185878a8ad09450505050501580156101c6573d6000803e3d6000fd5b50505056" - + "5b6000548156fea165627a7a72305820485b773c60fed3b76621350dd3da7ecf152a2d37ca02dc195" - + "d6f8a26aec196850029"; - String abi1 = retMap1.get("abI").toString(); + String code1 = retMap1.get("byteCode").toString(); String txid = ""; String num = "\"" + code1 + "\"" + "," + 1; txid = PublicMethed @@ -196,28 +149,6 @@ public void test1TriggerContract() { 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); PublicMethed.waitProduceNextBlock(blockingStubFull); - 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); - - 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); Optional infoById = null; infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); @@ -250,8 +181,83 @@ public void test1TriggerContract() { byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() .toByteArray(); String returnAddress = Base58.encode58Check(returnAddressBytes); - Assert.assertEquals(Base58.encode58Check(bytes), returnAddress); 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, @@ -284,8 +290,6 @@ public void test1TriggerContract() { 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); 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 new file mode 100644 index 00000000000..355c8cd30af --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/AltbnTest001.java @@ -0,0 +1,161 @@ +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 new file mode 100644 index 00000000000..b46c56d2ca4 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/ChainidAndSelfBalance001.java @@ -0,0 +1,157 @@ +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 blockZeroId = ByteArray.toHexString(blockZero.getBlockid().toByteArray()); + + 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 new file mode 100644 index 00000000000..9f6d87cf3af --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/Create2IstanbulTest001.java @@ -0,0 +1,105 @@ +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/AbstractTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AbstractTest.java new file mode 100644 index 00000000000..a803f06efe0 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AbstractTest.java @@ -0,0 +1,82 @@ +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"); + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + } + + /** + * 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 new file mode 100644 index 00000000000..d537f06ebd6 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AddressChange.java @@ -0,0 +1,149 @@ +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/BlockhashTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/BlockhashTest.java new file mode 100644 index 00000000000..7a0a5ca4e84 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/BlockhashTest.java @@ -0,0 +1,174 @@ +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()); + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + } + + /** + * 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/LengthTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/LengthTest.java new file mode 100644 index 00000000000..2f7950ed5d9 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/LengthTest.java @@ -0,0 +1,285 @@ +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/OverrideTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/OverrideTest001.java new file mode 100644 index 00000000000..ef46a71a2be --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/OverrideTest001.java @@ -0,0 +1,459 @@ +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()); + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + } + + /** + * 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 new file mode 100644 index 00000000000..65785e99283 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/PayableTest.java @@ -0,0 +1,158 @@ +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 new file mode 100644 index 00000000000..679c472d7e3 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/SelectorTest.java @@ -0,0 +1,108 @@ +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()); + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + } + + /** + * 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/StringSplitTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/StringSplitTest.java new file mode 100644 index 00000000000..c9b10733cd1 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/StringSplitTest.java @@ -0,0 +1,171 @@ +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()); + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + } + + /** + * 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/VirtualTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/VirtualTest001.java new file mode 100644 index 00000000000..ccbc4a54e1f --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/VirtualTest001.java @@ -0,0 +1,211 @@ +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()); + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + } + + /** + * 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 new file mode 100644 index 00000000000..5119dbf5ea0 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/assemblyTest.java @@ -0,0 +1,122 @@ +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()); + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + } + + /** + * 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/enumAndStructTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/enumAndStructTest.java new file mode 100644 index 00000000000..4230379af5a --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/enumAndStructTest.java @@ -0,0 +1,89 @@ +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 new file mode 100644 index 00000000000..bfa8ebf1561 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/fallbackOldVersion.java @@ -0,0 +1,156 @@ +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 new file mode 100644 index 00000000000..63bd60a0d1c --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/fallbackReceive.java @@ -0,0 +1,376 @@ +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/stateVariableShadowing.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/stateVariableShadowing.java new file mode 100644 index 00000000000..82ff090f2e2 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/stateVariableShadowing.java @@ -0,0 +1,140 @@ +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/transferfailed/ContractTestSendCoin001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/ContractTestSendCoin001.java index c488f0b24a6..58222f029b9 100644 --- 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 @@ -378,8 +378,8 @@ public void testSendCoinAndTransferAssetContract002() { } - @Test(enabled = true, description = "Use create2 to generate a contract address \"\n" - + " + \"Sendcoin and transferAsset to contractAddresss ,then selfdestruct") + @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()); 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 index 678f52f2886..cc4de40ade2 100644 --- 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 @@ -135,6 +135,7 @@ public void test01TriggerConstantContract() { 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"));*/ } @@ -150,6 +151,7 @@ public void test01TriggerConstantContractOnSolidity() { 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"));*/ } @@ -165,6 +167,7 @@ public void test01TriggerConstantContractOnRealSolidity() { 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"));*/ } @@ -181,6 +184,7 @@ public void test02TriggerConstantContract() { 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"));*/ } @@ -196,6 +200,7 @@ public void test02TriggerConstantContractOnSolidity() { 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"));*/ } @@ -211,6 +216,7 @@ public void test02TriggerConstantContractOnRealSolidity() { 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"));*/ } @@ -343,6 +349,7 @@ public void test05TriggerConstantContract() { 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); @@ -360,6 +367,7 @@ public void test05TriggerConstantContractOnSolidity() { 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); @@ -376,6 +384,7 @@ public void test05TriggerConstantContractOnRealSolidity() { 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); @@ -392,6 +401,7 @@ public void test06TriggerConstantContract() { 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); @@ -409,6 +419,7 @@ public void test06TriggerConstantContractOnSolidity() { 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); @@ -425,6 +436,7 @@ public void test06TriggerConstantContractOnRealSolidity() { 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); 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 index 077d36f6531..b25c3df3b23 100644 --- 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 @@ -77,10 +77,7 @@ public void beforeClass() { .usePlaintext(true) .build(); blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - @Test(enabled = true, description = "TriggerConstantContract a view function without ABI") - public void test001TriggerConstantContract() { Assert.assertTrue(PublicMethed .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, blockingStubFull)); @@ -95,10 +92,17 @@ public void test001TriggerConstantContract() { 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, @@ -131,8 +135,7 @@ public void test001TriggerConstantContract() { .toHexString(result)))); } - - @Test(enabled = true, description = "TriggerConstantContract a payable function with ABI") + @Test(enabled = true, description = "TriggerConstantContract a pure function without ABI") public void test002TriggerConstantContract() { Account info; @@ -149,6 +152,41 @@ public void test002TriggerConstantContract() { 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, 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 index 982f2f6a178..5b5e81816f0 100644 --- 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 @@ -73,7 +73,7 @@ public void beforeClass() { blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); } - @Test(enabled = true, description = "TriggerConstantContract a payable function with ABI") + @Test(enabled = false, description = "TriggerConstantContract a payable function with ABI") public void testTriggerConstantContract() { Assert.assertTrue(PublicMethed .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, 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 index 47cee15012c..32039867fe3 100644 --- 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 @@ -47,9 +47,12 @@ public class TriggerConstant013 { 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") @@ -58,6 +61,8 @@ public class TriggerConstant013 { .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); @BeforeSuite public void beforeSuite() { @@ -89,6 +94,10 @@ public void beforeClass() { .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") @@ -285,6 +294,31 @@ public void test15TriggerConstantContractOnRealSolidity() { .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. */ 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 new file mode 100644 index 00000000000..25872dbd324 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tryCatch/tryCatchTest001.java @@ -0,0 +1,256 @@ +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); + + 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(1,transactionInfo.get().getResultValue()); + Assert.assertEquals(transactionInfo.get().getFee(), maxFeeLimit.longValue()); + Assert.assertEquals(contractResult.OUT_OF_ENERGY, + 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(1,transactionInfo.get().getResultValue()); + Assert.assertEquals(transactionInfo.get().getFee(), maxFeeLimit.longValue()); + Assert.assertEquals(contractResult.OUT_OF_ENERGY, + 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(1,transactionInfo.get().getResultValue()); + Assert.assertEquals(transactionInfo.get().getFee(), maxFeeLimit.longValue()); + Assert.assertEquals(contractResult.OUT_OF_ENERGY, + 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 new file mode 100644 index 00000000000..b4427147611 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tryCatch/tryCatchTest002.java @@ -0,0 +1,249 @@ +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); + + 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(1,transactionInfo.get().getResultValue()); + Assert.assertEquals(maxFeeLimit.longValue(), transactionInfo.get().getFee()); + Assert.assertEquals(contractResult.OUT_OF_ENERGY, + transactionInfo.get().getReceipt().getResult()); + + } + + @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(1,transactionInfo.get().getResultValue()); + Assert.assertEquals(maxFeeLimit.longValue(), transactionInfo.get().getFee()); + Assert.assertEquals(contractResult.OUT_OF_ENERGY, + 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(1,transactionInfo.get().getResultValue()); + Assert.assertEquals(maxFeeLimit.longValue(), transactionInfo.get().getFee()); + Assert.assertEquals(contractResult.OUT_OF_ENERGY, + transactionInfo.get().getReceipt().getResult()); + + } + +} 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 new file mode 100644 index 00000000000..7ee912dcebd --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue001.java @@ -0,0 +1,286 @@ +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()); + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(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.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 new file mode 100644 index 00000000000..46916c73939 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue002.java @@ -0,0 +1,748 @@ +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()); + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(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.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 new file mode 100644 index 00000000000..3e2f3b9011d --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue003.java @@ -0,0 +1,868 @@ +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()); + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(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.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 new file mode 100644 index 00000000000..aa4ae1cd375 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue004.java @@ -0,0 +1,209 @@ +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()); + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(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.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 new file mode 100644 index 00000000000..ba7f60d1160 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue005.java @@ -0,0 +1,707 @@ +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()); + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(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.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 new file mode 100644 index 00000000000..2dbc0b54cf9 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/ContractRewardTest001.java @@ -0,0 +1,233 @@ +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 new file mode 100644 index 00000000000..c1a3d68992e --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/IsSrCandidateTest001.java @@ -0,0 +1,118 @@ +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 new file mode 100644 index 00000000000..f1a43ad8e49 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StackSuicideTest001.java @@ -0,0 +1,247 @@ +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 new file mode 100644 index 00000000000..2856b2d436c --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest002.java @@ -0,0 +1,186 @@ +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 new file mode 100644 index 00000000000..6393aece552 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest003.java @@ -0,0 +1,196 @@ +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 new file mode 100644 index 00000000000..69bcbcff619 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest004.java @@ -0,0 +1,397 @@ +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 new file mode 100644 index 00000000000..b324672d6ab --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest005.java @@ -0,0 +1,204 @@ +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 new file mode 100644 index 00000000000..4b9102fc901 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeTest001.java @@ -0,0 +1,312 @@ +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 new file mode 100644 index 00000000000..57feb98c49c --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/UnStakeTest001.java @@ -0,0 +1,471 @@ +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.spongycastle.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/zenProofCommand/VerifyBurnProof001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/VerifyBurnProof001.java index 4e3dc454bae..dbdcdadb800 100644 --- 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 @@ -231,7 +231,7 @@ public void verifyBurnProofTest004() { // parseLong will return Long.MAX_VALUE and checkResult false Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000000", contractResult); + + "0000000000000000000000000000000000000000000000000000000000000000", contractResult); } @Test(enabled = true, description = "verify success with address call") @@ -323,7 +323,7 @@ public void verifyBurnProofTest006() { infoById.get().getContractResult(0).toByteArray()); Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000001", contractResult); + + "0000000000000000000000000000000000000000000000000000000000000001", contractResult); } 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 index 421789fb1cd..67518968128 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token002.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token002.java @@ -14,8 +14,12 @@ @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; @@ -23,9 +27,6 @@ public class HttpShieldTrc20Token002 extends ZenTrc20Base { private JSONObject shieldAccountInfo; private JSONArray noteTxs; private Long publicFromAmount = getRandomLongAmount(); - JSONArray shieldedReceives = new JSONArray(); - String txid; - @Test(enabled = true, description = "Get new shield account by http") public void test01GetNewShieldAccountByHttp() { @@ -57,7 +58,7 @@ public void test02MintByHttp() { responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); @@ -80,7 +81,7 @@ public void test02MintByHttp() { responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); @@ -126,7 +127,7 @@ public void test04ShiledTrc20BurnByHttp() { responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, burn, responseContent .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); @@ -176,7 +177,7 @@ public void test05ShiledTrc20BurnWithoutAskByHttp() { responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, burn, responseContent .getString("value"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); 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 index d2613aecd3c..5fdc4e8039a 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token003.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token003.java @@ -15,8 +15,13 @@ @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; @@ -33,9 +38,6 @@ public class HttpShieldTrc20Token003 extends ZenTrc20Base { private Long account1Receive2V2Amount = 13L; private Long account2Receive2V2Amount = publicFromAmount + account2Receive1V2Amount - account1Receive2V2Amount; - JSONArray shieldedReceives = new JSONArray(); - String txid; - JSONArray shieldSpends = new JSONArray(); /** * constructor. @@ -59,7 +61,7 @@ public void prepareForTransfer() { responseContent = HttpMethed.parseResponseContent(response); //HttpMethed.printJsonContent(responseContent); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); @@ -74,7 +76,7 @@ public void prepareForTransfer() { responseContent = HttpMethed.parseResponseContent(response); //HttpMethed.printJsonContent(responseContent); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); @@ -98,7 +100,7 @@ public void test01TransferTypeWith1V1ByHttp() { responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); @@ -142,7 +144,7 @@ public void test02TransferTypeWith1V2ByHttp() { HttpMethed.printJsonContent(responseContent); Assert.assertTrue(responseContent.containsKey("trigger_contract_input")); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); @@ -187,7 +189,7 @@ public void test03TransferTypeWith2V2ByHttp() { HttpMethed.printJsonContent(responseContent); Assert.assertTrue(responseContent.containsKey("trigger_contract_input")); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); @@ -238,7 +240,7 @@ public void test04TransferTypeWith2V1ByHttp() { HttpMethed.printJsonContent(responseContent); Assert.assertTrue(responseContent.containsKey("trigger_contract_input")); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); 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 index efb0e55fc5c..c874776919f 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token004.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token004.java @@ -15,10 +15,17 @@ @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; @@ -33,9 +40,6 @@ public class HttpShieldTrc20Token004 extends ZenTrc20Base { private Long account1Receive2V2Amount = 13L; private Long account2Receive2V2Amount = publicFromAmount + account2Receive1V2Amount - account1Receive2V2Amount; - JSONArray shieldedReceives = new JSONArray(); - String txid; - JSONArray shieldSpends = new JSONArray(); /** * constructor. @@ -60,7 +64,7 @@ public void prepareForTransfer() { responseContent = HttpMethed.parseResponseContent(response); //HttpMethed.printJsonContent(responseContent); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); @@ -75,7 +79,7 @@ public void prepareForTransfer() { responseContent = HttpMethed.parseResponseContent(response); //HttpMethed.printJsonContent(responseContent); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); @@ -111,7 +115,7 @@ public void test01TransferTypeWith1V1WithoutAskByHttp() { responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent .getString("value"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); @@ -165,7 +169,7 @@ public void test02TransferTypeWith1V2WithoutAskByHttp() { responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent .getString("value"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); @@ -225,7 +229,7 @@ public void test03TransferTypeWith2V2WithoutAskByHttp() { responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent .getString("value"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); @@ -293,7 +297,7 @@ public void test04TransferTypeWith2V1WithoutAskByHttp() { responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent .getString("value"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); @@ -314,35 +318,51 @@ public void test04TransferTypeWith2V1WithoutAskByHttp() { 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 by http") - public void test05ScanNoteByIvkAndOvkOnSOlidityByHttp() { + @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); } 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 index 2d17ef07f90..998a97a9322 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token005.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token005.java @@ -15,8 +15,12 @@ @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; @@ -25,8 +29,6 @@ public class HttpShieldTrc20Token005 extends ZenTrc20Base { private JSONObject shieldReceiverAccountInfo; private JSONArray noteTxs; private Long publicFromAmount = getRandomLongAmount(); - JSONArray shieldedReceives = new JSONArray(); - String txid; /** * constructor. @@ -43,7 +45,7 @@ public void createTwoNote() { responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); @@ -61,7 +63,7 @@ public void createTwoNote() { responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); @@ -96,7 +98,7 @@ public void test01ShiledTrc20BurnToOnePublicAndOneShieldByHttp() { responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, burn, responseContent .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); @@ -157,7 +159,7 @@ public void test02ShiledTrc20BurnWithoutAskToOnePublicAndOneShieldByHttp() { responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode, + txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, zenTrc20TokenOwnerAddressString, shieldAddress, burn, responseContent .getString("value"), maxFeeLimit, 0L, 0, 0L, zenTrc20TokenOwnerKey); 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 index a5929d194b8..079e46de22d 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token006.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token006.java @@ -29,6 +29,8 @@ public class ShieldTrc20Token006 extends ZenTrc20Base { .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; @@ -60,6 +62,11 @@ public void beforeClass() throws Exception { .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 @@ -416,12 +423,47 @@ public void test04ScanShieldTrc20NoteByIvkAndOvkOnSolidity() throws Exception { 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") - public void test05IsShieldTrc20NoteSpendOnSolidity() throws Exception { + @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(), @@ -435,20 +477,36 @@ public void test05IsShieldTrc20NoteSpendOnSolidity() throws Exception { getTrc20SpendResult(shieldAddressInfo1.get(), shield1Note.getNoteTxs(0), blockingStubFull, blockingStubSolidity)); - Assert.assertEquals(getTrc20SpendResult(shieldAddressInfo1.get(), - shield1Note.getNoteTxs(1), blockingStubFull), + 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)); - Assert.assertEquals(getTrc20SpendResult(shieldAddressInfo2.get(), - shield2Note.getNoteTxs(0), blockingStubFull), + 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)); - Assert.assertEquals(getTrc20SpendResult(shieldAddressInfo2.get(), - shield2Note.getNoteTxs(1), blockingStubFull), + 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)); } diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/SuperWitnessAllowance.java b/framework/src/test/java/stest/tron/wallet/fulltest/SuperWitnessAllowance.java index 5970f702baa..f13cc4c09df 100644 --- a/framework/src/test/java/stest/tron/wallet/fulltest/SuperWitnessAllowance.java +++ b/framework/src/test/java/stest/tron/wallet/fulltest/SuperWitnessAllowance.java @@ -195,11 +195,7 @@ public Boolean createWitness(byte[] owner, byte[] url, String priKey) { } transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } + return response.getResult(); } diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAccount2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAccount2Test.java index 1e0138ef007..092bf60e0c5 100644 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAccount2Test.java +++ b/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAccount2Test.java @@ -887,10 +887,7 @@ public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDura transaction = TransactionUtils.sign(transaction, ecKey); GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } - return true; + return response.getResult(); } diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAsset2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAsset2Test.java index 825293bb7d0..fb5e6d067bd 100644 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAsset2Test.java +++ b/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAsset2Test.java @@ -457,7 +457,7 @@ public boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, Transaction transaction = blockingStubFull.participateAssetIssue(contract); transaction = signTransaction(ecKey, transaction); Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { + if (!response.getResult()) { logger.info(ByteArray.toStr(response.getMessage().toByteArray())); return false; } else { diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/VoteWitnessAccount2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/VoteWitnessAccount2Test.java index 4a86b224923..4b809a71445 100644 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/VoteWitnessAccount2Test.java +++ b/framework/src/test/java/stest/tron/wallet/newaddinterface2/VoteWitnessAccount2Test.java @@ -224,7 +224,7 @@ public Boolean voteWitness(HashMap witness, byte[] addRess, Stri transaction = signTransaction(ecKey, transaction); Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { + if (!response.getResult()) { logger.info(ByteArray.toStr(response.getMessage().toByteArray())); return false; } @@ -529,11 +529,7 @@ public boolean unFreezeBalance(byte[] addRess, String priKey) { transaction = TransactionUtils.setTimestamp(transaction); transaction = TransactionUtils.sign(transaction, ecKey); Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } + return response.getResult(); } /** diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/WithdrawBalance2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/WithdrawBalance2Test.java index 78d8c81d871..1b972d2289f 100644 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/WithdrawBalance2Test.java +++ b/framework/src/test/java/stest/tron/wallet/newaddinterface2/WithdrawBalance2Test.java @@ -139,12 +139,11 @@ public boolean withdrawBalance(byte[] address, String priKey) { transaction = signTransaction(ecKey, transaction); Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { + if (!response.getResult()) { return false; } logger.info("test withdraw" + priKey); return true; - } /** @@ -187,12 +186,11 @@ public Return withdrawBalance2(byte[] address, String priKey) { ECKey ecKey = temKey; transaction = signTransaction(ecKey, transaction); Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { + if (!response.getResult()) { return response; } logger.info("test withdraw" + priKey); return ret; - } /** @@ -240,7 +238,7 @@ public Boolean voteWitness(HashMap witness, byte[] address, Stri transaction = signTransaction(ecKey, transaction); Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { + if (!response.getResult()) { return false; } Account afterVote = queryAccount(ecKey, searchBlockingStubFull); diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/SupportTronlinkAutoTest.java b/framework/src/test/java/stest/tron/wallet/onlinestress/SupportTronlinkAutoTest.java index 983e1e9db88..39bded48aa2 100644 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/SupportTronlinkAutoTest.java +++ b/framework/src/test/java/stest/tron/wallet/onlinestress/SupportTronlinkAutoTest.java @@ -373,12 +373,6 @@ public Boolean createWitness(byte[] owner, byte[] url, String priKey) { } transaction = PublicMethed.signTransaction(ecKey, transaction); GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - + return response.getResult(); } - } \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestStorageAndCpu.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestStorageAndCpu.java index 439dfb11a23..0a4ce052157 100644 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestStorageAndCpu.java +++ b/framework/src/test/java/stest/tron/wallet/onlinestress/TestStorageAndCpu.java @@ -3,6 +3,7 @@ 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; @@ -13,15 +14,19 @@ 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 { @@ -49,10 +54,8 @@ public class TestStorageAndCpu { 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 String fullnode = "47.94.243.150:50051"; + private String fullnode1 = "47.94.243.150:50051"; @BeforeSuite public void beforeSuite() { @@ -81,6 +84,37 @@ public void beforeClass() { 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(); diff --git a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer001.java b/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer001.java index 9110114e17e..738ee458959 100644 --- a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer001.java +++ b/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer001.java @@ -264,11 +264,7 @@ public Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey) { } transaction = signTransaction(ecKey, transaction); Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } + return response.getResult(); } /** diff --git a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer003.java b/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer003.java index 1be9a8c33a1..14691c6dd27 100644 --- a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer003.java +++ b/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer003.java @@ -125,10 +125,9 @@ public static Protocol.Transaction sendcoin(byte[] to, long amount, byte[] owner } transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { + if (!response.getResult()) { logger.info(ByteArray.toStr(response.getMessage().toByteArray())); } - return transaction; } @@ -386,13 +385,10 @@ public Protocol.Transaction updateAccount(byte[] addressBytes, byte[] accountNam } transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { + if (!response.getResult()) { logger.info(ByteArray.toStr(response.getMessage().toByteArray())); } - return transaction; - - } } diff --git a/framework/src/test/java/stest/tron/wallet/witness/WalletTestWitness001.java b/framework/src/test/java/stest/tron/wallet/witness/WalletTestWitness001.java index 85d4f2513e1..07d67ca2b2d 100644 --- a/framework/src/test/java/stest/tron/wallet/witness/WalletTestWitness001.java +++ b/framework/src/test/java/stest/tron/wallet/witness/WalletTestWitness001.java @@ -186,7 +186,7 @@ public Boolean voteWitness(HashMap witness, byte[] addRess, Stri transaction = signTransaction(ecKey, transaction); Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { + if (!response.getResult()) { logger.info(ByteArray.toStr(response.getMessage().toByteArray())); return false; } @@ -262,7 +262,7 @@ public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDura transaction = TransactionUtils.sign(transaction, ecKey); Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { + if (!response.getResult()) { return false; } @@ -343,11 +343,7 @@ public boolean unFreezeBalance(byte[] addRess, String priKey) { transaction = TransactionUtils.setTimestamp(transaction); transaction = TransactionUtils.sign(transaction, ecKey); Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } + return response.getResult(); } /** diff --git a/framework/src/test/resources/daily-build.xml b/framework/src/test/resources/daily-build.xml index a5872a35f6a..4120973c34a 100644 --- a/framework/src/test/resources/daily-build.xml +++ b/framework/src/test/resources/daily-build.xml @@ -7,7 +7,10 @@ + + + \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/AssertException002.sol b/framework/src/test/resources/soliditycode/AssertException002.sol index 2bff1dcec3e..15cc07ff984 100644 --- a/framework/src/test/resources/soliditycode/AssertException002.sol +++ b/framework/src/test/resources/soliditycode/AssertException002.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract AssertException{ function divideIHaveArgsReturn(int x,int y) public returns (int z) { diff --git a/framework/src/test/resources/soliditycode/BlockHash.sol b/framework/src/test/resources/soliditycode/BlockHash.sol new file mode 100644 index 00000000000..6603da65e44 --- /dev/null +++ b/framework/src/test/resources/soliditycode/BlockHash.sol @@ -0,0 +1,38 @@ +contract TestBlockHash { + + function testOR1(bytes32 value) public returns(bytes32, bytes32, bytes32) { + bytes32 b1 = blockhash(block.number - 1); + bytes32 c = blockhash(block.number - 1) | bytes32(value); + return (b1, c, blockhash(block.number - 1)); + } + + function testOR2(bytes32 value) public returns(bytes32, bytes32, bytes32) { + bytes32 b1 = blockhash(block.number - 1); + bytes32 c = bytes32(value) | blockhash(block.number - 1); + return (b1, c, blockhash(block.number - 1)); + } + + function testAND1(bytes32 value) public returns(bytes32, bytes32, bytes32) { + bytes32 b1 = blockhash(block.number - 1); + bytes32 c = blockhash(block.number - 1) & bytes32(value); + return (b1, c, blockhash(block.number - 1)); + } + + function testAND2(bytes32 value) public returns(bytes32, bytes32, bytes32) { + bytes32 b1 = blockhash(block.number - 1); + bytes32 c = bytes32(value) & blockhash(block.number - 1); + return (b1, c, blockhash(block.number - 1)); + } + + function testXOR1(bytes32 value) public returns(bytes32, bytes32, bytes32) { + bytes32 b1 = blockhash(block.number - 1); + bytes32 c = blockhash(block.number - 1) ^ bytes32(value); + return (b1, c, blockhash(block.number - 1)); + } + + function testXOR2(bytes32 value) public returns(bytes32, bytes32, bytes32) { + bytes32 b1 = blockhash(block.number - 1); + bytes32 c = bytes32(value) ^ blockhash(block.number - 1); + return (b1, c, blockhash(block.number - 1)); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/ClearAbi001.sol b/framework/src/test/resources/soliditycode/ClearAbi001.sol index fccc59e14be..39a8e8cf005 100644 --- a/framework/src/test/resources/soliditycode/ClearAbi001.sol +++ b/framework/src/test/resources/soliditycode/ClearAbi001.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract testConstantContract{ function testPayable() public view returns (int z) { diff --git a/framework/src/test/resources/soliditycode/Create2Test025.sol b/framework/src/test/resources/soliditycode/Create2Test025.sol index 87aef52b0c7..895dc43e56f 100644 --- a/framework/src/test/resources/soliditycode/Create2Test025.sol +++ b/framework/src/test/resources/soliditycode/Create2Test025.sol @@ -14,6 +14,13 @@ contract Factory { emit Deployed(addr, salt, msg.sender); return addr; } + + function get(bytes1 prefix, bytes calldata code, uint256 salt) external view returns(address) { + //bytes32 hash = keccak256(abi.encodePacked(bytes1(0x41),address(this), salt, keccak256(code))); + bytes32 hash = keccak256(abi.encodePacked(prefix,address(this), salt, keccak256(code))); + address addr = address(uint160(uint256(hash))); + return addr; + } } contract TestContract{ diff --git a/framework/src/test/resources/soliditycode/SafeMath.sol b/framework/src/test/resources/soliditycode/SafeMath.sol index b154b8b81b5..1a7f1be2b8e 100644 --- a/framework/src/test/resources/soliditycode/SafeMath.sol +++ b/framework/src/test/resources/soliditycode/SafeMath.sol @@ -1,4 +1,4 @@ -pragma solidity ^0.5.8; + /** * @dev Wrappers over Solidity's arithmetic operations with added overflow diff --git a/framework/src/test/resources/soliditycode/TestMappings_array_pop.sol b/framework/src/test/resources/soliditycode/TestMappings_array_pop.sol index 3ceac916049..0d5c4bb7013 100644 --- a/framework/src/test/resources/soliditycode/TestMappings_array_pop.sol +++ b/framework/src/test/resources/soliditycode/TestMappings_array_pop.sol @@ -2,7 +2,7 @@ contract C { mapping (uint256 => uint256)[] a; function n1(uint256 key, uint256 value) public { - a.length++; + a.push(); a[a.length - 1][key] = value; } diff --git a/framework/src/test/resources/soliditycode/TriggerConstant001.sol b/framework/src/test/resources/soliditycode/TriggerConstant001.sol index 515b9e07724..b385850577d 100644 --- a/framework/src/test/resources/soliditycode/TriggerConstant001.sol +++ b/framework/src/test/resources/soliditycode/TriggerConstant001.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract testConstantContract{ uint256 public i; diff --git a/framework/src/test/resources/soliditycode/TriggerConstant002.sol b/framework/src/test/resources/soliditycode/TriggerConstant002.sol index 44332e58c51..7708d81792a 100644 --- a/framework/src/test/resources/soliditycode/TriggerConstant002.sol +++ b/framework/src/test/resources/soliditycode/TriggerConstant002.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract testConstantContract{ uint256 public i; diff --git a/framework/src/test/resources/soliditycode/TriggerConstant003.sol b/framework/src/test/resources/soliditycode/TriggerConstant003.sol index 0bc41cc3751..947b3f610e6 100644 --- a/framework/src/test/resources/soliditycode/TriggerConstant003.sol +++ b/framework/src/test/resources/soliditycode/TriggerConstant003.sol @@ -1,12 +1,18 @@ -//pragma solidity ^0.4.0; + contract testConstantContract{ -function testView() public view returns (uint256 z) { -uint256 i=1; -return i; -} -function testPayable() public payable returns (uint256 z) { -uint256 i=1; -return i; -} + function testView() public view returns (uint256 z) { + uint256 i=1; + return i; + } + + function testPure() public pure returns (uint256 z) { + uint256 i=1; + return i; + } + + function testPayable() public payable returns (uint256 z) { + uint256 i=1; + return i; + } } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/TriggerConstant004.sol b/framework/src/test/resources/soliditycode/TriggerConstant004.sol index fce77178ca7..7fcb44950e7 100644 --- a/framework/src/test/resources/soliditycode/TriggerConstant004.sol +++ b/framework/src/test/resources/soliditycode/TriggerConstant004.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract testConstantContract{ function testPure() public pure returns (uint256 z) { diff --git a/framework/src/test/resources/soliditycode/TriggerConstant024.sol b/framework/src/test/resources/soliditycode/TriggerConstant024.sol index 287b0fc9782..69ad3a2d5b5 100644 --- a/framework/src/test/resources/soliditycode/TriggerConstant024.sol +++ b/framework/src/test/resources/soliditycode/TriggerConstant024.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract testConstantContract{ function testView() public view returns (uint256 z) { diff --git a/framework/src/test/resources/soliditycode/TvmNewCommand103.sol b/framework/src/test/resources/soliditycode/TvmNewCommand103.sol index 7ad130c87c6..dbc7fd0f0f4 100644 --- a/framework/src/test/resources/soliditycode/TvmNewCommand103.sol +++ b/framework/src/test/resources/soliditycode/TvmNewCommand103.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract testConstantContract{ function testView() public constant returns (uint256 z) { diff --git a/framework/src/test/resources/soliditycode/TvmNewCommand107.sol b/framework/src/test/resources/soliditycode/TvmNewCommand107.sol index 4dcd33ad7b0..5b51cd1842c 100644 --- a/framework/src/test/resources/soliditycode/TvmNewCommand107.sol +++ b/framework/src/test/resources/soliditycode/TvmNewCommand107.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract testConstantContract{ int256 public i; diff --git a/framework/src/test/resources/soliditycode/TvmNewCommand108.sol b/framework/src/test/resources/soliditycode/TvmNewCommand108.sol index b44d5c82731..0088054faf9 100644 --- a/framework/src/test/resources/soliditycode/TvmNewCommand108.sol +++ b/framework/src/test/resources/soliditycode/TvmNewCommand108.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract testConstantContract{ function test() pure public returns (int z) { diff --git a/framework/src/test/resources/soliditycode/TvmNewCommand109.sol b/framework/src/test/resources/soliditycode/TvmNewCommand109.sol index 864f01f7fb4..dc8dd1e8399 100644 --- a/framework/src/test/resources/soliditycode/TvmNewCommand109.sol +++ b/framework/src/test/resources/soliditycode/TvmNewCommand109.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract testConstantContract{ function test() view public returns (int z) { diff --git a/framework/src/test/resources/soliditycode/TvmOldCommand001.sol b/framework/src/test/resources/soliditycode/TvmOldCommand001.sol index 9f3cf079ea1..1ee046babe0 100644 --- a/framework/src/test/resources/soliditycode/TvmOldCommand001.sol +++ b/framework/src/test/resources/soliditycode/TvmOldCommand001.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract binaryRightContract{ function binaryMoveR(int i)public returns (int z) { diff --git a/framework/src/test/resources/soliditycode/abstract001.sol b/framework/src/test/resources/soliditycode/abstract001.sol new file mode 100644 index 00000000000..56bdc38eef4 --- /dev/null +++ b/framework/src/test/resources/soliditycode/abstract001.sol @@ -0,0 +1,11 @@ +pragma solidity ^0.6.0; + +interface X { + function setValue(uint _x) external; + function setBalance(uint _x) external; +} + +abstract contract abstract001 is X { + uint x; + function setX(uint _x) public { x = _x; } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/abstract002.sol b/framework/src/test/resources/soliditycode/abstract002.sol new file mode 100644 index 00000000000..98bcf879f60 --- /dev/null +++ b/framework/src/test/resources/soliditycode/abstract002.sol @@ -0,0 +1,13 @@ +pragma solidity ^0.6.0; + +interface X { + function setValue(uint _x) external; + function setBalance(uint _x) external; +} + +abstract contract abstract002 is X { + uint x; + function setX(uint _x) public { x = _x; } + function setValue(uint _x) external override{ x = _x; } + function setBalance(uint _x) external override{ x = _x; } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/addMsg001Nonpayable.sol b/framework/src/test/resources/soliditycode/addMsg001Nonpayable.sol index d1294f2336a..fcd40cdb521 100644 --- a/framework/src/test/resources/soliditycode/addMsg001Nonpayable.sol +++ b/framework/src/test/resources/soliditycode/addMsg001Nonpayable.sol @@ -1,11 +1,11 @@ -//pragma solidity ^0.4.24; + contract IllegalDecorate { event log(uint256); constructor() payable public{} -function() payable external{} +fallback() payable external{} function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue)public { // function transferTokenWithValue(address toAddress, uint256 tokenValue) payable public { diff --git a/framework/src/test/resources/soliditycode/addMsg002View.sol b/framework/src/test/resources/soliditycode/addMsg002View.sol index 423bb68e3ed..0c04b5c0b8a 100644 --- a/framework/src/test/resources/soliditycode/addMsg002View.sol +++ b/framework/src/test/resources/soliditycode/addMsg002View.sol @@ -1,10 +1,10 @@ -//pragma solidity ^0.4.24; + contract IllegalDecorate { constructor() payable public{} -function() payable external{} +fallback() payable external{} event log(uint256); diff --git a/framework/src/test/resources/soliditycode/addMsg003Constant.sol b/framework/src/test/resources/soliditycode/addMsg003Constant.sol index 0f0ab7553e0..2065802bed1 100644 --- a/framework/src/test/resources/soliditycode/addMsg003Constant.sol +++ b/framework/src/test/resources/soliditycode/addMsg003Constant.sol @@ -1,10 +1,10 @@ -//pragma solidity ^0.4.24; + contract IllegalDecorate { constructor() payable public{} -function() payable external{} +fallback() payable external{} event log(uint256); diff --git a/framework/src/test/resources/soliditycode/addMsg004Pure.sol b/framework/src/test/resources/soliditycode/addMsg004Pure.sol index b5d3a4e4aee..25f1a36d8b7 100644 --- a/framework/src/test/resources/soliditycode/addMsg004Pure.sol +++ b/framework/src/test/resources/soliditycode/addMsg004Pure.sol @@ -1,10 +1,10 @@ -//pragma solidity ^0.4.24; + contract IllegalDecorate { constructor() payable public{} -function() payable external{} +fallback() payable external{} event log(uint256); diff --git a/framework/src/test/resources/soliditycode/addTransferToken001Nonpayable.sol b/framework/src/test/resources/soliditycode/addTransferToken001Nonpayable.sol index c8d0dcc7560..039b341b6ac 100644 --- a/framework/src/test/resources/soliditycode/addTransferToken001Nonpayable.sol +++ b/framework/src/test/resources/soliditycode/addTransferToken001Nonpayable.sol @@ -1,10 +1,10 @@ -//pragma solidity ^0.4.24; + contract IllegalDecorate { constructor() payable public{} - function() payable external{} + fallback() payable external{} function transferTokenWithOutPayable(address payable toAddress,trcToken id, uint256 tokenValue)public { diff --git a/framework/src/test/resources/soliditycode/addTransferToken001payable.sol b/framework/src/test/resources/soliditycode/addTransferToken001payable.sol index 803d66ad75e..17078e30189 100644 --- a/framework/src/test/resources/soliditycode/addTransferToken001payable.sol +++ b/framework/src/test/resources/soliditycode/addTransferToken001payable.sol @@ -1,10 +1,10 @@ -//pragma solidity ^0.4.24; + contract IllegalDecorate { constructor() payable public{} - function() payable external{} + fallback() payable external{} function transferTokenWithOutPayable(address payable toAddress,trcToken id, uint256 tokenValue) public payable{ diff --git a/framework/src/test/resources/soliditycode/addTransferToken002View.sol b/framework/src/test/resources/soliditycode/addTransferToken002View.sol index 109f46386ce..c50a16390f5 100644 --- a/framework/src/test/resources/soliditycode/addTransferToken002View.sol +++ b/framework/src/test/resources/soliditycode/addTransferToken002View.sol @@ -1,10 +1,10 @@ -//pragma solidity ^0.4.24; + contract IllegalDecorate { constructor() payable public{} - function() payable external{} + fallback() payable external{} function transferTokenWithView(address payable toAddress,trcToken id, uint256 tokenValue) public view{ diff --git a/framework/src/test/resources/soliditycode/addTransferToken003Constant.sol b/framework/src/test/resources/soliditycode/addTransferToken003Constant.sol index fb1a2cbbbb4..18721d9b94c 100644 --- a/framework/src/test/resources/soliditycode/addTransferToken003Constant.sol +++ b/framework/src/test/resources/soliditycode/addTransferToken003Constant.sol @@ -1,10 +1,9 @@ -//pragma solidity ^0.4.24; contract IllegalDecorate { constructor() payable public{} - function() payable external{} + fallback() payable external{} function transferTokenWithConstant(address payable toAddress, uint256 tokenValue) public constant{ diff --git a/framework/src/test/resources/soliditycode/addTransferToken004Pure.sol b/framework/src/test/resources/soliditycode/addTransferToken004Pure.sol index 7ea2bf0a40b..f7716ee3874 100644 --- a/framework/src/test/resources/soliditycode/addTransferToken004Pure.sol +++ b/framework/src/test/resources/soliditycode/addTransferToken004Pure.sol @@ -1,10 +1,10 @@ -//pragma solidity ^0.4.24; + contract IllegalDecorate { constructor() payable public{} - function() payable external{} + fallback() payable external{} function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public pure{ diff --git a/framework/src/test/resources/soliditycode/addTrcToken001Assemble.sol b/framework/src/test/resources/soliditycode/addTrcToken001Assemble.sol index a93d9046a3f..fe7a7f4cef8 100644 --- a/framework/src/test/resources/soliditycode/addTrcToken001Assemble.sol +++ b/framework/src/test/resources/soliditycode/addTrcToken001Assemble.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract InAssemble { diff --git a/framework/src/test/resources/soliditycode/addTrcToken002Cat.sol b/framework/src/test/resources/soliditycode/addTrcToken002Cat.sol index 6d9c169330d..0cd407079ba 100644 --- a/framework/src/test/resources/soliditycode/addTrcToken002Cat.sol +++ b/framework/src/test/resources/soliditycode/addTrcToken002Cat.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.11; + /** @@ -1287,7 +1287,7 @@ contract KittyCore is KittyMinting { /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) - function() external payable { + fallback() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) diff --git a/framework/src/test/resources/soliditycode/addTrcToken002Cat_withFinny.sol b/framework/src/test/resources/soliditycode/addTrcToken002Cat_withFinny.sol index 2acebceddda..24117bc5e6b 100644 --- a/framework/src/test/resources/soliditycode/addTrcToken002Cat_withFinny.sol +++ b/framework/src/test/resources/soliditycode/addTrcToken002Cat_withFinny.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.11; + /** @@ -1287,7 +1287,7 @@ contract KittyCore is KittyMinting { /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) - function() external payable { + fallback() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) diff --git a/framework/src/test/resources/soliditycode/altbn.sol b/framework/src/test/resources/soliditycode/altbn.sol new file mode 100644 index 00000000000..c3cfcdbe2b9 --- /dev/null +++ b/framework/src/test/resources/soliditycode/altbn.sol @@ -0,0 +1,61 @@ +contract AltBn128 { + constructor() public payable {} + function callBn256Add(bytes32 ax, bytes32 ay, bytes32 bx, bytes32 by) public returns (bytes32[2] memory result) { + bytes32[4] memory input; + input[0] = ax; + input[1] = ay; + input[2] = bx; + input[3] = by; + assembly { + let success := call(gas(), 0x06, 0, input, 0x80, result, 0x40) + } + + } + + function callBn256AddNoValue(bytes32 ax, bytes32 ay, bytes32 bx, bytes32 by) public returns + (bytes32[2] memory result) { + bytes32[4] memory input; + input[0] = ax; + input[1] = ay; + input[2] = bx; + input[3] = by; + assembly { + let success := call(gas(), 0xac, 0, input, 0x80, result, 0x40) + } + } + + function callBn256ScalarMul(bytes32 x, bytes32 y, bytes32 scalar) public returns (bytes32[2] memory result) { + bytes32[3] memory input; + input[0] = x; + input[1] = y; + input[2] = scalar; + assembly { + let success := call(gas(), 0x07, 0, input, 0x60, result, 0x40) + switch success + case 0 { + revert(0,0) + } + } + } + + function callBn256Pairing(bytes memory input) public returns (bytes32 result) { + // input is a serialized bytes stream of (a1, b1, a2, b2, ..., ak, bk) from (G_1 x G_2)^k + uint256 len = input.length; + require(len % 192 == 0); + assembly { + let memPtr := mload(0x40) + let success := call(gas(), 0x08, 0, add(input, 0x20), len, memPtr, 0x20) + switch success + case 0 { + revert(0,0) + } default { + result := mload(memPtr) + } + } + } + + function convert(uint256 num) public view returns(bytes32) { + return bytes32(num); + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/arrayLength001.sol b/framework/src/test/resources/soliditycode/arrayLength001.sol new file mode 100644 index 00000000000..46b2405a97e --- /dev/null +++ b/framework/src/test/resources/soliditycode/arrayLength001.sol @@ -0,0 +1,64 @@ + + +contract arrayLength { + byte[] a; + uint256[] IntergerArray; + bytes bs; + + // arrary length + function arrayPushValue() public returns (byte[] memory){ + a = new byte[](1); + a.push(0x01); + return a; + } + + function arrayPush() public returns(byte[] memory){ + a = new byte[](1); + a.push(); + return a; + } + + function arrayPop() public returns(byte[] memory){ + a = new byte[](1); + a.pop(); + return a; + } + + // arrary push/pop return Value + function arrayPushValueReturn() public { + a = new byte[](1); + return a.push(0x01); + } + + function arrayPushReturn() public returns (bytes1){ + a = new byte[](1); + return a.push(); + } + + function arrayPopReturn() public{ + a = new byte[](1); + return a.pop(); + } + + function uint256ArrayPushValue() public returns (byte[] memory){ + IntergerArray = [1,2,3]; + IntergerArray.push(); + return a; + } + + + // bytes + function bytesPushValue() public { + + return bs.push(0x01); + } + + function bytesPush() public returns (bytes1){ + return bs.push(); + } + + function bytesPop() public { + return bs.pop(); + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/assemblyTest.sol b/framework/src/test/resources/soliditycode/assemblyTest.sol new file mode 100644 index 00000000000..519a5a85fa3 --- /dev/null +++ b/framework/src/test/resources/soliditycode/assemblyTest.sol @@ -0,0 +1,61 @@ + +contract assemblyTest { + + uint constant x = 1; + uint constant y = x; + function getZuint() public view returns (uint) { + uint z = y + 1; + assembly { + z := y + } + return z; + } + + function getZuint2() public returns (uint) { + uint z = y + 1; + assembly { + z := y + } + return z; + } + + bool constant bool1 = true; + bool constant bool2 = bool1; + function getZbool() public view returns (bool) { + bool z; + assembly { + z := bool2 + } + return z; + } + + function getZbool2() public returns (bool) { + bool z; + assembly { + z := bool2 + } + return z; + } + + +// string constant string1 = "abc"; +// string constant string2 = string1; +// function getZstring() public view returns (string memory) { +// string memory z; +// assembly { +// z := string2 +// } +// return z; +// } + + +// address origin1 = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; +// address origin2 = origin1; +// function getZaddress() public view returns (address) { +// address z; +// assembly { +// z := origin2 +// } +// return z; +// } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/assertExceptiontest1DivideInt.sol b/framework/src/test/resources/soliditycode/assertExceptiontest1DivideInt.sol index ca38896acee..92778e42bc9 100644 --- a/framework/src/test/resources/soliditycode/assertExceptiontest1DivideInt.sol +++ b/framework/src/test/resources/soliditycode/assertExceptiontest1DivideInt.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract divideIHaveArgsReturnStorage{ function divideIHaveArgsReturn(int x,int y) public returns (int z) { diff --git a/framework/src/test/resources/soliditycode/assertExceptiontest2FindArgsContractMinTest.sol b/framework/src/test/resources/soliditycode/assertExceptiontest2FindArgsContractMinTest.sol index b8565d2578e..75436287805 100644 --- a/framework/src/test/resources/soliditycode/assertExceptiontest2FindArgsContractMinTest.sol +++ b/framework/src/test/resources/soliditycode/assertExceptiontest2FindArgsContractMinTest.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract findArgsIContract{ function findArgsByIndex1(uint i) public returns (uint z) { uint[] memory a = new uint[](3); diff --git a/framework/src/test/resources/soliditycode/assertExceptiontest3ByteMinContract.sol b/framework/src/test/resources/soliditycode/assertExceptiontest3ByteMinContract.sol index 6d846fad7f4..c8a2e5e363b 100644 --- a/framework/src/test/resources/soliditycode/assertExceptiontest3ByteMinContract.sol +++ b/framework/src/test/resources/soliditycode/assertExceptiontest3ByteMinContract.sol @@ -1,4 +1,4 @@ -pragma solidity >0.5.0; + contract byteContract{ bytes b; function testBytesGet(uint i) public returns (bytes1){ diff --git a/framework/src/test/resources/soliditycode/assertExceptiontest4Enum.sol b/framework/src/test/resources/soliditycode/assertExceptiontest4Enum.sol index 4a740d4a089..6bd2ade2eea 100644 --- a/framework/src/test/resources/soliditycode/assertExceptiontest4Enum.sol +++ b/framework/src/test/resources/soliditycode/assertExceptiontest4Enum.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.4; + contract enumContract { enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } diff --git a/framework/src/test/resources/soliditycode/assertExceptiontest5MoveRight.sol b/framework/src/test/resources/soliditycode/assertExceptiontest5MoveRight.sol index 7194520fb09..b83168d5ddc 100644 --- a/framework/src/test/resources/soliditycode/assertExceptiontest5MoveRight.sol +++ b/framework/src/test/resources/soliditycode/assertExceptiontest5MoveRight.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract binaryRightContract{ function binaryMoveR(int i)public returns (int z) { diff --git a/framework/src/test/resources/soliditycode/assertExceptiontest6UninitializedContract.sol b/framework/src/test/resources/soliditycode/assertExceptiontest6UninitializedContract.sol index 1ff2215abdb..c82e0f5806c 100644 --- a/framework/src/test/resources/soliditycode/assertExceptiontest6UninitializedContract.sol +++ b/framework/src/test/resources/soliditycode/assertExceptiontest6UninitializedContract.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract uni { function b(int x, int y) internal returns (int) { diff --git a/framework/src/test/resources/soliditycode/assertExceptiontest7TestAssertContract.sol b/framework/src/test/resources/soliditycode/assertExceptiontest7TestAssertContract.sol index 0bfd6fbd04e..05b592e0682 100644 --- a/framework/src/test/resources/soliditycode/assertExceptiontest7TestAssertContract.sol +++ b/framework/src/test/resources/soliditycode/assertExceptiontest7TestAssertContract.sol @@ -1,4 +1,3 @@ -pragma solidity >0.5.0; contract TestThrowsContract{ function testAssert() public{ assert(1==2); diff --git a/framework/src/test/resources/soliditycode/callvalue.sol b/framework/src/test/resources/soliditycode/callvalue.sol index ee2a30342c5..f01dcf2b52f 100644 --- a/framework/src/test/resources/soliditycode/callvalue.sol +++ b/framework/src/test/resources/soliditycode/callvalue.sol @@ -2,7 +2,7 @@ contract Callvalue { function check() public payable returns(uint) { uint256 wad; assembly { - wad := callvalue + wad := callvalue() } return wad; } diff --git a/framework/src/test/resources/soliditycode/chainid001.sol b/framework/src/test/resources/soliditycode/chainid001.sol new file mode 100644 index 00000000000..9cf24077dfb --- /dev/null +++ b/framework/src/test/resources/soliditycode/chainid001.sol @@ -0,0 +1,19 @@ + +contract IstanbulTest { + constructor() public payable {} + function getId() public view returns(uint256){ + uint256 id; + assembly { + id := chainid() + } + return id; + } + + function getBalance(address src) public view returns(uint256){ + return address(src).balance; + } + + function getBalance() public view returns(uint256){ + return address(this).balance; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/codeSaftySupport.sol b/framework/src/test/resources/soliditycode/codeSaftySupport.sol index 45a4beee384..1cee8e4646c 100644 --- a/framework/src/test/resources/soliditycode/codeSaftySupport.sol +++ b/framework/src/test/resources/soliditycode/codeSaftySupport.sol @@ -1,10 +1,10 @@ -//pragma solidity ^0.4.24; + contract IllegalDecorate { constructor() payable public{} -function() payable external{} +fallback() payable external{} event log(uint256); diff --git a/framework/src/test/resources/soliditycode/codeSaftyUnsupport.sol b/framework/src/test/resources/soliditycode/codeSaftyUnsupport.sol index 220d66b2257..d448f49d706 100644 --- a/framework/src/test/resources/soliditycode/codeSaftyUnsupport.sol +++ b/framework/src/test/resources/soliditycode/codeSaftyUnsupport.sol @@ -1,10 +1,10 @@ -//pragma solidity ^0.4.24; + contract SubC { event log(string); -function () payable external{} +fallback() payable external{} function receiveToken() payable public{} @@ -15,7 +15,7 @@ r = address(this).balance; contract UseDot { constructor() payable public{} -function() payable external{} +fallback() payable external{} mapping(address => mapping(trcToken => uint256)) sender_tokens; function trigger1(address payable addr, trcToken tokenInputId) payable public { diff --git a/framework/src/test/resources/soliditycode/constantContract001.sol b/framework/src/test/resources/soliditycode/constantContract001.sol index ab97b450235..7d574c5a008 100644 --- a/framework/src/test/resources/soliditycode/constantContract001.sol +++ b/framework/src/test/resources/soliditycode/constantContract001.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract testConstantContract{ function testPure(uint256 x,uint256 y) public pure returns (uint256 z) { diff --git a/framework/src/test/resources/soliditycode/contractGetterContract.sol b/framework/src/test/resources/soliditycode/contractGetterContract.sol index ba090f061dd..365b53ebf1a 100644 --- a/framework/src/test/resources/soliditycode/contractGetterContract.sol +++ b/framework/src/test/resources/soliditycode/contractGetterContract.sol @@ -1,10 +1,10 @@ -//pragma solidity ^0.4.0; + contract getterContract { constructor() public payable{} -function() external payable{} +fallback() external payable{} uint public c = msg.value; diff --git a/framework/src/test/resources/soliditycode/contractGrammar001test1Grammar001.sol b/framework/src/test/resources/soliditycode/contractGrammar001test1Grammar001.sol index 1d0ad6e3d3f..659e56c9150 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar001test1Grammar001.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar001test1Grammar001.sol @@ -1,4 +1,4 @@ -pragma solidity >0.5.0; + contract FunctionSelector { function select(bool useB, uint x) public returns (uint z) { //var f = a; diff --git a/framework/src/test/resources/soliditycode/contractGrammar001test2Grammar002.sol b/framework/src/test/resources/soliditycode/contractGrammar001test2Grammar002.sol index df9d5c88839..744b17e9585 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar001test2Grammar002.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar001test2Grammar002.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.16; + library Set { // We define a new struct datatype that will be used to // hold its data in the calling contract. diff --git a/framework/src/test/resources/soliditycode/contractGrammar001test3Grammar003.sol b/framework/src/test/resources/soliditycode/contractGrammar001test3Grammar003.sol index ce56f5c9912..140ba2a8f56 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar001test3Grammar003.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar001test3Grammar003.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.11; + library Set { struct Data { mapping(uint => bool) flags; } diff --git a/framework/src/test/resources/soliditycode/contractGrammar001test4Grammar004.sol b/framework/src/test/resources/soliditycode/contractGrammar001test4Grammar004.sol index b36d171a912..772691cebc5 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar001test4Grammar004.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar001test4Grammar004.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + library Search { function indexOf(uint[] storage self, uint value) public returns (uint) { diff --git a/framework/src/test/resources/soliditycode/contractGrammar001test5Grammar006.sol b/framework/src/test/resources/soliditycode/contractGrammar001test5Grammar006.sol index 805476a9e4a..9b2c906698b 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar001test5Grammar006.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar001test5Grammar006.sol @@ -1,4 +1,3 @@ -// pragma solidity ^0.4.0; contract InfoFeed { function d1(uint x) public{ assembly{ @@ -12,10 +11,15 @@ function d1(uint x) public{ assembly { x := sub(x, 1) } } - function d(uint x) public{ + // 0.6.0 Variable declarations cannot shadow declarations outside the assembly block. + function d(uint x1) public returns(uint256){ + uint256 x; assembly{ - let x := add(2, 3) let y := mload(0x40) x := add(x, y) + x := add(2, 3) + let y := mload(0x40) + x := add(x, y) } + return x; } function d4(uint x) public{ // Error: The labels 'repeat' is disallowed. Please use "if", "switch", "for" or function calls instead diff --git a/framework/src/test/resources/soliditycode/contractGrammar002test1Grammar007_1.sol b/framework/src/test/resources/soliditycode/contractGrammar002test1Grammar007_1.sol index 6e3ac0bfd1e..020c2a38ca4 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar002test1Grammar007_1.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar002test1Grammar007_1.sol @@ -1,24 +1,24 @@ -//pragma solidity ^0.4.19; contract Doug{ mapping (bytes32 => uint) public contracts; constructor() public{ - contracts['hww'] = 1; - contracts['brian'] = 2; - contracts['zzy'] = 7; + contracts['hww'] = 1; + contracts['brian'] = 2; + contracts['zzy'] = 7; } function getDougName(string memory _name) public view returns(string memory) { - return _name; + return _name; } function getDougAge(uint _age) public pure returns(uint) { - return 3 ** _age; + return 3 ** _age; } } -contract DogInterface { - function getDougAge(uint _age) public returns (uint); - function contracts(bytes32 name) public returns (uint); +// +abstract contract DogInterface { + function getDougAge(uint _age) public virtual returns (uint); + function contracts(bytes32 name) public virtual returns (uint); } contract main{ @@ -30,25 +30,25 @@ contract main{ DogInterface dogContract ; function setDOUG(address _doug) public { - DOUG = _doug; + DOUG = _doug; } constructor(address addr) public{ - dogInterfaceAddress = addr; - dogContract = DogInterface(dogInterfaceAddress); + dogInterfaceAddress = addr; + dogContract = DogInterface(dogInterfaceAddress); } function dougOfage(uint _age) public returns(uint) { - uint num = dogContract.getDougAge(_age); - return _age+num; - // return num; + uint num = dogContract.getDougAge(_age); + return _age+num; + // return num; } function uintOfName(bytes32 _name) public returns (uint) { - dogContract.contracts(_name); - emit FetchContract(dogInterfaceAddress, msg.sender, _name); + dogContract.contracts(_name); + emit FetchContract(dogInterfaceAddress, msg.sender, _name); } diff --git a/framework/src/test/resources/soliditycode/contractGrammar002test1Grammar007_2.sol b/framework/src/test/resources/soliditycode/contractGrammar002test1Grammar007_2.sol index 6e3ac0bfd1e..8945b566543 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar002test1Grammar007_2.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar002test1Grammar007_2.sol @@ -1,24 +1,24 @@ -//pragma solidity ^0.4.19; + contract Doug{ mapping (bytes32 => uint) public contracts; constructor() public{ - contracts['hww'] = 1; - contracts['brian'] = 2; - contracts['zzy'] = 7; + contracts['hww'] = 1; + contracts['brian'] = 2; + contracts['zzy'] = 7; } function getDougName(string memory _name) public view returns(string memory) { - return _name; + return _name; } function getDougAge(uint _age) public pure returns(uint) { - return 3 ** _age; + return 3 ** _age; } } -contract DogInterface { - function getDougAge(uint _age) public returns (uint); - function contracts(bytes32 name) public returns (uint); +abstract contract DogInterface { + function getDougAge(uint _age) public virtual returns (uint); + function contracts(bytes32 name) public virtual returns (uint); } contract main{ @@ -30,25 +30,25 @@ contract main{ DogInterface dogContract ; function setDOUG(address _doug) public { - DOUG = _doug; + DOUG = _doug; } constructor(address addr) public{ - dogInterfaceAddress = addr; - dogContract = DogInterface(dogInterfaceAddress); + dogInterfaceAddress = addr; + dogContract = DogInterface(dogInterfaceAddress); } function dougOfage(uint _age) public returns(uint) { - uint num = dogContract.getDougAge(_age); - return _age+num; - // return num; + uint num = dogContract.getDougAge(_age); + return _age+num; + // return num; } function uintOfName(bytes32 _name) public returns (uint) { - dogContract.contracts(_name); - emit FetchContract(dogInterfaceAddress, msg.sender, _name); + dogContract.contracts(_name); + emit FetchContract(dogInterfaceAddress, msg.sender, _name); } diff --git a/framework/src/test/resources/soliditycode/contractGrammar002test2Grammar008.sol b/framework/src/test/resources/soliditycode/contractGrammar002test2Grammar008.sol index c9c5d614d2d..956623c3103 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar002test2Grammar008.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar002test2Grammar008.sol @@ -1,14 +1,18 @@ -//pragma solidity ^0.4.19; -contract Feline { - function utterance() public returns (bytes32); + + +// version 0.6.0 change +// add abstract and override +abstract contract Feline { + + function utterance() public virtual returns (bytes32); function getContractName() public returns (string memory){ - return "Feline"; + return "Feline"; } } contract Cat is Feline { - function utterance() public returns (bytes32) { return "miaow"; } + function utterance() public override returns (bytes32) { return "miaow"; } } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar002test3Grammar010.sol b/framework/src/test/resources/soliditycode/contractGrammar002test3Grammar010.sol index a7749dfcc71..d6845d2e336 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar002test3Grammar010.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar002test3Grammar010.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract InfoFeed { function info() public payable returns (uint ret) { return 42; } } diff --git a/framework/src/test/resources/soliditycode/contractGrammar002test4Grammar011.sol b/framework/src/test/resources/soliditycode/contractGrammar002test4Grammar011.sol index 921b52a6080..fcd18f438ef 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar002test4Grammar011.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar002test4Grammar011.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract C { function f(uint key, uint value) public returns(uint) { return key; diff --git a/framework/src/test/resources/soliditycode/contractGrammar002test4Grammar012.sol b/framework/src/test/resources/soliditycode/contractGrammar002test4Grammar012.sol index 45e6d3aaf6e..8fb3c750298 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar002test4Grammar012.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar002test4Grammar012.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract rTest { function info() public payable returns (uint,address,bytes4,uint,uint,uint,address,uint) { //function info() public payable returns (address ,uint,uint,uint,bytes32,uint,bytes,uint,address,bytes4,uint,uint,uint,address,uint) { diff --git a/framework/src/test/resources/soliditycode/contractGrammar002test6Grammar013.sol b/framework/src/test/resources/soliditycode/contractGrammar002test6Grammar013.sol index 56f97191ea0..53de5def6bc 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar002test6Grammar013.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar002test6Grammar013.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.4; + contract Counter { uint count = 0; address payable owner; diff --git a/framework/src/test/resources/soliditycode/contractGrammar003test1Grammar014.sol b/framework/src/test/resources/soliditycode/contractGrammar003test1Grammar014.sol index 9190e902056..b2d70b3741c 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar003test1Grammar014.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar003test1Grammar014.sol @@ -1,4 +1,3 @@ -//pragma solidity ^0.4.4; contract A { uint256 public numberForB; address public senderForB; diff --git a/framework/src/test/resources/soliditycode/contractGrammar003test2Grammar015.sol b/framework/src/test/resources/soliditycode/contractGrammar003test2Grammar015.sol index 51aa0843890..0aa93e5e94f 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar003test2Grammar015.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar003test2Grammar015.sol @@ -1,11 +1,12 @@ -//pragma solidity ^0.4.0; + contract ExecuteFallback{ //回退事件,会把调用的数据打印出来 event FallbackCalled(bytes data); //fallback函数,注意是没有名字的,没有参数,没有返回值的 - function() external{ + // 0.6.0 Split unnamed fallback functions into two cases defined using fallback() and receive() + fallback() external{ emit FallbackCalled(msg.data); } diff --git a/framework/src/test/resources/soliditycode/contractGrammar003test3Grammar016.sol b/framework/src/test/resources/soliditycode/contractGrammar003test3Grammar016.sol index 11eb8f9cc70..6a73d7a8d7e 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar003test3Grammar016.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar003test3Grammar016.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract C { uint private data; function f(uint a) private returns(uint b) { return a + 1; } diff --git a/framework/src/test/resources/soliditycode/contractGrammar003test4Grammar017.sol b/framework/src/test/resources/soliditycode/contractGrammar003test4Grammar017.sol index 23fcdec76f0..fb81b6e529c 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar003test4Grammar017.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar003test4Grammar017.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract CrowdFunding{ struct Funder{ address addr; diff --git a/framework/src/test/resources/soliditycode/contractGrammar003test5Grammar018.sol b/framework/src/test/resources/soliditycode/contractGrammar003test5Grammar018.sol index ddd6deb040f..ec241f3eae9 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar003test5Grammar018.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar003test5Grammar018.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract Grammar18{ diff --git a/framework/src/test/resources/soliditycode/contractGrammar003test6Grammar019.sol b/framework/src/test/resources/soliditycode/contractGrammar003test6Grammar019.sol index 30418539865..727ef7091e7 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar003test6Grammar019.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar003test6Grammar019.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract timetest { constructor() public { diff --git a/framework/src/test/resources/soliditycode/contractGrammar003test7Grammar020.sol b/framework/src/test/resources/soliditycode/contractGrammar003test7Grammar020.sol index 1b960e6e313..39a7fddcb7e 100644 --- a/framework/src/test/resources/soliditycode/contractGrammar003test7Grammar020.sol +++ b/framework/src/test/resources/soliditycode/contractGrammar003test7Grammar020.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract trxtest { function test() public { diff --git a/framework/src/test/resources/soliditycode/contractInnerContract.sol b/framework/src/test/resources/soliditycode/contractInnerContract.sol index bc183931c88..0de68bbf7da 100644 --- a/framework/src/test/resources/soliditycode/contractInnerContract.sol +++ b/framework/src/test/resources/soliditycode/contractInnerContract.sol @@ -1,11 +1,11 @@ -//pragma solidity ^0.4.0; + contract InnerContract { constructor() public payable{} - function() external payable{} + fallback() external payable{} function messageI() payable public returns (uint ret) { @@ -21,7 +21,7 @@ contract OuterContract { constructor() public payable{} - function() external payable{} + fallback() external payable{} function callInner(address payable addr) payable public returns (uint) { diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction001.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction001.sol index 8baba262e87..02fa51949c3 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction001.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction001.sol @@ -1,12 +1,11 @@ -//pragma solidity ^0.4.24; contract A{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function test1(address payable cAddr) public payable{ B b1 = (new B).value(10)();//1.1 B b2 = new B();//1.2 - address(b2).transfer(5);//1.3 + payable(address(b2)).transfer(5);//1.3 b2.callCGetZero(cAddr, 1);//1.4 b2.callCGetZero(cAddr,2);//1.6 } @@ -18,7 +17,7 @@ contract A{ contract B{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getOne() payable public returns(uint256){ return 1; } @@ -29,7 +28,7 @@ contract B{ contract C{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getZero() payable public returns(uint256){ return 0; } diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction002.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction002.sol index 42231b7c960..92edfeb1157 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction002.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction002.sol @@ -1,8 +1,7 @@ -//pragma solidity ^0.4.24; contract A{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function test2(address cAddress,uint256 amount) public payable{ //cAddress.call.value(amount)();//2.1 @@ -13,7 +12,7 @@ contract A{ contract C{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getZero() payable public returns(uint256){ return 0; } diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction003.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction003.sol index 0910a0c4a2b..2e17d6dbc02 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction003.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction003.sol @@ -1,4 +1,3 @@ -//pragma solidity ^0.4.24; contract A{ uint256 public num = 0; @@ -26,6 +25,6 @@ function getBalance() public returns(uint256){ return address(this).balance; } - function () payable external{} + fallback() payable external{} } diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction004.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction004.sol index c7866dddb58..e8f32d7bfd9 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction004.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction004.sol @@ -1,23 +1,22 @@ -//pragma solidity ^0.4.24; contract A{ constructor () payable public{} function test(address payable toAddress) public payable{ selfdestruct(toAddress); } - function () payable external{} + fallback() payable external{} function getBalance() public view returns(uint256){ return address(this).balance; } } contract B{ - function() external payable{} + fallback() external payable{} function kill(address contractAddres, address toAddress) payable public { contractAddres.call(abi.encodeWithSignature("test(address)",address(this))); } function kill2() public{ A a = new A(); - a.test(address(this)); + a.test(payable(address(this))); } function getBalance() public view returns(uint256){ return address(this).balance; diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction005.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction005.sol index 6e83c423b38..b198d260e4d 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction005.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction005.sol @@ -1,8 +1,7 @@ -//pragma solidity ^0.4.24; contract A{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function test1() public payable{ B b1 = (new B).value(10)();//1.1 b1.callCGetZero(false); @@ -21,7 +20,7 @@ contract A{ contract B{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getOne() payable public returns(uint256){ return 1; } @@ -38,14 +37,14 @@ contract B{ contract C{ uint256 public flag=0; constructor() payable public{} - function() payable external{} + fallback() payable external{} function getZero() payable public returns(uint256){ return 0; } function newBAndTransfer(bool success) payable public returns(uint256){ flag = 1; if(!success){ - require(2==1); + require(2==1); } } function getFlag() public returns(uint256){ diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction006.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction006.sol index 6bc548690a5..ca51fda2021 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction006.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction006.sol @@ -1,8 +1,8 @@ -//pragma solidity ^0.4.24; + contract A{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function test1() public payable{ B b1 = (new B).value(10)();//1.1 b1.callCGetZero(true);//1.4 @@ -21,7 +21,7 @@ contract A{ contract B{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getOne() payable public returns(uint256){ return 1; } @@ -38,7 +38,7 @@ contract B{ contract C{ uint256 public flag=0; constructor() payable public{} - function() payable external{} + fallback() payable external{} function getZero() payable public returns(uint256){ return 0; } diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction002test1InternalTransaction007.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction002test1InternalTransaction007.sol index 229bf82fa2d..528fb9fa8a8 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction002test1InternalTransaction007.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction002test1InternalTransaction007.sol @@ -1,12 +1,12 @@ -//pragma solidity ^0.4.24; + contract A{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function test1(address cAddr) public payable{ B b1 = (new B).value(10)();//1.1 B b2 = new B();//1.2 - address(b2).transfer(5);//1.3 + payable(address(b2)).transfer(5);//1.3 b2.callCGetZero();//1.4 } function test2(address cAddress,uint256 amount) public payable{ @@ -16,7 +16,7 @@ contract A{ contract B{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getOne() payable public returns(uint256){ return 1; } @@ -28,7 +28,7 @@ contract B{ contract C{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getZero() payable public returns(uint256){ return 0; } diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction002test2InternalTransaction008.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction002test2InternalTransaction008.sol index a75fba4f14b..c1e9ea0596f 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction002test2InternalTransaction008.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction002test2InternalTransaction008.sol @@ -1,8 +1,8 @@ -//pragma solidity ^0.4.24; + contract A{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function testAssert(address bAddress,uint256 amount) public payable{ bAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("callCGetZero(bool)",false));//2.1 @@ -27,7 +27,7 @@ contract A{ contract B{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getOne() payable public returns(uint256){ return 1; } @@ -44,7 +44,7 @@ contract B{ contract C{ uint256 public flag=0; constructor() payable public{} - function() payable external{} + fallback() payable external{} function getZero() payable public returns(uint256){ return 0; } diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction002test3InternalTransaction009.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction002test3InternalTransaction009.sol index 1a7df822511..7c8a1f8c879 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction002test3InternalTransaction009.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction002test3InternalTransaction009.sol @@ -1,11 +1,11 @@ -//pragma solidity ^0.4.24; + contract A{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function test1(address cAddr,address dcontract,address baddress) public payable{ B b1 = (new B).value(10)();//1.1 - address(b1).transfer(5);//1.3 + payable(address(b1)).transfer(5);//1.3 b1.callCGetZero(cAddr, 1);//1.4 b1.getOne(dcontract,baddress); } @@ -13,7 +13,7 @@ contract A{ contract B{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getOne(address contractAddres, address toAddress) payable public{ contractAddres.call(abi.encodeWithSignature("suicide1(address)",address(this))); @@ -25,7 +25,7 @@ contract B{ contract C{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getZero() payable public returns(uint256){ return 0; } @@ -40,7 +40,7 @@ contract D{ function suicide1(address payable toAddress) public payable{ selfdestruct(toAddress); } - function () payable external{} + fallback() payable external{} function getBalance() public view returns(uint256){ return address(this).balance; } diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction002test4InternalTransaction010.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction002test4InternalTransaction010.sol index 7f34b2bfe08..af2b54af172 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction002test4InternalTransaction010.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction002test4InternalTransaction010.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract A{ uint256 public num = 0; @@ -181,6 +181,6 @@ function getBalance() public returns(uint256){ return address(this).balance; } - function () payable external{} + fallback() payable external{} } diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction002test4InternalTransaction010_1.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction002test4InternalTransaction010_1.sol index c77fe76f5fa..d0c80d14ffb 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction002test4InternalTransaction010_1.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction002test4InternalTransaction010_1.sol @@ -1,4 +1,4 @@ -pragma solidity ^0.4.24; + contract A{ uint256 public num = 0; @@ -204,7 +204,7 @@ pragma solidity ^0.4.24; function getBalance() returns(uint256){ return this.balance; } - function () payable{} + fallback() payable{} } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction002test5InternalTransaction012.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction002test5InternalTransaction012.sol index ce2798888fe..e9bc38b58d4 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction002test5InternalTransaction012.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction002test5InternalTransaction012.sol @@ -1,8 +1,8 @@ -//pragma solidity ^0.4.24; + contract A{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function test1(address bAddr,address eAddr) public payable{ bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 } @@ -11,7 +11,7 @@ contract A{ contract B{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getOne() payable public returns(uint256){ return 1; } @@ -23,7 +23,7 @@ contract B{ contract C{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getZero() payable public returns(uint256){ return 0; } @@ -33,7 +33,7 @@ contract C{ } contract E{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getZero() payable public returns(uint256){ return 0; } @@ -43,7 +43,7 @@ contract E{ } contract D{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getOne(address eAddress) payable public returns(uint256){ eAddress.call.value(1)(abi.encodeWithSignature("getZero()"));//2.1 } diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction013.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction013.sol index bc1d3dbe6cd..3ef9264ee70 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction013.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction013.sol @@ -1,8 +1,8 @@ -//pragma solidity ^0.4.24; + contract A{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function test1(address dAddr) public payable{ B b1 = (new B).value(10)();//1.1 b1.testNN(dAddr,2);//1.6 @@ -16,7 +16,7 @@ contract A{ contract B{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getOne() payable public returns(uint256){ return 1; } @@ -28,7 +28,7 @@ contract B{ contract C{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getZero() payable public returns(uint256){ return 0; } @@ -38,7 +38,7 @@ contract C{ } contract E{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getZero() payable public returns(uint256){ return 0; } @@ -48,7 +48,7 @@ contract E{ } contract D{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getOne() payable public returns(uint256){ E e = (new E).value(5)(); } diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction014.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction014.sol index b3bbfc9a7db..5647048bab3 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction014.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction014.sol @@ -1,6 +1,6 @@ contract callerContract { constructor() payable public{} - function() payable external{} + fallback() payable external{} function sendToB(address called_address,address c) public payable{ called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); } @@ -13,7 +13,7 @@ contract callerContract { } contract calledContract { - function() payable external {} + fallback() payable external {} constructor() payable public{} function transferTo(address payable toAddress)public payable{ toAddress.transfer(5); @@ -34,5 +34,5 @@ contract callerContract { function setI() payable public{ i=5; } - function() payable external{} + fallback() payable external{} } diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction015.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction015.sol index 0426d650da4..229f79f3c96 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction015.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction015.sol @@ -1,8 +1,8 @@ -//pragma solidity ^0.4.24; + contract A{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function test1(address dAddr,address eAddr) public payable{ B b1 = (new B).value(10)();//1.1 b1.testNN(dAddr,2,eAddr);//1.6 @@ -16,7 +16,7 @@ contract A{ contract B{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getOne() payable public returns(uint256){ return 1; } @@ -28,7 +28,7 @@ contract B{ contract C{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getZero() payable public returns(uint256){ return 0; } @@ -38,7 +38,7 @@ contract C{ } contract E{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getZero() payable public returns(uint256){ return 0; } @@ -51,7 +51,7 @@ contract E{ } contract D{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getOne(address payable eAddress) payable public{ E e = (new E).value(5)(); e.suicide(eAddress); diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction016.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction016.sol index f97217fe169..f5cbdc2f1fa 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction016.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction016.sol @@ -1,9 +1,9 @@ -//pragma solidity ^0.4.24; + contract A{ uint256 public num = 0; constructor() public payable{} - function () payable external{} + fallback() payable external{} function transfer() payable public{ (new B).value(1)();//1 (new B).value(1)();//1 @@ -166,7 +166,7 @@ function getBalance() public returns(uint256){ return address(this).balance; } - function () payable external{} + fallback() payable external{} function suicide1(address payable toAddress) public payable{ selfdestruct(toAddress); } diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction017.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction017.sol index ebe570fd8af..6847eebc546 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction017.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction017.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract A{ uint256 public num = 0; @@ -194,6 +194,6 @@ function getBalance() public returns(uint256){ return address(this).balance; } - function () payable external{} + fallback() payable external{} } diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction018.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction018.sol index a59c587b233..80705ffd5e9 100644 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction018.sol +++ b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction018.sol @@ -1,8 +1,8 @@ -//pragma solidity ^0.4.24; + contract A{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function test1(address payable bAddr,address eAddr) public payable{ bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 @@ -57,7 +57,7 @@ contract A{ contract B{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getOne() payable public returns(uint256){ return 1; } @@ -69,7 +69,7 @@ contract B{ contract C{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getZero() payable public returns(uint256){ return 0; } @@ -79,7 +79,7 @@ contract C{ } contract E{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getZero() payable public returns(uint256){ return 0; } @@ -89,7 +89,7 @@ contract E{ } contract D{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function getOne(address eAddress) payable public returns(uint256){ eAddress.call.value(1)(abi.encodeWithSignature("getZero()"));//2.1 } diff --git a/framework/src/test/resources/soliditycode/contractLinkage001.sol b/framework/src/test/resources/soliditycode/contractLinkage001.sol index 4c04cf5c6fb..8d441fba2da 100644 --- a/framework/src/test/resources/soliditycode/contractLinkage001.sol +++ b/framework/src/test/resources/soliditycode/contractLinkage001.sol @@ -1,8 +1,8 @@ -//pragma solidity ^0.4.0; + contract divideIHaveArgsReturnStorage{ constructor() payable public{} -function() payable external{} +fallback() payable external{} function divideIHaveArgsReturn(int x,int y) public payable returns (int z) { return z = x / y; } diff --git a/framework/src/test/resources/soliditycode/contractLinkage002.sol b/framework/src/test/resources/soliditycode/contractLinkage002.sol index ca38896acee..92778e42bc9 100644 --- a/framework/src/test/resources/soliditycode/contractLinkage002.sol +++ b/framework/src/test/resources/soliditycode/contractLinkage002.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract divideIHaveArgsReturnStorage{ function divideIHaveArgsReturn(int x,int y) public returns (int z) { diff --git a/framework/src/test/resources/soliditycode/contractLinkage003.sol b/framework/src/test/resources/soliditycode/contractLinkage003.sol index ca38896acee..92778e42bc9 100644 --- a/framework/src/test/resources/soliditycode/contractLinkage003.sol +++ b/framework/src/test/resources/soliditycode/contractLinkage003.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract divideIHaveArgsReturnStorage{ function divideIHaveArgsReturn(int x,int y) public returns (int z) { diff --git a/framework/src/test/resources/soliditycode/contractLinkage004.sol b/framework/src/test/resources/soliditycode/contractLinkage004.sol index ca38896acee..92778e42bc9 100644 --- a/framework/src/test/resources/soliditycode/contractLinkage004.sol +++ b/framework/src/test/resources/soliditycode/contractLinkage004.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract divideIHaveArgsReturnStorage{ function divideIHaveArgsReturn(int x,int y) public returns (int z) { diff --git a/framework/src/test/resources/soliditycode/contractLinkage006.sol b/framework/src/test/resources/soliditycode/contractLinkage006.sol index 9c20c82dc02..53449f61ce2 100644 --- a/framework/src/test/resources/soliditycode/contractLinkage006.sol +++ b/framework/src/test/resources/soliditycode/contractLinkage006.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract AA{ uint256 public count=0; constructor () payable public{} diff --git a/framework/src/test/resources/soliditycode/contractOriginEnergyLimit001.sol b/framework/src/test/resources/soliditycode/contractOriginEnergyLimit001.sol index 212614935f6..6feb7fff3b8 100644 --- a/framework/src/test/resources/soliditycode/contractOriginEnergyLimit001.sol +++ b/framework/src/test/resources/soliditycode/contractOriginEnergyLimit001.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract findArgsContractTest{ function findArgsByIndexTest(uint i) public returns (uint z) { diff --git a/framework/src/test/resources/soliditycode/contractOriginEnergyLimit004.sol b/framework/src/test/resources/soliditycode/contractOriginEnergyLimit004.sol index 212614935f6..6feb7fff3b8 100644 --- a/framework/src/test/resources/soliditycode/contractOriginEnergyLimit004.sol +++ b/framework/src/test/resources/soliditycode/contractOriginEnergyLimit004.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract findArgsContractTest{ function findArgsByIndexTest(uint i) public returns (uint z) { diff --git a/framework/src/test/resources/soliditycode/contractOtherToTrcToken.sol b/framework/src/test/resources/soliditycode/contractOtherToTrcToken.sol index 74afd5d0e54..933358e128b 100644 --- a/framework/src/test/resources/soliditycode/contractOtherToTrcToken.sol +++ b/framework/src/test/resources/soliditycode/contractOtherToTrcToken.sol @@ -1,10 +1,10 @@ -//pragma solidity ^0.4.24; + contract ConvertType { constructor() payable public{} -function() payable external{} +fallback() payable external{} //function stringToTrctoken(address payable toAddress, string memory tokenStr, uint256 tokenValue) public { // trcToken t = trcToken(tokenStr); // ERROR diff --git a/framework/src/test/resources/soliditycode/contractScenario001.sol b/framework/src/test/resources/soliditycode/contractScenario001.sol index ca38896acee..92778e42bc9 100644 --- a/framework/src/test/resources/soliditycode/contractScenario001.sol +++ b/framework/src/test/resources/soliditycode/contractScenario001.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract divideIHaveArgsReturnStorage{ function divideIHaveArgsReturn(int x,int y) public returns (int z) { diff --git a/framework/src/test/resources/soliditycode/contractScenario002.sol b/framework/src/test/resources/soliditycode/contractScenario002.sol index aa9deda79ef..5b990fe36e8 100644 --- a/framework/src/test/resources/soliditycode/contractScenario002.sol +++ b/framework/src/test/resources/soliditycode/contractScenario002.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract TronNative{ address public voteContractAddress= address(0x10001); diff --git a/framework/src/test/resources/soliditycode/contractScenario003.sol b/framework/src/test/resources/soliditycode/contractScenario003.sol index ca38896acee..92778e42bc9 100644 --- a/framework/src/test/resources/soliditycode/contractScenario003.sol +++ b/framework/src/test/resources/soliditycode/contractScenario003.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract divideIHaveArgsReturnStorage{ function divideIHaveArgsReturn(int x,int y) public returns (int z) { diff --git a/framework/src/test/resources/soliditycode/contractScenario004.sol b/framework/src/test/resources/soliditycode/contractScenario004.sol index b3ca2687b4c..f6919502914 100644 --- a/framework/src/test/resources/soliditycode/contractScenario004.sol +++ b/framework/src/test/resources/soliditycode/contractScenario004.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.11; + contract TronToken { diff --git a/framework/src/test/resources/soliditycode/contractScenario005.sol b/framework/src/test/resources/soliditycode/contractScenario005.sol index d46098cd410..f33f21b60d8 100644 --- a/framework/src/test/resources/soliditycode/contractScenario005.sol +++ b/framework/src/test/resources/soliditycode/contractScenario005.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.16; + interface token { function transfer(address receiver, uint amount) external; @@ -44,7 +44,7 @@ contract Crowdsale { * 无函数名的Fallback函数, * 在向合约转账时,这个函数会被调用 */ - function () payable external{ + fallback() payable external{ require(!crowdsaleClosed); uint amount = msg.value; balanceOf[msg.sender] += amount; diff --git a/framework/src/test/resources/soliditycode/contractScenario006.sol b/framework/src/test/resources/soliditycode/contractScenario006.sol index 397c62096e0..6d6feeb8188 100644 --- a/framework/src/test/resources/soliditycode/contractScenario006.sol +++ b/framework/src/test/resources/soliditycode/contractScenario006.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); @@ -603,7 +603,7 @@ contract FoMo3Dlong is F3Devents { /** * @dev emergency buy uses last stored affiliate ID and team snek */ - function() + fallback() isActivated() isHuman() isWithinLimits(msg.value) diff --git a/framework/src/test/resources/soliditycode/contractScenario007.sol b/framework/src/test/resources/soliditycode/contractScenario007.sol index 1e6ff5d7250..a6fa095860f 100644 --- a/framework/src/test/resources/soliditycode/contractScenario007.sol +++ b/framework/src/test/resources/soliditycode/contractScenario007.sol @@ -1,4 +1,3 @@ -//pragma solidity 0.4.24; /** * @title ERC165 diff --git a/framework/src/test/resources/soliditycode/contractScenario008.sol b/framework/src/test/resources/soliditycode/contractScenario008.sol index 251b41bc6a2..ec25dc5ab3f 100644 --- a/framework/src/test/resources/soliditycode/contractScenario008.sol +++ b/framework/src/test/resources/soliditycode/contractScenario008.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.11; + /** @@ -1287,7 +1287,7 @@ contract KittyCore is KittyMinting { /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) - function() external payable { + fallback() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) diff --git a/framework/src/test/resources/soliditycode/contractScenario009.sol b/framework/src/test/resources/soliditycode/contractScenario009.sol index fb0b76db240..52fa63e90ac 100644 --- a/framework/src/test/resources/soliditycode/contractScenario009.sol +++ b/framework/src/test/resources/soliditycode/contractScenario009.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + library Set { // We define a new struct datatype that will be used to diff --git a/framework/src/test/resources/soliditycode/contractScenario010.sol b/framework/src/test/resources/soliditycode/contractScenario010.sol index f665ea9686e..4e299efecad 100644 --- a/framework/src/test/resources/soliditycode/contractScenario010.sol +++ b/framework/src/test/resources/soliditycode/contractScenario010.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.11; + contract TRON_ERC721 { //name diff --git a/framework/src/test/resources/soliditycode/contractScenario011.sol b/framework/src/test/resources/soliditycode/contractScenario011.sol index 74fe819be31..041d298cf32 100644 --- a/framework/src/test/resources/soliditycode/contractScenario011.sol +++ b/framework/src/test/resources/soliditycode/contractScenario011.sol @@ -1,4 +1,3 @@ -//pragma solidity ^0.4.11; /** @@ -7,36 +6,36 @@ * functions, this simplifies the implementation of "user permissions". */ contract Ownable { - address public owner; + address public owner; - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + if (newOwner != address(0)) { + owner = newOwner; + } } - } } @@ -151,7 +150,7 @@ contract KittyAccessControl { /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. - function unpause() public onlyCEO whenPaused { + function unpause() public virtual onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } @@ -234,20 +233,20 @@ contract KittyBase is KittyAccessControl { /// and over again. Caps out at one week (a cat can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) + uint32(1 minutes), + uint32(2 minutes), + uint32(5 minutes), + uint32(10 minutes), + uint32(30 minutes), + uint32(1 hours), + uint32(2 hours), + uint32(4 hours), + uint32(8 hours), + uint32(16 hours), + uint32(1 days), + uint32(2 days), + uint32(4 days), + uint32(7 days) ]; // An approximation of currently how many seconds are in between blocks. @@ -324,8 +323,8 @@ contract KittyBase is KittyAccessControl { uint256 _genes, address _owner ) - internal - returns (uint) + internal + returns (uint) { // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. However! _createKitty() is already @@ -350,8 +349,9 @@ contract KittyBase is KittyAccessControl { siringWithId: 0, cooldownIndex: cooldownIndex, generation: uint16(_generation) - }); - uint256 newKittenId = kitties.push(_kitty) - 1; + }); + kitties.push(_kitty); + uint256 newKittenId = kitties.length - 1; // It's probably never going to happen, 4 billion cats is A LOT, but // let's just be 100% sure we never let this happen. @@ -383,14 +383,14 @@ contract KittyBase is KittyAccessControl { /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley (https://github.com/dete) -contract ERC721 { +abstract contract ERC721 { // Required methods - function totalSupply() public view returns (uint256 total); - function balanceOf(address _owner) public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external view returns (address owner); - function approve(address _to, uint256 _tokenId) external; - function transfer(address _to, uint256 _tokenId) external; - function transferFrom(address _from, address _to, uint256 _tokenId) external; + function totalSupply() public virtual view returns (uint256 total); + function balanceOf(address _owner) public virtual view returns (uint256 balance); + function ownerOf(uint256 _tokenId) external virtual view returns (address owner); + function approve(address _to, uint256 _tokenId) external virtual; + function transfer(address _to, uint256 _tokenId) external virtual; + function transferFrom(address _from, address _to, uint256 _tokenId) external virtual; // Events event Transfer(address from, address to, uint256 tokenId); @@ -403,7 +403,7 @@ contract ERC721 { // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external view returns (bool); + function supportsInterface(bytes4 _interfaceID) external virtual view returns (bool); } @@ -421,24 +421,24 @@ contract KittyOwnership is ERC721, KittyBase { ERC721Metadata public erc721Metadata; bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); + bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); + bytes4(keccak256('name()')) ^ + bytes4(keccak256('symbol()')) ^ + bytes4(keccak256('totalSupply()')) ^ + bytes4(keccak256('balanceOf(address)')) ^ + bytes4(keccak256('ownerOf(uint256)')) ^ + bytes4(keccak256('approve(address,uint256)')) ^ + bytes4(keccak256('transfer(address,uint256)')) ^ + bytes4(keccak256('transferFrom(address,address,uint256)')) ^ + bytes4(keccak256('tokensOfOwner(address)')) ^ + bytes4(keccak256('tokenMetadata(uint256,string)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external view returns (bool) + function supportsInterface(bytes4 _interfaceID) external override view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); @@ -482,7 +482,7 @@ contract KittyOwnership is ERC721, KittyBase { /// @notice Returns the number of Kitties owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view returns (uint256 count) { + function balanceOf(address _owner) public view override returns (uint256 count) { return ownershipTokenCount[_owner]; } @@ -496,8 +496,9 @@ contract KittyOwnership is ERC721, KittyBase { address _to, uint256 _tokenId ) - external - whenNotPaused + override + external + whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); @@ -528,8 +529,9 @@ contract KittyOwnership is ERC721, KittyBase { address _to, uint256 _tokenId ) - external - whenNotPaused + external + override + whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); @@ -553,8 +555,9 @@ contract KittyOwnership is ERC721, KittyBase { address _to, uint256 _tokenId ) - external - whenNotPaused + external + override + whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); @@ -572,16 +575,17 @@ contract KittyOwnership is ERC721, KittyBase { /// @notice Returns the total number of Kitties currently in existence. /// @dev Required for ERC-721 compliance. - function totalSupply() public view returns (uint) { + function totalSupply() public override view returns (uint) { return kitties.length - 1; } /// @notice Returns the address currently assigned ownership of a given Kitty. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) - external - view - returns (address owner) + external + override + view + returns (address owner) { owner = kittyIndexToOwner[_tokenId]; @@ -688,7 +692,7 @@ contract KittyBreeding is KittyOwnership { /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 sun; + uint256 public autoBirthFee = 2 ; // Keeps track of number of pregnant kitties. uint256 public pregnantKitties; @@ -751,8 +755,8 @@ contract KittyBreeding is KittyOwnership { /// address(0) to clear all siring approvals for this Kitty. /// @param _sireId A Kitty that you own that _addr will now be able to sire with. function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused + external + whenNotPaused { require(_owns(msg.sender, _sireId)); sireAllowedToAddress[_sireId] = _addr; @@ -775,9 +779,9 @@ contract KittyBreeding is KittyOwnership { /// in the middle of a siring cooldown). /// @param _kittyId reference the id of the kitten, any user can inquire about it function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) + public + view + returns (bool) { require(_kittyId > 0); Kitty storage kit = kitties[_kittyId]; @@ -787,9 +791,9 @@ contract KittyBreeding is KittyOwnership { /// @dev Checks whether a kitty is currently pregnant. /// @param _kittyId reference the id of the kitten, any user can inquire about it function isPregnant(uint256 _kittyId) - public - view - returns (bool) + public + view + returns (bool) { require(_kittyId > 0); // A kitty is pregnant if and only if this field is set @@ -808,9 +812,9 @@ contract KittyBreeding is KittyOwnership { Kitty storage _sire, uint256 _sireId ) - private - view - returns(bool) + private + view + returns(bool) { // A Kitty can't breed with itself! if (_matronId == _sireId) { @@ -846,9 +850,9 @@ contract KittyBreeding is KittyOwnership { /// @dev Internal check to see if a given sire and matron are a valid mating pair for /// breeding via auction (i.e. skips ownership and siring approval checks). function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) + internal + view + returns (bool) { Kitty storage matron = kitties[_matronId]; Kitty storage sire = kitties[_sireId]; @@ -862,16 +866,16 @@ contract KittyBreeding is KittyOwnership { /// @param _matronId The ID of the proposed matron. /// @param _sireId The ID of the proposed sire. function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) + external + view + returns(bool) { require(_matronId > 0); require(_sireId > 0); Kitty storage matron = kitties[_matronId]; Kitty storage sire = kitties[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); + _isSiringPermitted(_sireId, _matronId); } /// @dev Internal utility function to initiate breeding, assumes that all breeding @@ -906,9 +910,9 @@ contract KittyBreeding is KittyOwnership { /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused + external + payable + whenNotPaused { // Checks for payment. require(msg.value >= autoBirthFee); @@ -946,11 +950,11 @@ contract KittyBreeding is KittyOwnership { // Test that these cats are a valid mating pair. require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); + matron, + _matronId, + sire, + _sireId + )); // All checks passed, kitty gets pregnant! _breedWith(_matronId, _sireId); @@ -965,9 +969,9 @@ contract KittyBreeding is KittyOwnership { /// new kitten will be ready to breed again. Note that anyone can call this function (if they /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) + external + whenNotPaused + returns(uint256) { // Grab a reference to the matron in storage. Kitty storage matron = kitties[_matronId]; @@ -1054,8 +1058,8 @@ contract KittyAuction is KittyBreeding { uint256 _endingPrice, uint256 _duration ) - external - whenNotPaused + external + whenNotPaused { // Auction contract checks input sizes // If kitty is already on any auction, this will throw @@ -1086,8 +1090,8 @@ contract KittyAuction is KittyBreeding { uint256 _endingPrice, uint256 _duration ) - external - whenNotPaused + external + whenNotPaused { // Auction contract checks input sizes // If kitty is already on any auction, this will throw @@ -1114,9 +1118,9 @@ contract KittyAuction is KittyBreeding { uint256 _sireId, uint256 _matronId ) - external - payable - whenNotPaused + external + payable + whenNotPaused { // Auction contract checks input sizes require(_owns(msg.sender, _matronId)); @@ -1150,7 +1154,7 @@ contract KittyMinting is KittyAuction { uint256 public constant GEN0_CREATION_LIMIT = 45000; // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 sun; + uint256 public constant GEN0_STARTING_PRICE = 10 ; uint256 public constant GEN0_AUCTION_DURATION = 1 days; // Counts the number of cats the contract owner has created. @@ -1163,7 +1167,7 @@ contract KittyMinting is KittyAuction { function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { address kittyOwner = _owner; if (kittyOwner == address(0)) { - kittyOwner = cooAddress; + kittyOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); @@ -1287,7 +1291,7 @@ contract KittyCore is KittyMinting { /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) - function() external payable { + fallback() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) @@ -1297,9 +1301,9 @@ contract KittyCore is KittyMinting { /// @notice Returns all the relevant information about a specific kitty. /// @param _id The ID of the kitty of interest. function getKitty(uint256 _id) - external - view - returns ( + external + view + returns ( bool isGestating, bool isReady, uint256 cooldownIndex, @@ -1332,7 +1336,7 @@ contract KittyCore is KittyMinting { /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. - function unpause() public onlyCEO whenPaused { + function unpause() public override onlyCEO whenPaused { require(address(saleAuction) != address(0)); require(address(siringAuction) != address(0)); require(address(geneScience) != address(0)); @@ -1383,17 +1387,17 @@ contract GeneScienceInterface { function isGeneScience() public pure returns (bool){ return true; } - + /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of mom /// @param genes2 genes of sire /// @return the genes that are supposed to be passed down the child function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - + return (genes1+genes2+targetBlock)/2; - - -} + + + } } @@ -1535,8 +1539,8 @@ contract ClockAuctionBase { /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) + internal + returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; @@ -1612,9 +1616,9 @@ contract ClockAuctionBase { /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) + internal + view + returns (uint256) { uint256 secondsPassed = 0; @@ -1643,9 +1647,9 @@ contract ClockAuctionBase { uint256 _duration, uint256 _secondsPassed ) - internal - pure - returns (uint256) + internal + pure + returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for @@ -1698,45 +1702,45 @@ contract ClockAuctionBase { * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused public returns (bool) { - paused = true; - emit Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused public returns (bool) { - paused = false; - emit Unpause(); - return true; - } + event Pause(); + event Unpause(); + + bool public paused = false; + + + /** + * @dev modifier to allow actions only when the contract IS paused + */ + modifier whenNotPaused() { + require(!paused); + _; + } + + /** + * @dev modifier to allow actions only when the contract IS NOT paused + */ + modifier whenPaused { + require(paused); + _; + } + + /** + * @dev called by the owner to pause, triggers stopped state + */ + function pause() onlyOwner whenNotPaused public returns (bool) { + paused = true; + emit Pause(); + return true; + } + + /** + * @dev called by the owner to unpause, returns to normal state + */ + function unpause() onlyOwner whenPaused public returns (bool) { + paused = false; + emit Unpause(); + return true; + } } @@ -1793,8 +1797,9 @@ contract ClockAuction is Pausable, ClockAuctionBase { uint256 _duration, address payable _seller ) - external - whenNotPaused + external + virtual + whenNotPaused { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. @@ -1818,9 +1823,10 @@ contract ClockAuction is Pausable, ClockAuctionBase { /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to bid on. function bid(uint256 _tokenId) - external - payable - whenNotPaused + external + payable + virtual + whenNotPaused { // _bid will throw if the bid or funds transfer fails _bid(_tokenId, msg.value); @@ -1833,7 +1839,7 @@ contract ClockAuction is Pausable, ClockAuctionBase { /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) - external + external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); @@ -1847,9 +1853,9 @@ contract ClockAuction is Pausable, ClockAuctionBase { /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external + whenPaused + onlyOwner + external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); @@ -1859,9 +1865,9 @@ contract ClockAuction is Pausable, ClockAuctionBase { /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) - external - view - returns + external + view + returns ( address seller, uint256 startingPrice, @@ -1872,20 +1878,20 @@ contract ClockAuction is Pausable, ClockAuctionBase { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt + auction.seller, + auction.startingPrice, + auction.endingPrice, + auction.duration, + auction.startedAt ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) + external + view + returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); @@ -1905,7 +1911,7 @@ contract SiringClockAuction is ClockAuction { // Delegate constructor constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} + ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be KittyCore contract. @@ -1921,7 +1927,8 @@ contract SiringClockAuction is ClockAuction { uint256 _duration, address payable _seller ) - external + external + override { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. @@ -1946,8 +1953,9 @@ contract SiringClockAuction is ClockAuction { /// should be wrapped. Also returns the kitty to the /// seller rather than the winner. function bid(uint256 _tokenId) - external - payable + external + payable + override { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; @@ -1978,7 +1986,7 @@ contract SaleClockAuction is ClockAuction { // Delegate constructor constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} + ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. @@ -1993,7 +2001,8 @@ contract SaleClockAuction is ClockAuction { uint256 _duration, address payable _seller ) - external + external + override { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. @@ -2016,8 +2025,9 @@ contract SaleClockAuction is ClockAuction { /// @dev Updates lastSalePrice if seller is the nft contract /// Otherwise, works the same as default bid method. function bid(uint256 _tokenId) - external - payable + external + payable + override { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; diff --git a/framework/src/test/resources/soliditycode/contractScenario012.sol b/framework/src/test/resources/soliditycode/contractScenario012.sol index 7bed08dd111..7fea2b1ccf1 100644 --- a/framework/src/test/resources/soliditycode/contractScenario012.sol +++ b/framework/src/test/resources/soliditycode/contractScenario012.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract PayTest { uint256 public n; @@ -42,7 +42,7 @@ return msg.sender.send(money); // return (msg.sender, msg.value, msg.sender.send(money)); // } -// function () payable { +// fallback() payable { // msg.sender.send(1); // } diff --git a/framework/src/test/resources/soliditycode/contractScenario013.sol b/framework/src/test/resources/soliditycode/contractScenario013.sol index b91085d018e..93b7905679b 100644 --- a/framework/src/test/resources/soliditycode/contractScenario013.sol +++ b/framework/src/test/resources/soliditycode/contractScenario013.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract timetest { function time() public{ diff --git a/framework/src/test/resources/soliditycode/contractScenario014.sol b/framework/src/test/resources/soliditycode/contractScenario014.sol index 41ea739e231..9f423d1b1ab 100644 --- a/framework/src/test/resources/soliditycode/contractScenario014.sol +++ b/framework/src/test/resources/soliditycode/contractScenario014.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract Contract1 { constructor() public payable{} function send5SunToReceiver(address payable _receiver) payable public{ diff --git a/framework/src/test/resources/soliditycode/contractTest.sol b/framework/src/test/resources/soliditycode/contractTest.sol index 409545eaabb..9a72b4a53b4 100644 --- a/framework/src/test/resources/soliditycode/contractTest.sol +++ b/framework/src/test/resources/soliditycode/contractTest.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.4; + contract Test{ diff --git a/framework/src/test/resources/soliditycode/contractToMathedFeed.sol b/framework/src/test/resources/soliditycode/contractToMathedFeed.sol index a5d181ad927..d9df9d9c10d 100644 --- a/framework/src/test/resources/soliditycode/contractToMathedFeed.sol +++ b/framework/src/test/resources/soliditycode/contractToMathedFeed.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract ToMathedFeed { uint public i=1; diff --git a/framework/src/test/resources/soliditycode/contractTransferToken001.sol b/framework/src/test/resources/soliditycode/contractTransferToken001.sol index e91c0d7bf0f..0edbbfbb44a 100644 --- a/framework/src/test/resources/soliditycode/contractTransferToken001.sol +++ b/framework/src/test/resources/soliditycode/contractTransferToken001.sol @@ -15,7 +15,7 @@ contract A { contract B{ constructor() public payable {} - function() external payable {} + fallback() external payable {} function kill(address payable toAddress) payable public{ selfdestruct(toAddress); } diff --git a/framework/src/test/resources/soliditycode/contractTrcToken001.sol b/framework/src/test/resources/soliditycode/contractTrcToken001.sol index 0db64f36336..ea28f4a62b6 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken001.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken001.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract tokenTest{ trcToken idCon = 0; diff --git a/framework/src/test/resources/soliditycode/contractTrcToken002.sol b/framework/src/test/resources/soliditycode/contractTrcToken002.sol index 0db64f36336..ea28f4a62b6 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken002.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken002.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract tokenTest{ trcToken idCon = 0; diff --git a/framework/src/test/resources/soliditycode/contractTrcToken003.sol b/framework/src/test/resources/soliditycode/contractTrcToken003.sol index 48205199eec..863429fc4f8 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken003.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken003.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract tokenTest{ constructor() public payable{} diff --git a/framework/src/test/resources/soliditycode/contractTrcToken005.sol b/framework/src/test/resources/soliditycode/contractTrcToken005.sol index 48205199eec..863429fc4f8 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken005.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken005.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract tokenTest{ constructor() public payable{} diff --git a/framework/src/test/resources/soliditycode/contractTrcToken011.sol b/framework/src/test/resources/soliditycode/contractTrcToken011.sol index f815c26b136..43e4010ec3f 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken011.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken011.sol @@ -1,7 +1,7 @@ -//pragma solidity ^0.4.24; + contract transferTokenContract { constructor() payable public{} - function() payable external{} + fallback() payable external{} function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { toAddress.transferToken(tokenValue, id); } @@ -29,7 +29,7 @@ contract transferTokenContract { contract Result { event log(uint256,uint256,uint256); constructor() payable public{} - function() payable external{ + fallback() payable external{ emit log(msg.tokenid,msg.tokenvalue,msg.value); } } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken012.sol b/framework/src/test/resources/soliditycode/contractTrcToken012.sol index 668f67ae205..ab0c19767e7 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken012.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken012.sol @@ -1,7 +1,7 @@ -//pragma solidity ^0.4.24; + contract transferTokenContract { constructor() payable public{} - function() payable external{} + fallback() payable external{} function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { toAddress.transferToken(tokenValue, id); } diff --git a/framework/src/test/resources/soliditycode/contractTrcToken014.sol b/framework/src/test/resources/soliditycode/contractTrcToken014.sol index 3753770398a..589406c47c6 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken014.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken014.sol @@ -1,7 +1,7 @@ -//pragma solidity ^0.4.24; + contract transferTokenContract { constructor() payable public{} - function() payable external{} + fallback() payable external{} function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { toAddress.transferToken(tokenValue, id); } @@ -28,7 +28,7 @@ contract transferTokenContract { contract Result { event log(uint256,uint256,uint256); constructor() payable public{} - function() payable external{ + fallback() payable external{ emit log(msg.tokenid,msg.tokenvalue,msg.value); } } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken018.sol b/framework/src/test/resources/soliditycode/contractTrcToken018.sol index 668f67ae205..ab0c19767e7 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken018.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken018.sol @@ -1,7 +1,7 @@ -//pragma solidity ^0.4.24; + contract transferTokenContract { constructor() payable public{} - function() payable external{} + fallback() payable external{} function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { toAddress.transferToken(tokenValue, id); } diff --git a/framework/src/test/resources/soliditycode/contractTrcToken023.sol b/framework/src/test/resources/soliditycode/contractTrcToken023.sol index 99b19beb107..070acb201ff 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken023.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken023.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract tokenTest{ constructor() public payable{} @@ -10,16 +10,16 @@ contract B{ uint256 public flag = 0; constructor() public payable {} - function() external { + fallback() external { flag = 1; } } -//pragma solidity ^0.4.24; + contract C{ uint256 public flag = 0; constructor() public payable {} - function() external payable { + fallback() external payable { //flag = 1; } diff --git a/framework/src/test/resources/soliditycode/contractTrcToken026.sol b/framework/src/test/resources/soliditycode/contractTrcToken026.sol index 66635521150..5464265d81f 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken026.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken026.sol @@ -1,8 +1,8 @@ -//pragma solidity ^0.4.24; + contract token{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function testInCall(address callBAddress,address callCAddress, address toAddress ,uint256 amount,trcToken id) payable public{ //callBAddress.call(bytes4(keccak256("transC(address,address,uint256,trcToken)")),callCAddress,toAddress,amount,id); callBAddress.call(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callCAddress,toAddress,amount,id)); @@ -16,14 +16,14 @@ contract token{ contract B{ constructor() public payable{} - function() external payable{} + fallback() external payable{} function transC(address payable callCAddress,address payable toAddress,uint256 amount, trcToken id) payable public{ callCAddress.call(abi.encodeWithSignature("trans(address,uint256,trcToken)",toAddress,amount,id)); } } contract C{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function trans(address payable toAddress,uint256 amount, trcToken id) payable public{ toAddress.transferToken(amount,id); } diff --git a/framework/src/test/resources/soliditycode/contractTrcToken027.sol b/framework/src/test/resources/soliditycode/contractTrcToken027.sol index ee9c1d3eb46..e7d6ee768f3 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken027.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken027.sol @@ -1,8 +1,8 @@ -//pragma solidity ^0.4.24; + contract token{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function testInCall(address callBAddress,address callCAddress, address toAddress ,uint256 amount,trcToken id) payable public{ callBAddress.call(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callCAddress,toAddress,amount,id)); } @@ -15,14 +15,14 @@ contract token{ contract B{ constructor() public payable{} - function() external payable{} + fallback() external payable{} function transC(address callCAddress,address toAddress,uint256 amount, trcToken id) payable public{ callCAddress.call(abi.encodeWithSignature("trans(address,uint256,trcToken)",toAddress,amount,id)); } } contract C{ constructor() payable public{} - function() payable external{} + fallback() payable external{} function trans(address payable toAddress,uint256 amount, trcToken id) payable public{ toAddress.transferToken(amount,id); } diff --git a/framework/src/test/resources/soliditycode/contractTrcToken028.sol b/framework/src/test/resources/soliditycode/contractTrcToken028.sol index 957f1c3c60d..0f27d89c819 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken028.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken028.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract token{ uint256 public a=1; @@ -16,7 +16,7 @@ contract token{ contract B{ uint256 public flag =0; constructor() public payable{} - function() external payable{} + fallback() external payable{} function tokenBalance(trcToken id) payable public returns(uint256){ flag =9; return flag; diff --git a/framework/src/test/resources/soliditycode/contractTrcToken029.sol b/framework/src/test/resources/soliditycode/contractTrcToken029.sol index e8f5cbc0988..8480cf6f19d 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken029.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken029.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract token{ address public a; @@ -14,7 +14,7 @@ contract token{ contract B{ uint256 public flag =0; constructor() public payable{} - function() external payable{} + fallback() external payable{} function transferToken(uint256 amount, trcToken id) payable public returns(bool){ flag =9; } diff --git a/framework/src/test/resources/soliditycode/contractTrcToken030.sol b/framework/src/test/resources/soliditycode/contractTrcToken030.sol index 5693292d127..06b8201979c 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken030.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken030.sol @@ -1,4 +1,3 @@ -//pragma solidity ^0.4.24; contract token{ constructor() public payable{} @@ -14,5 +13,5 @@ contract B{ constructor() public payable {} - function() external payable {} + fallback() external payable {} } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken031.sol b/framework/src/test/resources/soliditycode/contractTrcToken031.sol index 5693292d127..65ec394e8da 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken031.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken031.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract token{ constructor() public payable{} @@ -14,5 +14,5 @@ contract B{ constructor() public payable {} - function() external payable {} + fallback() external payable {} } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken034.sol b/framework/src/test/resources/soliditycode/contractTrcToken034.sol index c9a5e70a3fb..b50992d06bb 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken034.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken034.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract token{ @@ -19,5 +19,5 @@ contract B{ uint256 public flag = 0; constructor() public payable {} - function() external payable {} + fallback() external payable {} } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken035.sol b/framework/src/test/resources/soliditycode/contractTrcToken035.sol index c9a5e70a3fb..b50992d06bb 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken035.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken035.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract token{ @@ -19,5 +19,5 @@ contract B{ uint256 public flag = 0; constructor() public payable {} - function() external payable {} + fallback() external payable {} } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken036.sol b/framework/src/test/resources/soliditycode/contractTrcToken036.sol index 6a4c61d1e07..c1da2f7555e 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken036.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken036.sol @@ -1,7 +1,7 @@ -//pragma solidity ^0.4.24; + contract IllegalDecorate { constructor() payable public{} -function() payable external{} +fallback() payable external{} event log(uint256); function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public payable { emit log(msg.value); @@ -14,7 +14,7 @@ toAddress.transfer(msg.value); contract IllegalDecorate1 { constructor() payable public{} -function() payable external{} +fallback() payable external{} event log(uint256); function transferTokenWithConstant(address payable toAddress, uint256 tokenValue) public payable { emit log(msg.value); @@ -27,7 +27,7 @@ toAddress.transfer(msg.value); contract IllegalDecorate2 { constructor() payable public{} -function() payable external{} +fallback() payable external{} event log(uint256); function transferTokenWithView(address payable toAddress, uint256 tokenValue) public payable { emit log(msg.value); @@ -41,7 +41,7 @@ toAddress.transfer(msg.value); contract IllegalDecorate3 { event log(uint256); constructor() payable public{} -function() payable external{} +fallback() payable external{} function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue) public { emit log(msg.value); emit log(msg.tokenvalue); diff --git a/framework/src/test/resources/soliditycode/contractTrcToken036_1.sol b/framework/src/test/resources/soliditycode/contractTrcToken036_1.sol index cd039f3e39d..327ab5a756e 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken036_1.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken036_1.sol @@ -1,7 +1,7 @@ -//pragma solidity ^0.4.24; + contract IllegalDecorate { constructor() payable public{} -function() payable external{} +fallback() payable external{} event log(uint256); function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public pure { emit log(msg.value); diff --git a/framework/src/test/resources/soliditycode/contractTrcToken036_2.sol b/framework/src/test/resources/soliditycode/contractTrcToken036_2.sol index 0b4d56e086b..817a96e3c80 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken036_2.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken036_2.sol @@ -1,7 +1,7 @@ -//pragma solidity ^0.4.24; + contract IllegalDecorate { constructor() payable public{} -function() payable external{} +fallback() payable external{} event log(uint256); function transferTokenWithConstant(address toAddress, uint256 tokenValue) public constant { emit log(msg.value); diff --git a/framework/src/test/resources/soliditycode/contractTrcToken036_3.sol b/framework/src/test/resources/soliditycode/contractTrcToken036_3.sol index b8c7d750514..67400c2e8ad 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken036_3.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken036_3.sol @@ -1,7 +1,7 @@ -//pragma solidity ^0.4.24; + contract IllegalDecorate { constructor() payable public{} -function() payable external{} +fallback() payable external{} event log(uint256); function transferTokenWithView(address payable toAddress, uint256 tokenValue) public view { emit log(msg.value); diff --git a/framework/src/test/resources/soliditycode/contractTrcToken036_4.sol b/framework/src/test/resources/soliditycode/contractTrcToken036_4.sol index 29c1990962b..cbaca0d4b38 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken036_4.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken036_4.sol @@ -1,8 +1,8 @@ -//pragma solidity ^0.4.24; + contract IllegalDecorate { event log(uint256); constructor() payable public{} -function() payable external{} +fallback() payable external{} function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue) public { emit log(msg.value); emit log(msg.tokenvalue); diff --git a/framework/src/test/resources/soliditycode/contractTrcToken036_old.sol b/framework/src/test/resources/soliditycode/contractTrcToken036_old.sol index 7ea2561a1e1..1f03afb7636 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken036_old.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken036_old.sol @@ -1,9 +1,9 @@ -//pragma solidity ^0.4.24; + contract IllegalDecorate1 { constructor() payable public{} -function() payable public{} +fallback() payable public{} event log(uint256); function transferTokenWithConstant(address toAddress, uint256 tokenValue) public constant { emit log(msg.value); @@ -16,7 +16,7 @@ toAddress.transfer(msg.value); contract IllegalDecorate2 { constructor() payable public{} -function() payable public{} +fallback() payable public{} event log(uint256); function transferTokenWithView(address toAddress, uint256 tokenValue) public view { emit log(msg.value); @@ -30,7 +30,7 @@ toAddress.transfer(msg.value); contract IllegalDecorate3 { event log(uint256); constructor() payable public{} -function() payable public{} +fallback() payable public{} function transferTokenWithOutPayable(address toAddress, uint256 tokenValue) public { emit log(msg.value); emit log(msg.tokenvalue); diff --git a/framework/src/test/resources/soliditycode/contractTrcToken037.sol b/framework/src/test/resources/soliditycode/contractTrcToken037.sol index 5e3fbcb8270..7cdd91702e8 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken037.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken037.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract transferTrc10 { function receive(address payable rec) public payable { @@ -16,7 +16,7 @@ contract transferTrc10 { } contract receiveTrc10 { - function() external payable {} + fallback() external payable {} function checkTrc10(uint256 amount,trcToken tid,uint256 meamount) public{ require(amount==address(this).tokenBalance(tid)); require(meamount==msg.sender.tokenBalance(tid)); diff --git a/framework/src/test/resources/soliditycode/contractTrcToken038.sol b/framework/src/test/resources/soliditycode/contractTrcToken038.sol index 713d7661e84..eeb5ae744cf 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken038.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken038.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract transferTrc10 { function receive(address payable rec) public payable { @@ -16,7 +16,7 @@ contract transferTrc10 { } contract receiveTrc10 { - function() external payable { + fallback() external payable { } function AssertError() public{ assert(1==2); diff --git a/framework/src/test/resources/soliditycode/contractTrcToken039.sol b/framework/src/test/resources/soliditycode/contractTrcToken039.sol index e60b3285652..ebf6fb932ed 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken039.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken039.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + /* * 1. caller账户issue一个token * 2. caller部署proxy, 传入1000 token,1000 trx @@ -17,7 +17,7 @@ contract Proxy { function upgradeTo(address _address) public { implementation = _address; } - function() payable external{ + fallback() payable external{ address addr = implementation; require(addr != address(0)); assembly { diff --git a/framework/src/test/resources/soliditycode/contractTrcToken041.sol b/framework/src/test/resources/soliditycode/contractTrcToken041.sol index a6272bc813d..6284253d1d5 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken041.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken041.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract tokenTest{ constructor() public payable{} @@ -12,7 +12,7 @@ contract B{ uint256 public flag = 0; constructor() public payable {} - function() external payable {} + fallback() external payable {} function setFlag() public payable{ flag = 1; diff --git a/framework/src/test/resources/soliditycode/contractTrcToken043.sol b/framework/src/test/resources/soliditycode/contractTrcToken043.sol index f815c26b136..43e4010ec3f 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken043.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken043.sol @@ -1,7 +1,7 @@ -//pragma solidity ^0.4.24; + contract transferTokenContract { constructor() payable public{} - function() payable external{} + fallback() payable external{} function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { toAddress.transferToken(tokenValue, id); } @@ -29,7 +29,7 @@ contract transferTokenContract { contract Result { event log(uint256,uint256,uint256); constructor() payable public{} - function() payable external{ + fallback() payable external{ emit log(msg.tokenid,msg.tokenvalue,msg.value); } } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken048.sol b/framework/src/test/resources/soliditycode/contractTrcToken048.sol index de2844608c0..e705f696c1d 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken048.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken048.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract Test { event log(uint256); diff --git a/framework/src/test/resources/soliditycode/contractTrcToken049.sol b/framework/src/test/resources/soliditycode/contractTrcToken049.sol index 3fd502c89fd..d40480720df 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken049.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken049.sol @@ -1,4 +1,3 @@ -//pragma solidity ^0.4.24; contract tokenTest{ constructor() public payable{} diff --git a/framework/src/test/resources/soliditycode/contractTrcToken050.sol b/framework/src/test/resources/soliditycode/contractTrcToken050.sol index 3fd502c89fd..6bc6d956898 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken050.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken050.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract tokenTest{ constructor() public payable{} diff --git a/framework/src/test/resources/soliditycode/contractTrcToken051.sol b/framework/src/test/resources/soliditycode/contractTrcToken051.sol index b5b9efd4817..493016b777f 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken051.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken051.sol @@ -1,8 +1,8 @@ -//pragma solidity ^0.4.24; + contract tokenTest{ constructor() public payable{} - function() external payable{} + fallback() external payable{} // positive case function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ //trcToken id = 0x74657374546f6b656e; diff --git a/framework/src/test/resources/soliditycode/contractTrcToken052.sol b/framework/src/test/resources/soliditycode/contractTrcToken052.sol index 3fd502c89fd..6bc6d956898 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken052.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken052.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract tokenTest{ constructor() public payable{} diff --git a/framework/src/test/resources/soliditycode/contractTrcToken054.sol b/framework/src/test/resources/soliditycode/contractTrcToken054.sol index 48205199eec..863429fc4f8 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken054.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken054.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract tokenTest{ constructor() public payable{} diff --git a/framework/src/test/resources/soliditycode/contractTrcToken055.sol b/framework/src/test/resources/soliditycode/contractTrcToken055.sol index 48205199eec..863429fc4f8 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken055.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken055.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract tokenTest{ constructor() public payable{} diff --git a/framework/src/test/resources/soliditycode/contractTrcToken060.sol b/framework/src/test/resources/soliditycode/contractTrcToken060.sol index 0db64f36336..ea28f4a62b6 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken060.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken060.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract tokenTest{ trcToken idCon = 0; diff --git a/framework/src/test/resources/soliditycode/contractTrcToken061.sol b/framework/src/test/resources/soliditycode/contractTrcToken061.sol index 0db64f36336..ea28f4a62b6 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken061.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken061.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract tokenTest{ trcToken idCon = 0; diff --git a/framework/src/test/resources/soliditycode/contractTrcToken064.sol b/framework/src/test/resources/soliditycode/contractTrcToken064.sol index cf2a6fe8097..43e0da8a510 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken064.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken064.sol @@ -1,7 +1,7 @@ -//pragma solidity ^0.4.24; + contract transferTokenContract { constructor() payable public{} - function() payable external{} + fallback() payable external{} function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { toAddress.transferToken(tokenValue, id); } @@ -43,7 +43,7 @@ contract transferTokenContract { contract Result { event log(uint256,uint256,uint256); constructor() payable public{} - function() payable external{ + fallback() payable external{ emit log(msg.tokenid,msg.tokenvalue,msg.value); } } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken066.sol b/framework/src/test/resources/soliditycode/contractTrcToken066.sol index f815c26b136..43e4010ec3f 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken066.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken066.sol @@ -1,7 +1,7 @@ -//pragma solidity ^0.4.24; + contract transferTokenContract { constructor() payable public{} - function() payable external{} + fallback() payable external{} function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { toAddress.transferToken(tokenValue, id); } @@ -29,7 +29,7 @@ contract transferTokenContract { contract Result { event log(uint256,uint256,uint256); constructor() payable public{} - function() payable external{ + fallback() payable external{ emit log(msg.tokenid,msg.tokenvalue,msg.value); } } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken067.sol b/framework/src/test/resources/soliditycode/contractTrcToken067.sol index f815c26b136..43e4010ec3f 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken067.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken067.sol @@ -1,7 +1,7 @@ -//pragma solidity ^0.4.24; + contract transferTokenContract { constructor() payable public{} - function() payable external{} + fallback() payable external{} function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { toAddress.transferToken(tokenValue, id); } @@ -29,7 +29,7 @@ contract transferTokenContract { contract Result { event log(uint256,uint256,uint256); constructor() payable public{} - function() payable external{ + fallback() payable external{ emit log(msg.tokenid,msg.tokenvalue,msg.value); } } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken073.sol b/framework/src/test/resources/soliditycode/contractTrcToken073.sol index 9cb13ec7268..a9ee8ea412b 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken073.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken073.sol @@ -1,4 +1,3 @@ -//pragma solidity ^0.4.0; contract Dest { event logFallback(uint256 indexed, uint256 indexed, uint256 indexed); @@ -11,7 +10,7 @@ contract Dest { emit logGetToken(msg.sender.tokenBalance(tokenId), msg.tokenid, msg.tokenvalue, msg.value); } - function () payable external{ + fallback() payable external{ emit logFallback(msg.tokenid, msg.tokenvalue, msg.value); } } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken075.sol b/framework/src/test/resources/soliditycode/contractTrcToken075.sol index 2a32fd7e8d3..9f201900295 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken075.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken075.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract Dest { event logFallback(uint256 indexed, uint256 indexed, uint256 indexed); @@ -20,7 +20,7 @@ contract Dest { emit logGetToken(msg.sender.tokenBalance(trcToken(9223372036855775827)), msg.tokenid, msg.tokenvalue, msg.value); } - function () payable external{ + fallback() payable external{ emit logFallback(msg.tokenid, msg.tokenvalue, msg.value); } } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken076.sol b/framework/src/test/resources/soliditycode/contractTrcToken076.sol index 9de79a327c3..a9decbee320 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken076.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken076.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract Test { address public origin; address public sender; diff --git a/framework/src/test/resources/soliditycode/contractTrcToken077.sol b/framework/src/test/resources/soliditycode/contractTrcToken077.sol index e110f24e2fc..aeecf9cb9a5 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken077.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken077.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract trcToken077 { function addressTest() public returns(bytes32 addressValue) { diff --git a/framework/src/test/resources/soliditycode/contractTrcToken078.sol b/framework/src/test/resources/soliditycode/contractTrcToken078.sol index f7504ea55aa..02ba4a79699 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken078.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken078.sol @@ -1,7 +1,7 @@ -//pragma solidity ^0.4.24; + contract callerContract { constructor() public payable{} - function() external payable{} + fallback() external payable{} function sendToB(address called_address, address c) public payable{ called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); } @@ -13,7 +13,7 @@ contract callerContract { } } contract calledContract { - function() external payable{} + fallback() external payable{} constructor() public payable {} function transferTo(address payable toAddress)public payable{ toAddress.transfer(5); @@ -29,7 +29,7 @@ contract callerContract { address public sender; constructor() public payable{} event log(address,address); - function() payable external{ + fallback() payable external{ emit log(tx.origin,msg.sender); } } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken079.sol b/framework/src/test/resources/soliditycode/contractTrcToken079.sol index 48205199eec..863429fc4f8 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken079.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken079.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract tokenTest{ constructor() public payable{} diff --git a/framework/src/test/resources/soliditycode/contractTrcToken080.sol b/framework/src/test/resources/soliditycode/contractTrcToken080.sol index 27529ce48e8..2d2688b74a4 100644 --- a/framework/src/test/resources/soliditycode/contractTrcToken080.sol +++ b/framework/src/test/resources/soliditycode/contractTrcToken080.sol @@ -1,10 +1,10 @@ -//pragma solidity ^0.4.24; + contract tokenTest{ trcToken idCon = 0; uint256 tokenValueCon=0; uint256 callValueCon = 0; - function() external payable{} + fallback() external payable{} // positive case function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ //trcToken id = 0x74657374546f6b656e; diff --git a/framework/src/test/resources/soliditycode/contractTrcTokenToOther.sol b/framework/src/test/resources/soliditycode/contractTrcTokenToOther.sol index 22456df9e8e..8e926d3ba17 100644 --- a/framework/src/test/resources/soliditycode/contractTrcTokenToOther.sol +++ b/framework/src/test/resources/soliditycode/contractTrcTokenToOther.sol @@ -1,10 +1,10 @@ -//pragma solidity ^0.4.24; + contract ConvertType { constructor() payable public{} -function() payable external{} +fallback() payable external{} //function trcTokenOnStorage(trcToken storage token) internal { // ERROR: Data location can only be specified for array, struct or mapping types, but "storage" was given. //} diff --git a/framework/src/test/resources/soliditycode/contractUnknownException.sol b/framework/src/test/resources/soliditycode/contractUnknownException.sol index 37c28468be1..4fd9c64be72 100644 --- a/framework/src/test/resources/soliditycode/contractUnknownException.sol +++ b/framework/src/test/resources/soliditycode/contractUnknownException.sol @@ -1,4 +1,3 @@ -// pragma solidity ^0.4.24; contract testA { constructor() public payable { diff --git a/framework/src/test/resources/soliditycode/create2CallContract.sol b/framework/src/test/resources/soliditycode/create2CallContract.sol index f2de1c7ee13..046706ebd9e 100644 --- a/framework/src/test/resources/soliditycode/create2CallContract.sol +++ b/framework/src/test/resources/soliditycode/create2CallContract.sol @@ -1,6 +1,6 @@ contract callerContract { constructor() payable public{} - function() payable external{} + fallback() payable external{} function delegateCallCreate2(address called_address, bytes memory code, uint256 salt) public { called_address.delegatecall(abi.encodeWithSignature("deploy(bytes,uint256)",code,salt)); } diff --git a/framework/src/test/resources/soliditycode/create2Istanbul.sol b/framework/src/test/resources/soliditycode/create2Istanbul.sol new file mode 100644 index 00000000000..c2ef8f3236b --- /dev/null +++ b/framework/src/test/resources/soliditycode/create2Istanbul.sol @@ -0,0 +1,28 @@ + + +contract create2Istanbul { + function deploy(bytes memory code, uint256 salt) public returns(address) { + address addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + + } + return addr; + } + + // prefix in main net is 0x41, testnet config is 0xa0 + function get(bytes1 prefix, bytes calldata code, uint256 salt) external view returns(address) { + //bytes32 hash = keccak256(abi.encodePacked(bytes1(0x41),address(this), salt, keccak256(code))); + bytes32 hash = keccak256(abi.encodePacked(prefix,address(this), salt, keccak256(code))); + address addr = address(uint160(uint256(hash))); + return addr; + } + +} + +contract B { + constructor() public payable{} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/demo.sol b/framework/src/test/resources/soliditycode/demo.sol index c7f6d0d4da9..06bf15387fc 100644 --- a/framework/src/test/resources/soliditycode/demo.sol +++ b/framework/src/test/resources/soliditycode/demo.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.24; + contract tokenTest{ uint256 codesize; diff --git a/framework/src/test/resources/soliditycode/enumAndStruct.sol b/framework/src/test/resources/soliditycode/enumAndStruct.sol new file mode 100644 index 00000000000..836a4ac850e --- /dev/null +++ b/framework/src/test/resources/soliditycode/enumAndStruct.sol @@ -0,0 +1,43 @@ + + +struct S_out { +uint x; +} + +enum ErrorType { +Revert_Error, //0 +RevertWithMsg_Error, //1 +Require_Error, //2 +RequirewithMsg_Error, //3 +Assert_Error, //4 +Tansfer_Error, //5 +Send_Error, //6 +Math_Error, //7 +ArrayOverFlow_Error //8 +} + +contract enumAndStructTest { + +struct S_inner { +int x; +} + +enum ErrorType_inner { +Revert_Error, //0 +RevertWithMsg_Error, //1 +Require_Error, //2 +RequirewithMsg_Error, //3 +Assert_Error, //4 +Tansfer_Error, //5 +Send_Error, //6 +Math_Error, //7 +ArrayOverFlow_Error //8 +} + +function getvalue() public returns(uint) { + require(ErrorType.Require_Error == ErrorType(2)); + S_out memory s = S_out(1); + return s.x; +} + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/event002.sol b/framework/src/test/resources/soliditycode/event002.sol index 70a5275521c..a61f834e1b5 100644 --- a/framework/src/test/resources/soliditycode/event002.sol +++ b/framework/src/test/resources/soliditycode/event002.sol @@ -1,4 +1,4 @@ -pragma solidity >=0.4.0 <0.7.0; + contract Event { diff --git a/framework/src/test/resources/soliditycode/fallbackUpgrade.sol b/framework/src/test/resources/soliditycode/fallbackUpgrade.sol new file mode 100644 index 00000000000..f73140ad245 --- /dev/null +++ b/framework/src/test/resources/soliditycode/fallbackUpgrade.sol @@ -0,0 +1,83 @@ +contract Test0{ + event FuncCalled(bytes data,uint a); +} + +contract Test1 { + + event FuncCalled(string a); + fallback() external { + x = "fallback"; + emit FuncCalled(x); + } + string x; +} +//含有payable的fallback,无receice +contract Test2 { + + event FuncCalled(string data); + fallback() external payable{ + x = "fallback"; + emit FuncCalled(x); + } + string x; +} + +contract TestPayable { + event FuncCalled(string a); + + fallback() external payable { + x = "fallback"; + emit FuncCalled(x); + } + + receive() external payable { + x = "receive"; + emit FuncCalled(x); + } + string x; +} + +contract Caller { + function callTest0(Test0 test) public{ + (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()")); + require(success); + } + function callTest1(address test) public returns (bool) { + (bool success,) = test.call(abi.encodeWithSignature("nonExistingFunction()")); + require(success); + (success,) = address(test).call(""); + require(success); + return true; + } + function callTest2(address test) public payable returns (bool) { + (bool success,) = test.call.value(1000)(abi.encodeWithSignature("nonExistingFunction()")); + require(success); + return true; + } + function callTestPayable1(TestPayable test) public payable returns (bool) { + (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()")); + require(success); + (success,) = address(test).call(""); + require(success); + return true; + } +} + + +//contract Test0 { +// event FallbackCall(string data,bytes msg); +// //event FuncCalled(string a,bytes data); +// function() external payable{ +// x = "fallback"; +// emit FallbackCall(x,msg.data); +// } +// string x; +//} +//contract Caller{ +// function call(Test0 test) public payable returns(bool){ +// (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()")); +// require(success); +// return true; +// } +//} + diff --git a/framework/src/test/resources/soliditycode/getAddressChange.sol b/framework/src/test/resources/soliditycode/getAddressChange.sol new file mode 100644 index 00000000000..2796da68770 --- /dev/null +++ b/framework/src/test/resources/soliditycode/getAddressChange.sol @@ -0,0 +1,12 @@ +contract getAddressChange { + constructor() public payable {} + // testaddress1函数新增了一个address属性。0.6.0之前 external函数可以通过address(x)来转化为地址,6.0将其禁止,可以通过函数address属性直接获取 + function testaddress1() public view returns(address) { + //return address(this.getamount); //0.6.0之前可以使用 + return this.getamount.address; //0.6.0 + + } + function getamount(address) external view returns(uint256) { + return address(this).balance; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/isSRCandidate.sol b/framework/src/test/resources/soliditycode/isSRCandidate.sol new file mode 100644 index 00000000000..e8e9b692dec --- /dev/null +++ b/framework/src/test/resources/soliditycode/isSRCandidate.sol @@ -0,0 +1,35 @@ + + + +contract ContractB{ + address others; +} + +contract TestIsSRCandidate{ + + ContractB contractB = new ContractB(); + + function isSRCandidateTest(address addr) public view returns (bool) { + return address(addr).isSRCandidate; + } + + function zeroAddressTest() public view returns (bool) { + return address(0x0).isSRCandidate; + } + + function localContractAddrTest() public view returns (bool) { + return address(this).isSRCandidate; + } + + function otherContractAddrTest() public view returns (bool) { + return address(contractB).isSRCandidate; + } + + function nonpayableAddrTest(address addr) public view returns (bool) { + return addr.isSRCandidate; + } + + function payableAddrTest(address payable addr) public returns (bool) { + return addr.isSRCandidate; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/override002.sol b/framework/src/test/resources/soliditycode/override002.sol new file mode 100644 index 00000000000..c5533815f9b --- /dev/null +++ b/framework/src/test/resources/soliditycode/override002.sol @@ -0,0 +1,12 @@ +pragma solidity >=0.5.0 <0.7.0; + +contract A { + uint public x; + function setValue(uint _x) public { + x = _x; + } +} +contract B is A {} +contract C is A {} +// No explicit override required +contract D is B, C {} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/override003.sol b/framework/src/test/resources/soliditycode/override003.sol new file mode 100644 index 00000000000..103133fc53c --- /dev/null +++ b/framework/src/test/resources/soliditycode/override003.sol @@ -0,0 +1,20 @@ +pragma solidity ^0.6.0; +contract A { + uint public x; + function setValue(uint _x) public virtual { + x = _x; + } +} + +contract B { + uint public y; + function setValue(uint _y) public virtual { + y = _y; + } +} + +contract C is A, B { + function setValue(uint _x) public override(B,A) { + A.setValue(_x); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/override004.sol b/framework/src/test/resources/soliditycode/override004.sol new file mode 100644 index 00000000000..1549d49b53f --- /dev/null +++ b/framework/src/test/resources/soliditycode/override004.sol @@ -0,0 +1,25 @@ +pragma solidity >=0.5.0 <0.7.0; + +contract A { + uint public x = 4; + function setValue(uint _x) public notZero { + x = _x; + } + modifier notZero() virtual { + require(x >= 5,"x must >= 5"); + _; + } +} + +contract B is A { + function setValue2(uint _x) public { + x = _x; + } +} + +contract C is A,B { + modifier notZero override { + require(x >= 6,"x must >= 6"); + _; + } +} diff --git a/framework/src/test/resources/soliditycode/override005.sol b/framework/src/test/resources/soliditycode/override005.sol new file mode 100644 index 00000000000..80a75e93e59 --- /dev/null +++ b/framework/src/test/resources/soliditycode/override005.sol @@ -0,0 +1,39 @@ +pragma solidity 0.6.0; + +contract Base { + enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } + ActionChoices public choice2 = ActionChoices.GoRight; + + function stopped() virtual external pure returns (bool) { + return true; + } + function i() virtual external pure returns (int) { + return 32482980; + } + function i2() virtual external pure returns (int) { + return -32482980; + } + function ui() virtual external pure returns (uint) { + return 23487820; + } + function origin() virtual external pure returns (address) { + return 0x3b0E4a6EdEE231CE0c3433F00F1bbc5FeD409c0B; + } + function b32() virtual external pure returns (bytes32) { + return 0xb55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd231050; + } + function choice() virtual external returns (ActionChoices) { + return choice2; + } +} + +contract Test is Base { + + bool override public stopped = false; + int override public i = 32482989; + int override public i2 = -32482989; + uint override public ui = 23487823; + address override public origin = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; + bytes32 override public b32 = 0xb55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105c; + ActionChoices override public choice = ActionChoices.SitStill; +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/payable001.sol b/framework/src/test/resources/soliditycode/payable001.sol new file mode 100644 index 00000000000..4fe7b20921f --- /dev/null +++ b/framework/src/test/resources/soliditycode/payable001.sol @@ -0,0 +1,31 @@ + + + +contract A { + constructor() public payable{ + } + + fallback() external payable { + } +} + +contract PayableTest { + +address payable a1; +function receiveMoneyTransfer(address a, uint256 _x) public { +a1 = payable(a); +a1.transfer(_x); +} + +function receiveMoneySend(address a, uint256 x) public { +address payable a2 = payable(a); +a2.send(x); +} + +function receiveMoneyTransferWithContract(A PayableTest, uint256 x) public { +payable(address(PayableTest)).transfer(x); +} + +constructor() public payable{ +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/pedersenHash002.sol b/framework/src/test/resources/soliditycode/pedersenHash002.sol index b61d81d7683..b0a78973ef2 100644 --- a/framework/src/test/resources/soliditycode/pedersenHash002.sol +++ b/framework/src/test/resources/soliditycode/pedersenHash002.sol @@ -1,12 +1,11 @@ -pragma solidity ^0.5.8; pragma experimental ABIEncoderV2; import "./SafeMath.sol"; -contract TokenTRC20 { - function transfer(address _to, uint256 _value) public returns (bool success); +abstract contract TokenTRC20 { + function transfer(address _to, uint256 _value) public virtual returns (bool success); - function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) public virtual returns (bool success); } contract ShieldedTRC20 { diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest1TestRequireContract.sol b/framework/src/test/resources/soliditycode/requireExceptiontest1TestRequireContract.sol index dbb97ab4f04..16d01911d35 100644 --- a/framework/src/test/resources/soliditycode/requireExceptiontest1TestRequireContract.sol +++ b/framework/src/test/resources/soliditycode/requireExceptiontest1TestRequireContract.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract TestThrowsContract{ function testAssert() public { assert(1==2); diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest2TestThrowsContract.sol b/framework/src/test/resources/soliditycode/requireExceptiontest2TestThrowsContract.sol index abcc2d84ca2..1ff73ad6460 100644 --- a/framework/src/test/resources/soliditycode/requireExceptiontest2TestThrowsContract.sol +++ b/framework/src/test/resources/soliditycode/requireExceptiontest2TestThrowsContract.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract TestThrowsContract{ function testAssert() public { assert(1==2); diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest3TestRevertContract.sol b/framework/src/test/resources/soliditycode/requireExceptiontest3TestRevertContract.sol index 229fa6a74b0..b42a8c3fb23 100644 --- a/framework/src/test/resources/soliditycode/requireExceptiontest3TestRevertContract.sol +++ b/framework/src/test/resources/soliditycode/requireExceptiontest3TestRevertContract.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract TestThrowsContract{ function testAssert() public { assert(1==2); diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest4noPayableContract.sol b/framework/src/test/resources/soliditycode/requireExceptiontest4noPayableContract.sol index aa043ad9c3b..35f89631e7d 100644 --- a/framework/src/test/resources/soliditycode/requireExceptiontest4noPayableContract.sol +++ b/framework/src/test/resources/soliditycode/requireExceptiontest4noPayableContract.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract noPayableContract { diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest4noPayableContract_1.sol b/framework/src/test/resources/soliditycode/requireExceptiontest4noPayableContract_1.sol index fe7ba275736..5b6dd509f6f 100644 --- a/framework/src/test/resources/soliditycode/requireExceptiontest4noPayableContract_1.sol +++ b/framework/src/test/resources/soliditycode/requireExceptiontest4noPayableContract_1.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract noPayableContract { diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest5noPayableConstructor.sol b/framework/src/test/resources/soliditycode/requireExceptiontest5noPayableConstructor.sol index e1733b0562b..097594ab7c9 100644 --- a/framework/src/test/resources/soliditycode/requireExceptiontest5noPayableConstructor.sol +++ b/framework/src/test/resources/soliditycode/requireExceptiontest5noPayableConstructor.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract MyContract { uint money; diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest5noPayableConstructor_1.sol b/framework/src/test/resources/soliditycode/requireExceptiontest5noPayableConstructor_1.sol index 793b468d4c2..5008ec5c9bf 100644 --- a/framework/src/test/resources/soliditycode/requireExceptiontest5noPayableConstructor_1.sol +++ b/framework/src/test/resources/soliditycode/requireExceptiontest5noPayableConstructor_1.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract MyContract { uint money; diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest6transferTestContract.sol b/framework/src/test/resources/soliditycode/requireExceptiontest6transferTestContract.sol index 8c64ff740cd..4f171aebb9a 100644 --- a/framework/src/test/resources/soliditycode/requireExceptiontest6transferTestContract.sol +++ b/framework/src/test/resources/soliditycode/requireExceptiontest6transferTestContract.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract transferTestContract { function tranferTest(address payable addr) public payable{ diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest7payableFallbakContract.sol b/framework/src/test/resources/soliditycode/requireExceptiontest7payableFallbakContract.sol index 85cf454e08e..534726cb1b4 100644 --- a/framework/src/test/resources/soliditycode/requireExceptiontest7payableFallbakContract.sol +++ b/framework/src/test/resources/soliditycode/requireExceptiontest7payableFallbakContract.sol @@ -1,7 +1,7 @@ -//pragma solidity ^0.4.0; + contract Test { - function() external { x = 1; } + fallback() external { x = 1; } uint x; } diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest8newContractGasNoenough.sol b/framework/src/test/resources/soliditycode/requireExceptiontest8newContractGasNoenough.sol index b322ac68591..b8743e8231a 100644 --- a/framework/src/test/resources/soliditycode/requireExceptiontest8newContractGasNoenough.sol +++ b/framework/src/test/resources/soliditycode/requireExceptiontest8newContractGasNoenough.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract Account{ uint256 public accId; diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest9MessageUsedErrorFeed.sol b/framework/src/test/resources/soliditycode/requireExceptiontest9MessageUsedErrorFeed.sol index 05448bfd0ac..18142d20ee8 100644 --- a/framework/src/test/resources/soliditycode/requireExceptiontest9MessageUsedErrorFeed.sol +++ b/framework/src/test/resources/soliditycode/requireExceptiontest9MessageUsedErrorFeed.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract MathedFeed { diff --git a/framework/src/test/resources/soliditycode/requireExceptiontestFunctionUsedErrorFeed.sol b/framework/src/test/resources/soliditycode/requireExceptiontestFunctionUsedErrorFeed.sol index b7f5244954d..ad90faa6dab 100644 --- a/framework/src/test/resources/soliditycode/requireExceptiontestFunctionUsedErrorFeed.sol +++ b/framework/src/test/resources/soliditycode/requireExceptiontestFunctionUsedErrorFeed.sol @@ -1,4 +1,4 @@ -//pragma solidity ^0.4.0; + contract MessageFeed { diff --git a/framework/src/test/resources/soliditycode/selector.sol b/framework/src/test/resources/soliditycode/selector.sol new file mode 100644 index 00000000000..5805a6e8d22 --- /dev/null +++ b/framework/src/test/resources/soliditycode/selector.sol @@ -0,0 +1,21 @@ + + +library A { + function getBalance(address) public view returns (uint256) { + return address(this).balance; + } + + function getamount(address) external view returns (uint256) { + return address(this).balance; + } +} + +contract testSelector { + using A for address; + + + function getselector2() public view returns (bytes4, bytes4) { + return (A.getBalance.selector, A.getamount.selector); + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/stackContract001.sol b/framework/src/test/resources/soliditycode/stackContract001.sol new file mode 100644 index 00000000000..c2e8f2f7611 --- /dev/null +++ b/framework/src/test/resources/soliditycode/stackContract001.sol @@ -0,0 +1,61 @@ + + +contract A{ + event log(uint256); + constructor() payable public{ + emit log(withdrawreward()); + emit log(address(this).rewardbalance); + } + function withdrawRewardTest() public returns (uint256){ + return withdrawreward(); + } + + function test() public{ + emit log(123); + } +} + +contract B{ + event log(uint256); + constructor() payable public{ + emit log(withdrawreward()); + emit log(address(this).rewardbalance); + } + function Stake(address sr, uint256 amount) public returns (bool result){ + return stake(sr, amount); + } + function UnStake() public returns (bool result){ + return unstake(); + } + function SelfdestructTest(address payable target) public{ + selfdestruct(target); + } + function rewardBalance(address addr) public view returns (uint256){ + return addr.rewardbalance; + } + + function nullAddressTest() public view returns (uint256) { + return address(0x0).rewardbalance; + } + + function localContractAddrTest() public view returns (uint256) { + address payable localContract = address(uint160(address(this))); + return localContract.rewardbalance; + } + + function withdrawRewardTest() public returns (uint256){ + return withdrawreward(); + } + + function contractBWithdrawRewardTest(address contractB) public returns (uint) { + return B(contractB).withdrawRewardTest(); + } + + function createA() public returns (address){ + return address(new A()); + } + + function callA(address Addr) public{ + A(Addr).test(); + } +} diff --git a/framework/src/test/resources/soliditycode/stackSuicide001.sol b/framework/src/test/resources/soliditycode/stackSuicide001.sol new file mode 100644 index 00000000000..d1fc520ddb2 --- /dev/null +++ b/framework/src/test/resources/soliditycode/stackSuicide001.sol @@ -0,0 +1,84 @@ + +contract testStakeSuicide{ + B b; + constructor() payable public{} + function deployB() payable public returns (B addrB){ + b = (new B).value(1000000000)(); + return b; + } + function SelfdestructTest(address payable target) public{ + selfdestruct(target); + } + function SelfdestructTest2(address sr, uint256 amount, address payable target) public{ + stake(sr, amount); + selfdestruct(target); + } + function Stake(address sr, uint256 amount) public payable returns (bool result){ + return stake(sr, amount); + } + function Stake2(address sr, uint256 amount) public returns (bool result){ + stake(sr, amount); + return stake(sr, amount); + } + function UnStake() public returns (bool result){ + return unstake(); + } + function UnStake2() public returns (bool result){ + unstake(); + return unstake(); + } + function WithdrawReward() public { + withdrawreward(); + } + function RewardBalance(address addr) view public returns (uint256 balance) { + return addr.rewardbalance; + } + function revertTest1(address sr, uint256 amount, address payable transferAddr) public{ + transferAddr.transfer(1000000); + stake(sr, amount); + transferAddr.transfer(2000000); + stake(sr, 1000000000000000);//stake more than balance to fail + transferAddr.transfer(4000000); + } + function revertTest2(address payable transferAddr) public{ + transferAddr.transfer(1000000); + unstake(); + transferAddr.transfer(2000000); + unstake();//unstake twice to fail + transferAddr.transfer(4000000); + } + + function BStake(address sr, uint256 amount) public returns (bool result){ + return b.Stake(sr, amount); + } + function BUnStake() public returns (bool result){ + return b.UnStake(); + } + function transfer(address payable add,uint256 num) public { + return add.transfer(num); + } +} + +contract B{ + constructor() payable public{} + function Stake(address sr, uint256 amount) public returns (bool result){ + return stake(sr, amount); + } + function UnStake() public returns (bool result){ + return unstake(); + } + function SelfdestructTest(address payable target) public{ + selfdestruct(target); + } + + function deploy(bytes memory code, uint256 salt) public returns(address) { + address addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + return addr; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/stateVariableShadowing.sol b/framework/src/test/resources/soliditycode/stateVariableShadowing.sol new file mode 100644 index 00000000000..a9109ee296c --- /dev/null +++ b/framework/src/test/resources/soliditycode/stateVariableShadowing.sol @@ -0,0 +1,21 @@ +contract test { +// uint public x; +// function setValue1(uint _x) public returns (uint){ +// x = _x; +// return x; +// } + uint public y; + function setValue3(uint _x) public returns (uint){ + y = _x; + return y; + } +} + +contract stateVariableShadowing is test { + uint public x; + function setValue2(uint _x) public returns (uint){ + x = _x; + return x; + } +} + diff --git a/framework/src/test/resources/soliditycode/stringSplit.sol b/framework/src/test/resources/soliditycode/stringSplit.sol new file mode 100644 index 00000000000..84231f2d1fe --- /dev/null +++ b/framework/src/test/resources/soliditycode/stringSplit.sol @@ -0,0 +1,45 @@ + + +contract testStringSplit { +string s1 = "s""1""2"",./"; +string s2 = "s123?\\'."; +string s3 = hex"41"hex"42"; +string s4 = hex"4142"; + +function getS1() public view returns (string memory) { +return s1; +} + +function getS1N1() public pure returns (string memory) { +string memory n1 = "s""1""2"",./"; +return n1; +} + +function getS2() public view returns (string memory) { +return s2; +} + +function getS2N2() public pure returns (string memory) { +string memory n2 = "s123?\'."; +return n2; +} + +function getS3() public view returns (string memory) { +return s3; +} + +function getS3N3() public pure returns (string memory) { +string memory n3 = hex"41"hex"42"; +return n3; +} + +function getS4() public view returns (string memory) { +return s4; +} + +function getS4N4() public pure returns (string memory) { +string memory n4 = hex"4142"; +return n4; +} + +} diff --git a/framework/src/test/resources/soliditycode/testStakeSuicide.sol b/framework/src/test/resources/soliditycode/testStakeSuicide.sol new file mode 100644 index 00000000000..3342a5607f7 --- /dev/null +++ b/framework/src/test/resources/soliditycode/testStakeSuicide.sol @@ -0,0 +1,71 @@ + +contract testStakeSuicide{ + B b; + constructor() payable public{} + function deployB() payable public returns (B addrB){ + b = (new B).value(1000000000)(); + return b; + } + function SelfdestructTest(address payable target) public{ + selfdestruct(target); + } + function SelfdestructTest2(address sr, uint256 amount, address payable target) public{ + stake(sr, amount); + selfdestruct(target); + } + function Stake(address sr, uint256 amount) public returns (bool result){ + return stake(sr, amount); + } + function Stake2(address sr, uint256 amount) public returns (bool result){ + stake(sr, amount); + return stake(sr, amount); + } + function UnStake() public returns (bool result){ + return unstake(); + } + function UnStake2() public returns (bool result){ + unstake(); + return unstake(); + } + function WithdrawReward() public { + withdrawreward(); + } + function RewardBalance(address addr) view public returns (uint256 balance) { + return addr.rewardbalance; + } + function revertTest1(address sr, uint256 amount, address payable transferAddr) public{ + transferAddr.transfer(1000000); + stake(sr, amount); + transferAddr.transfer(2000000); + stake(sr, 1000000000000000);//stake more than balance to fail + transferAddr.transfer(4000000); + } + function revertTest2(address payable transferAddr) public{ + transferAddr.transfer(1000000); + unstake(); + transferAddr.transfer(2000000); + unstake();//unstake twice to fail + transferAddr.transfer(4000000); + } + function BStake(address sr, uint256 amount) public returns (bool result){ + return b.Stake(sr, amount); + } + function BUnStake() public returns (bool result){ + return b.UnStake(); + } + function BSelfdestructTest(address payable target) public{ + b.SelfdestructTest(target); + } +} +contract B{ + constructor() payable public{} + function Stake(address sr, uint256 amount) public returns (bool result){ + return stake(sr, amount); + } + function UnStake() public returns (bool result){ + return unstake(); + } + function SelfdestructTest(address payable target) public{ + selfdestruct(target); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/tryCatch001.sol b/framework/src/test/resources/soliditycode/tryCatch001.sol new file mode 100644 index 00000000000..283db92e159 --- /dev/null +++ b/framework/src/test/resources/soliditycode/tryCatch001.sol @@ -0,0 +1,105 @@ + + +enum ErrorType { + Revert_Error, //0 + RevertWithMsg_Error, //1 + Require_Error, //2 + RequirewithMsg_Error, //3 + Assert_Error, //4 + Tansfer_Error, //5 + Send_Error, //6 + Math_Error, //7 + ArrayOverFlow_Error //8 +} +contract errorContract { + uint256[] arraryUint ; + + function errorSwitch(uint256 errorType) public returns(string memory) { + if (ErrorType(errorType) == ErrorType.Revert_Error){ + revert(); + } else if (ErrorType(errorType) == ErrorType.RevertWithMsg_Error){ + revert("Revert Msg."); + } else if (ErrorType(errorType) == ErrorType.Require_Error) { + require(0>1); + } else if (ErrorType(errorType) == ErrorType.RequirewithMsg_Error) { + require(0>1,"Require Msg."); + } else if (ErrorType(errorType) == ErrorType.Assert_Error) { + assert(1<0); + } else if (ErrorType(errorType) == ErrorType.Tansfer_Error) { + payable(msg.sender).transfer(1); + } else if (ErrorType(errorType) == ErrorType.Send_Error) { + payable(msg.sender).send(1); + } else if (ErrorType(errorType) == ErrorType.Math_Error) { + uint256 a = 1; + uint256 b = 0; + uint256 n = a / b; + } else if (ErrorType(errorType) == ErrorType.ArrayOverFlow_Error) { + arraryUint.pop(); + } + return "success"; + + } + + function callFun(string memory functionStr, string memory argsStr) public{ + address(this).call(abi.encodeWithSignature(functionStr, argsStr)); + } + +} + +contract NewContract { + uint256[] arraryUint ; + + constructor(uint256 errorType) public payable{ + if (ErrorType(errorType) == ErrorType.Revert_Error){ + revert(); + } else if (ErrorType(errorType) == ErrorType.RevertWithMsg_Error){ + revert("Revert Msg."); + } else if (ErrorType(errorType) == ErrorType.Require_Error) { + require(0>1); + } else if (ErrorType(errorType) == ErrorType.RequirewithMsg_Error) { + require(0>1,"Require Msg."); + } else if (ErrorType(errorType) == ErrorType.Assert_Error) { + assert(1<0); + } else if (ErrorType(errorType) == ErrorType.Tansfer_Error) { + payable(msg.sender).transfer(1); + } else if (ErrorType(errorType) == ErrorType.Send_Error) { + payable(msg.sender).send(1); + } else if (ErrorType(errorType) == ErrorType.Math_Error) { + uint256 a = 1; + uint256 b = 0; + uint256 n = a / b; + } else if (ErrorType(errorType) == ErrorType.ArrayOverFlow_Error) { + arraryUint.pop(); + } + } +} + +contract tryTest { + function getData(errorContract inter, string memory functionStr, string memory argsStr) public payable returns(string memory) { + try inter.callFun(functionStr,argsStr) { + return "123"; + } catch Error(string memory errorMsg/* 出错原因 */) { + return errorMsg; + } catch (bytes memory) { + return "3"; + } + } + + function getErrorSwitch(errorContract add, uint256 errorType ) public payable returns(string memory) { + try add.errorSwitch(errorType) returns (string memory Msg) { + return Msg; + } catch Error(string memory errorMsg/* 出错原因 */) { + return errorMsg; + } catch (bytes memory) { + return "NoErrorMsg"; + } + } + + function catchNewErrorSwitch(uint256 errorType) public returns (address nc){ + try new NewContract(errorType) returns (NewContract nc){ + return address(nc); + }catch { + return address(0x00); + } + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/tvmAssetIssue001.sol b/framework/src/test/resources/soliditycode/tvmAssetIssue001.sol new file mode 100644 index 00000000000..5388ed68473 --- /dev/null +++ b/framework/src/test/resources/soliditycode/tvmAssetIssue001.sol @@ -0,0 +1,25 @@ + +contract tvmAssetIssue001 { + constructor() payable public{} + + function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { + return assetissue(name, abbr, totalSupply, precision); + } + + function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { + return updateasset(tokenId, bytes(url), bytes(desc)); + } + + function updateOtherAccountAsset(string memory url, string memory desc) public returns (bool) { + trcToken tokenId = trcToken(1000004); + return updateasset(tokenId, bytes(url), bytes(desc)); + } + + function updateAssetOnBytes(trcToken tokenId, bytes memory url, bytes memory desc) public returns (bool) { + return updateasset(tokenId, url, desc); + } + + function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { + toAddress.transferToken(tokenValue, id); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/tvmAssetIssue002.sol b/framework/src/test/resources/soliditycode/tvmAssetIssue002.sol new file mode 100644 index 00000000000..87c1206b778 --- /dev/null +++ b/framework/src/test/resources/soliditycode/tvmAssetIssue002.sol @@ -0,0 +1,15 @@ + + +contract tvmAssetIssue002 { + constructor() payable public{} + + function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { + assetissue(name, abbr, totalSupply, precision); + return assetissue(name, abbr, totalSupply, precision); + } + + function updateAsset(trcToken tokenId, string memory url1, string memory desc1, string memory url2, string memory desc2) public returns (bool) { + updateasset(tokenId, bytes(url1), bytes(desc1)); + return updateasset(tokenId, bytes(url2), bytes(desc2)); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/tvmAssetIssue003.sol b/framework/src/test/resources/soliditycode/tvmAssetIssue003.sol new file mode 100644 index 00000000000..f5ce5e0dc3e --- /dev/null +++ b/framework/src/test/resources/soliditycode/tvmAssetIssue003.sol @@ -0,0 +1,23 @@ + + +contract tvmAssetIssue003 { + constructor() payable public{} + + function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { + return assetissue(name, abbr, totalSupply, precision); + } + + function tokenIssueAndTransfer(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision, address addr) public { + address payable newaddress = address(uint160(addr)); + newaddress.transfer(100000000); + assetissue(name, abbr, totalSupply, precision); + newaddress.transfer(100000000); + } + + function updateAssetAndTransfer(trcToken tokenId, string memory url, string memory desc, address addr) public { + address payable newaddress = address(uint160(addr)); + newaddress.transfer(100000000); + updateasset(tokenId, bytes(url), bytes(desc)); + newaddress.transfer(100000000); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/tvmAssetIssue004.sol b/framework/src/test/resources/soliditycode/tvmAssetIssue004.sol new file mode 100644 index 00000000000..c8332de8f45 --- /dev/null +++ b/framework/src/test/resources/soliditycode/tvmAssetIssue004.sol @@ -0,0 +1,39 @@ + + +contract A { + + constructor() payable public{} + fallback() payable external {} + + function tokenIssueA(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint){ + return assetissue(name, abbr, totalSupply, precision); + } + + function updateAssetA(trcToken tokenId, string memory url, string memory desc) public returns (bool) { + return updateasset(tokenId, bytes(url), bytes(desc)); + } + + function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { + toAddress.transferToken(tokenValue, id); + } +} + +contract tvmAssetIssue004 { + + A a; + + constructor() payable public{} + + function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { + return a.tokenIssueA(name, abbr, totalSupply, precision); + } + + function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { + return a.updateAssetA(tokenId, url, desc); + } + + function getContractAddress() public payable returns (address) { + a = (new A).value(1024000000)(); + return address(a); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/tvmAssetIssue005.sol b/framework/src/test/resources/soliditycode/tvmAssetIssue005.sol new file mode 100644 index 00000000000..8c36d050ff8 --- /dev/null +++ b/framework/src/test/resources/soliditycode/tvmAssetIssue005.sol @@ -0,0 +1,45 @@ + + +contract tvmAssetIssue005 { + constructor() payable public{} + + fallback() external payable { + } + + function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { + return assetissue(name, abbr, totalSupply, precision); + } + + function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { + return updateasset(tokenId, bytes(url), bytes(desc)); + } + + function updateAssetOnBytes(trcToken tokenId, bytes memory url, bytes memory desc) public returns (bool) { + return updateasset(tokenId, url, desc); + } + + function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { + toAddress.transferToken(tokenValue, id); + } + + function SelfdestructTest(address payable target) public { + selfdestruct(target); + } +} + +contract B { + event Deployed(address addr, uint256 salt); + + function deploy(uint256 salt) public returns (address) { + address addr; + bytes memory code = type(tvmAssetIssue005).creationCode; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed(addr, salt); + return addr; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/unStake001.sol b/framework/src/test/resources/soliditycode/unStake001.sol new file mode 100644 index 00000000000..03734fecfa5 --- /dev/null +++ b/framework/src/test/resources/soliditycode/unStake001.sol @@ -0,0 +1,90 @@ + + +contract unStakeTest { + B b; + constructor() payable public{} + function deployB() payable public returns (B addrB){ + b = (new B).value(1000000000)(); + return b; + } + + function selfdestructTest(address payable target) public { + selfdestruct(target); + } + + function selfdestructTest2(address sr, uint256 amount, address payable target) public { + stake(sr, amount); + selfdestruct(target); + } + + function Stake(address sr, uint256 amount) public returns (bool result){ + return stake(sr, amount); + } + + function stake2(address sr, uint256 amount) public returns (bool result){ + stake(sr, amount); + return stake(sr, amount); + } + + function unStake() public returns (bool result){ + return unstake(); + } + + function unStake2() public returns (bool result){ + unstake(); + return unstake(); + } + + function withdrawReward() public returns (uint256 amount) { + return withdrawreward(); + } + + function rewardBalance(address addr) view public returns (uint256 balance) { + return addr.rewardbalance; + } + + function revertTest1(address sr, uint256 amount, address payable transferAddr) public { + transferAddr.transfer(1000000); + stake(sr, amount); + transferAddr.transfer(2000000); + stake(sr, 1000000000000000); + //stake more than balance to fail + transferAddr.transfer(4000000); + } + + function revertTest2(address payable transferAddr) public { + transferAddr.transfer(1000000); + unstake(); + transferAddr.transfer(2000000); + unstake(); + //unstake twice to fail + transferAddr.transfer(4000000); + } + + function BStake(address sr, uint256 amount) public returns (bool result){ + return b.Stake(sr, amount); + } + + function BUnStake() public returns (bool result){ + return b.UnStake(); + } + + function BSelfdestructTest(address payable target) public { + b.SelfdestructTest(target); + } +} + +contract B { + constructor() payable public{} + function Stake(address sr, uint256 amount) public returns (bool result){ + return stake(sr, amount); + } + + function UnStake() public returns (bool result){ + return unstake(); + } + + function SelfdestructTest(address payable target) public { + selfdestruct(target); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/virtual001.sol b/framework/src/test/resources/soliditycode/virtual001.sol new file mode 100644 index 00000000000..6dddac07ef4 --- /dev/null +++ b/framework/src/test/resources/soliditycode/virtual001.sol @@ -0,0 +1,19 @@ +pragma solidity ^0.6.0; +interface X { + function setValue(uint _x) external; +} +abstract contract Y { + function setBool(bool _y) external virtual ; +} +contract Y2 { + string public z; + function setString(string calldata _z) external virtual { z = "123"; } +} + +contract Z is X,Y,Y2 { + uint public x; + bool public y; + function setValue(uint _x) external override { x = _x; } + function setBool(bool _y) external override { y = _y; } + function setString(string calldata _z) external override { z = _z; } +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/AssertException002.sol b/framework/src/test/resources/soliditycode_0.5.15/AssertException002.sol new file mode 100644 index 00000000000..2bff1dcec3e --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/AssertException002.sol @@ -0,0 +1,17 @@ +//pragma solidity ^0.4.0; + +contract AssertException{ + function divideIHaveArgsReturn(int x,int y) public returns (int z) { + return x / y; + } + function testAssert() public { + require(2==1); + } +} +contract C { + constructor() public payable { + assert(1==2); + } + function fun() public { + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/AssignToExternal.sol b/framework/src/test/resources/soliditycode_0.5.15/AssignToExternal.sol new file mode 100644 index 00000000000..d4f09590a36 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/AssignToExternal.sol @@ -0,0 +1,30 @@ +contract AssignToExternal { + // Not allow: + // function f(uint256[] calldata x, uint256[] calldata y) external pure { + // x = y; + // } + + // allow: + + function f(uint256 a) external returns (uint){ + a = a + 1; + return a; + } + + function StringSet(string calldata a) external returns (string memory){ + return a; + } + + function ByteSet(bytes32 a) external returns (bytes32){ + return a; + } + + function UintArraySet(uint256[2] calldata a) external returns (uint256[2] memory){ + return a; + } + + function AddSet(address a) external returns (address){ + return a; + } + +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/BlockHash.sol b/framework/src/test/resources/soliditycode_0.5.15/BlockHash.sol new file mode 100644 index 00000000000..6603da65e44 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/BlockHash.sol @@ -0,0 +1,38 @@ +contract TestBlockHash { + + function testOR1(bytes32 value) public returns(bytes32, bytes32, bytes32) { + bytes32 b1 = blockhash(block.number - 1); + bytes32 c = blockhash(block.number - 1) | bytes32(value); + return (b1, c, blockhash(block.number - 1)); + } + + function testOR2(bytes32 value) public returns(bytes32, bytes32, bytes32) { + bytes32 b1 = blockhash(block.number - 1); + bytes32 c = bytes32(value) | blockhash(block.number - 1); + return (b1, c, blockhash(block.number - 1)); + } + + function testAND1(bytes32 value) public returns(bytes32, bytes32, bytes32) { + bytes32 b1 = blockhash(block.number - 1); + bytes32 c = blockhash(block.number - 1) & bytes32(value); + return (b1, c, blockhash(block.number - 1)); + } + + function testAND2(bytes32 value) public returns(bytes32, bytes32, bytes32) { + bytes32 b1 = blockhash(block.number - 1); + bytes32 c = bytes32(value) & blockhash(block.number - 1); + return (b1, c, blockhash(block.number - 1)); + } + + function testXOR1(bytes32 value) public returns(bytes32, bytes32, bytes32) { + bytes32 b1 = blockhash(block.number - 1); + bytes32 c = blockhash(block.number - 1) ^ bytes32(value); + return (b1, c, blockhash(block.number - 1)); + } + + function testXOR2(bytes32 value) public returns(bytes32, bytes32, bytes32) { + bytes32 b1 = blockhash(block.number - 1); + bytes32 c = bytes32(value) ^ blockhash(block.number - 1); + return (b1, c, blockhash(block.number - 1)); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/ClearAbi001.sol b/framework/src/test/resources/soliditycode_0.5.15/ClearAbi001.sol new file mode 100644 index 00000000000..fccc59e14be --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/ClearAbi001.sol @@ -0,0 +1,7 @@ +//pragma solidity ^0.4.0; + +contract testConstantContract{ +function testPayable() public view returns (int z) { +return 1; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/ClearAbi005.sol b/framework/src/test/resources/soliditycode_0.5.15/ClearAbi005.sol new file mode 100644 index 00000000000..a3115398386 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/ClearAbi005.sol @@ -0,0 +1,26 @@ +contract Factory { + event Deployed(address addr, uint256 salt, address sender); + function deploy(bytes memory code, uint256 salt) public returns(address){ + address addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed(addr, salt, msg.sender); + return addr; + } +} + + + +contract TestConstract { + uint public i=0; + constructor () public { + } + function plusOne() public returns(uint){ + i++; + return i; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/ConstructorDefaults.sol b/framework/src/test/resources/soliditycode_0.5.15/ConstructorDefaults.sol new file mode 100644 index 00000000000..4b6186ccb95 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/ConstructorDefaults.sol @@ -0,0 +1,9 @@ +contract testIsContract{ + bool result; + constructor (bool a) public { + result = a; + } +function test( address a) public returns (bool) { +return result; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/Create2Test023.sol b/framework/src/test/resources/soliditycode_0.5.15/Create2Test023.sol new file mode 100644 index 00000000000..4c3f8af9f2b --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/Create2Test023.sol @@ -0,0 +1,31 @@ +contract factory { + constructor() payable public { + } + + function deploy(bytes memory code, uint256 salt) public returns(address){ + Caller addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + return address(addr); + } + + function testCreate() payable public returns (address){ + Caller add = (new Caller).value(0)(); + return address(add); + } + + function kill( ) payable public{ + selfdestruct(msg.sender); + } +} + + + +contract Caller { + constructor() payable public {} + function test() payable public returns (uint256){return 1;} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/Create2Test024.sol b/framework/src/test/resources/soliditycode_0.5.15/Create2Test024.sol new file mode 100644 index 00000000000..f5a9d032cff --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/Create2Test024.sol @@ -0,0 +1,56 @@ +contract Factory { + event Deployed(address addr, uint256 salt, address sender); + function deploy(bytes memory code, uint256 salt) public returns(address){ + TestConstract addr; + TestConstract addr1; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + + addr.testSuicideNonexistentTarget(msg.sender); + addr.set(); + emit Deployed(address(addr), salt, msg.sender); + return address(addr); + } + + function deploy2(bytes memory code, uint256 salt) public returns(address){ + TestConstract addr; + TestConstract addr1; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + + //addr.testSuicideNonexistentTarget(msg.sender); + //addr.set(); + + assembly { + addr1 := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed(address(addr), salt, msg.sender); + return address(addr); + } +} + + + +contract TestConstract { + uint public i=1; + constructor () public { + } + + function set() public{ + i=9; + } + function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { + selfdestruct(nonexistentTarget); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/Create2Test025.sol b/framework/src/test/resources/soliditycode_0.5.15/Create2Test025.sol new file mode 100644 index 00000000000..895dc43e56f --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/Create2Test025.sol @@ -0,0 +1,34 @@ +contract Factory { + event Deployed(address addr, uint256 salt, address sender); + constructor() public { + } + + function create2(bytes memory code, uint256 salt) public returns(address){ + address addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed(addr, salt, msg.sender); + return addr; + } + + function get(bytes1 prefix, bytes calldata code, uint256 salt) external view returns(address) { + //bytes32 hash = keccak256(abi.encodePacked(bytes1(0x41),address(this), salt, keccak256(code))); + bytes32 hash = keccak256(abi.encodePacked(prefix,address(this), salt, keccak256(code))); + address addr = address(uint160(uint256(hash))); + return addr; + } +} + +contract TestContract{ + uint256 public num; + constructor(uint256 j) public{ + num = j; + } + function getNum() public returns (uint256){ + return num; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/ExtCodeHashTest010.sol b/framework/src/test/resources/soliditycode_0.5.15/ExtCodeHashTest010.sol new file mode 100644 index 00000000000..bfa8a7fa0d8 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/ExtCodeHashTest010.sol @@ -0,0 +1,46 @@ +contract Counter { + uint count = 0; + address payable owner; + event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); + constructor() public{ + owner = msg.sender; + } + function getCodeHashSuicide(address addr) public returns (bytes32 _hashBefore){ + assembly{ + _hashBefore := extcodehash(addr) + } + selfdestruct(owner); + return _hashBefore; + } + + function getCodeHashRevert() public returns (bytes32 _hashBefore, bytes32 _hashAfter) { + address addr = address(this); + assembly { + _hashBefore := extcodehash(addr) + } + if (owner == msg.sender) { + selfdestruct(owner); + } + assembly { + _hashAfter := extcodehash(addr) + } + revert(); + emit LogResult(_hashBefore, _hashAfter); + } + + function getCodeHashCreate() public returns (bytes32 _hashBefore){ + TestContract A = (new TestContract).value(0)(); + address addr = address(A); + assembly{ + _hashBefore := extcodehash(addr) + } + revert(); + return _hashBefore; + } +} + +contract TestContract{ + uint256 count = 1; + constructor() public payable{ + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/ParentTypeBug.sol b/framework/src/test/resources/soliditycode_0.5.15/ParentTypeBug.sol new file mode 100644 index 00000000000..897c843ae24 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/ParentTypeBug.sol @@ -0,0 +1,13 @@ +contract Parent { + uint256 public m_aMember; + address public m_bMember; +} +contract Child is Parent { + function foo() public view returns (uint256) { return Parent.m_aMember; } + function bar() public view returns (address) { return Parent.m_bMember; } + + // complie failed + // function foo() public pure returns (uint256) { return Parent.m_aMember; } + // function bar() public pure returns (address) { return Parent.m_bMember; } + +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/SafeMath.sol b/framework/src/test/resources/soliditycode_0.5.15/SafeMath.sol new file mode 100644 index 00000000000..b154b8b81b5 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/SafeMath.sol @@ -0,0 +1,149 @@ +pragma solidity ^0.5.8; + +/** + * @dev Wrappers over Solidity's arithmetic operations with added overflow + * checks. + * + * Arithmetic operations in Solidity wrap on overflow. This can easily result + * in bugs, because programmers usually assume that an overflow raises an + * error, which is the standard behavior in high level programming languages. + * `SafeMath` restores this intuition by reverting the transaction when an + * operation overflows. + * + * Using this library instead of the unchecked operations eliminates an entire + * class of bugs, so it's recommended to use it always. + */ +library SafeMath { + /** + * @dev Returns the addition of two unsigned integers, reverting on + * overflow. + * + * Counterpart to Solidity's `+` operator. + * + * Requirements: + * - Addition cannot overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a, "SafeMath: addition overflow"); + + return c; + } + + /** + * @dev Returns the subtraction of two unsigned integers, reverting on + * overflow (when the result is negative). + * + * Counterpart to Solidity's `-` operator. + * + * Requirements: + * - Subtraction cannot overflow. + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + return sub(a, b, "SafeMath: subtraction overflow"); + } + + /** + * @dev Returns the subtraction of two unsigned integers, reverting with custom message on + * overflow (when the result is negative). + * + * Counterpart to Solidity's `-` operator. + * + * Requirements: + * - Subtraction cannot overflow. + */ + function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { + require(b <= a, errorMessage); + uint256 c = a - b; + + return c; + } + + /** + * @dev Returns the multiplication of two unsigned integers, reverting on + * overflow. + * + * Counterpart to Solidity's `*` operator. + * + * Requirements: + * - Multiplication cannot overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + // Gas optimization: this is cheaper than requiring 'a' not being zero, but the + // benefit is lost if 'b' is also tested. + // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 + if (a == 0) { + return 0; + } + + uint256 c = a * b; + require(c / a == b, "SafeMath: multiplication overflow"); + + return c; + } + + /** + * @dev Returns the integer division of two unsigned integers. Reverts on + * division by zero. The result is rounded towards zero. + * + * Counterpart to Solidity's `/` operator. Note: this function uses a + * `revert` opcode (which leaves remaining gas untouched) while Solidity + * uses an invalid opcode to revert (consuming all remaining gas). + * + * Requirements: + * - The divisor cannot be zero. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + return div(a, b, "SafeMath: division by zero"); + } + + /** + * @dev Returns the integer division of two unsigned integers. Reverts with custom message on + * division by zero. The result is rounded towards zero. + * + * Counterpart to Solidity's `/` operator. Note: this function uses a + * `revert` opcode (which leaves remaining gas untouched) while Solidity + * uses an invalid opcode to revert (consuming all remaining gas). + * + * Requirements: + * - The divisor cannot be zero. + */ + function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { + require(b > 0, errorMessage); + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + + return c; + } + + /** + * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), + * Reverts when dividing by zero. + * + * Counterpart to Solidity's `%` operator. This function uses a `revert` + * opcode (which leaves remaining gas untouched) while Solidity uses an + * invalid opcode to revert (consuming all remaining gas). + * + * Requirements: + * - The divisor cannot be zero. + */ + function mod(uint256 a, uint256 b) internal pure returns (uint256) { + return mod(a, b, "SafeMath: modulo by zero"); + } + + /** + * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), + * Reverts with custom message when dividing by zero. + * + * Counterpart to Solidity's `%` operator. This function uses a `revert` + * opcode (which leaves remaining gas untouched) while Solidity uses an + * invalid opcode to revert (consuming all remaining gas). + * + * Requirements: + * - The divisor cannot be zero. + */ + function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { + require(b != 0, errorMessage); + return a % b; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/ShiftCommand001.sol b/framework/src/test/resources/soliditycode_0.5.15/ShiftCommand001.sol new file mode 100644 index 00000000000..574ee2b571b --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/ShiftCommand001.sol @@ -0,0 +1,18 @@ +contract TestBitwiseShift { + + function shlTest(uint256 num, uint256 input) public returns (bytes32 out) { + assembly { + out := shl(num, input) + } + } + function shrTest(uint256 num, uint256 input) public returns (bytes32 out) { + assembly { + out := shr(num, input) + } + } + function sarTest(uint256 num, uint256 input) public returns (bytes32 out) { + assembly { + out := sar(num, input) + } + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/SolidityMappingFix.sol b/framework/src/test/resources/soliditycode_0.5.15/SolidityMappingFix.sol new file mode 100644 index 00000000000..67692d3b4ae --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/SolidityMappingFix.sol @@ -0,0 +1,9 @@ +pragma experimental ABIEncoderV2; +contract Tests { + mapping(address => uint) public balances; + function update(uint256 amount) public returns (address addr) + { + balances[msg.sender] = amount; + return msg.sender; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TestMappings_array_pop.sol b/framework/src/test/resources/soliditycode_0.5.15/TestMappings_array_pop.sol new file mode 100644 index 00000000000..3ceac916049 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TestMappings_array_pop.sol @@ -0,0 +1,19 @@ +contract C { + mapping (uint256 => uint256)[] a; + + function n1(uint256 key, uint256 value) public { + a.length++; + a[a.length - 1][key] = value; + } + + + + function map(uint256 key) public view returns (uint) { + return a[a.length - 1][key]; + } + + function p() public { + a.pop(); + } +} + diff --git a/framework/src/test/resources/soliditycode_0.5.15/TransferFailed001.sol b/framework/src/test/resources/soliditycode_0.5.15/TransferFailed001.sol new file mode 100644 index 00000000000..dba043edcb3 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TransferFailed001.sol @@ -0,0 +1,147 @@ +contract EnergyOfTransferFailedTest { + constructor() payable public { + + } + + function testTransferTokenCompiledLongMax() payable public{ + address(0x1).transferToken(1,9223372036855775827); + } + + function testTransferTokenCompiled() payable public{ + address(0x1).transferToken(1,1); + } + + function testTransferTokenCompiledLongMin() payable public{ + //address(0x1).transferToken(1,-9223372036855775828); + } + + function testTransferTokenCompiledLongMin1() payable public returns(uint256){ + return address(0x2).tokenBalance(trcToken(-9223372036855775828)); + } + + function testTransferTokenCompiled1() payable public returns(uint256){ + return address(0x1).tokenBalance(trcToken(1)); + } + + function testTransferTokenCompiledLongMax1() payable public returns(uint256){ + return address(0x2).tokenBalance(trcToken(9223372036855775827)); + } + + function testTransferTokenCompiledTokenId(uint256 tokenid) payable public returns(uint256){ + return address(0x1).tokenBalance(trcToken(tokenid)); + } + + function testTransferTokenTest(address addr ,uint256 tokenid) payable public returns(uint256){ + return addr.tokenBalance(trcToken(tokenid)); + } + + // InsufficientBalance + function testTransferTrxInsufficientBalance(uint256 i) payable public{ + msg.sender.transfer(i); + } + + function testSendTrxInsufficientBalance(uint256 i) payable public{ + msg.sender.send(i); + } + + function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ + msg.sender.transferToken(i, tokenId); + } + + function testCallTrxInsufficientBalance(uint256 i,address payable caller) public { + caller.call.value(i)(abi.encodeWithSignature("test()")); + } + + function testCreateTrxInsufficientBalance(uint256 i) payable public { + (new Caller).value(i)(); + } + + // NonexistentTarget + + function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { + nonexistentTarget.send(i); + } + + function testSendTrxRevert(uint256 i,address payable nonexistentTarget) payable public { + nonexistentTarget.send(i); + revert(); + } + + function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { + nonexistentTarget.transfer(i); + } + + function testTransferTrxrevert(uint256 i,address payable nonexistentTarget) payable public{ + nonexistentTarget.transfer(i); + revert(); + } + + function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { + nonexistentTarget.transferToken(i, tokenId); + } + + function testTransferTokenRevert(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { + nonexistentTarget.transferToken(i, tokenId); + revert(); + } + + function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { + nonexistentTarget.call.value(i)(abi.encodeWithSignature("test()")); + } + + function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { + selfdestruct(nonexistentTarget); + } + + function testSuicideRevert(address payable nonexistentTarget) payable public { + selfdestruct(nonexistentTarget); + revert(); + } + + // target is self + function testTransferTrxSelf(uint256 i) payable public{ + address payable self = address(uint160(address(this))); + self.transfer(i); + } + + function testSendTrxSelf(uint256 i) payable public{ + address payable self = address(uint160(address(this))); + self.send(i); + } + + function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ + address payable self = address(uint160(address(this))); + self.transferToken(i, tokenId); + } + + event Deployed(address addr, uint256 salt, address sender); + function deploy(bytes memory code, uint256 salt) public returns(address){ + address addr; + assembly { + addr := create2(10, add(code, 0x20), mload(code), salt) + //if iszero(extcodesize(addr)) { + // revert(0, 0) + //} + } + //emit Deployed(addr, salt, msg.sender); + return addr; + } + function deploy2(bytes memory code, uint256 salt) public returns(address){ + address addr; + assembly { + addr := create2(300, add(code, 0x20), mload(code), salt) + //if iszero(extcodesize(addr)) { + // revert(0, 0) + //} + } + //emit Deployed(addr, salt, msg.sender); + return addr; + } +} + + + +contract Caller { + constructor() payable public {} + function test() payable public {} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TransferFailed005.sol b/framework/src/test/resources/soliditycode_0.5.15/TransferFailed005.sol new file mode 100644 index 00000000000..aa39aafa152 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TransferFailed005.sol @@ -0,0 +1,90 @@ +contract EnergyOfTransferFailedTest { + constructor() payable public { + + } + // InsufficientBalance + function testTransferTrxInsufficientBalance(uint256 i) payable public{ + msg.sender.transfer(i); + } + + function testSendTrxInsufficientBalance(uint256 i) payable public{ + msg.sender.send(i); + } + + function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ + msg.sender.transferToken(i, tokenId); + } + + function testCallTrxInsufficientBalance(uint256 i,address payable caller) public returns (bool,bytes memory){ + return caller.call.value(i)(abi.encodeWithSignature("test()")); + } + + function testCreateTrxInsufficientBalance(uint256 i) payable public { + (new Caller).value(i)(); + } + + // NonexistentTarget + + function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { + require(address(this).balance >= i); + nonexistentTarget.send(i); + } + + function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { + require(address(this).balance >= i); + nonexistentTarget.transfer(i); + } + + function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { + require(address(this).balance >= i); + nonexistentTarget.transferToken(i, tokenId); + } + + function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { + require(address(this).balance >= i); + nonexistentTarget.call.value(i)(abi.encodeWithSignature("test()")); + } + + function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { + selfdestruct(nonexistentTarget); + } + + // target is self + function testTransferTrxSelf(uint256 i) payable public{ + require(address(this).balance >= i); + address payable self = address(uint160(address(this))); + self.transfer(i); + } + + function testSendTrxSelf(uint256 i) payable public{ + require(address(this).balance >= i); + address payable self = address(uint160(address(this))); + self.send(i); + } + + function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ + require(address(this).balance >= i); + address payable self = address(uint160(address(this))); + self.transferToken(i, tokenId); + } + + event Deployed(address addr, uint256 salt, address sender); + function deploy(bytes memory code, uint256 salt) public returns(address){ + address addr; + assembly { + addr := create2(10, add(code, 0x20), mload(code), salt) + //if iszero(extcodesize(addr)) { + // revert(0, 0) + //} + } + //emit Deployed(addr, salt, msg.sender); + return addr; + } +} + + + +contract Caller { + constructor() payable public {} + function test() payable public returns (uint256 ){return 1;} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TransferFailed006.sol b/framework/src/test/resources/soliditycode_0.5.15/TransferFailed006.sol new file mode 100644 index 00000000000..aa39aafa152 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TransferFailed006.sol @@ -0,0 +1,90 @@ +contract EnergyOfTransferFailedTest { + constructor() payable public { + + } + // InsufficientBalance + function testTransferTrxInsufficientBalance(uint256 i) payable public{ + msg.sender.transfer(i); + } + + function testSendTrxInsufficientBalance(uint256 i) payable public{ + msg.sender.send(i); + } + + function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ + msg.sender.transferToken(i, tokenId); + } + + function testCallTrxInsufficientBalance(uint256 i,address payable caller) public returns (bool,bytes memory){ + return caller.call.value(i)(abi.encodeWithSignature("test()")); + } + + function testCreateTrxInsufficientBalance(uint256 i) payable public { + (new Caller).value(i)(); + } + + // NonexistentTarget + + function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { + require(address(this).balance >= i); + nonexistentTarget.send(i); + } + + function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { + require(address(this).balance >= i); + nonexistentTarget.transfer(i); + } + + function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { + require(address(this).balance >= i); + nonexistentTarget.transferToken(i, tokenId); + } + + function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { + require(address(this).balance >= i); + nonexistentTarget.call.value(i)(abi.encodeWithSignature("test()")); + } + + function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { + selfdestruct(nonexistentTarget); + } + + // target is self + function testTransferTrxSelf(uint256 i) payable public{ + require(address(this).balance >= i); + address payable self = address(uint160(address(this))); + self.transfer(i); + } + + function testSendTrxSelf(uint256 i) payable public{ + require(address(this).balance >= i); + address payable self = address(uint160(address(this))); + self.send(i); + } + + function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ + require(address(this).balance >= i); + address payable self = address(uint160(address(this))); + self.transferToken(i, tokenId); + } + + event Deployed(address addr, uint256 salt, address sender); + function deploy(bytes memory code, uint256 salt) public returns(address){ + address addr; + assembly { + addr := create2(10, add(code, 0x20), mload(code), salt) + //if iszero(extcodesize(addr)) { + // revert(0, 0) + //} + } + //emit Deployed(addr, salt, msg.sender); + return addr; + } +} + + + +contract Caller { + constructor() payable public {} + function test() payable public returns (uint256 ){return 1;} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TransferFailed007.sol b/framework/src/test/resources/soliditycode_0.5.15/TransferFailed007.sol new file mode 100644 index 00000000000..aa39aafa152 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TransferFailed007.sol @@ -0,0 +1,90 @@ +contract EnergyOfTransferFailedTest { + constructor() payable public { + + } + // InsufficientBalance + function testTransferTrxInsufficientBalance(uint256 i) payable public{ + msg.sender.transfer(i); + } + + function testSendTrxInsufficientBalance(uint256 i) payable public{ + msg.sender.send(i); + } + + function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ + msg.sender.transferToken(i, tokenId); + } + + function testCallTrxInsufficientBalance(uint256 i,address payable caller) public returns (bool,bytes memory){ + return caller.call.value(i)(abi.encodeWithSignature("test()")); + } + + function testCreateTrxInsufficientBalance(uint256 i) payable public { + (new Caller).value(i)(); + } + + // NonexistentTarget + + function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { + require(address(this).balance >= i); + nonexistentTarget.send(i); + } + + function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { + require(address(this).balance >= i); + nonexistentTarget.transfer(i); + } + + function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { + require(address(this).balance >= i); + nonexistentTarget.transferToken(i, tokenId); + } + + function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { + require(address(this).balance >= i); + nonexistentTarget.call.value(i)(abi.encodeWithSignature("test()")); + } + + function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { + selfdestruct(nonexistentTarget); + } + + // target is self + function testTransferTrxSelf(uint256 i) payable public{ + require(address(this).balance >= i); + address payable self = address(uint160(address(this))); + self.transfer(i); + } + + function testSendTrxSelf(uint256 i) payable public{ + require(address(this).balance >= i); + address payable self = address(uint160(address(this))); + self.send(i); + } + + function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ + require(address(this).balance >= i); + address payable self = address(uint160(address(this))); + self.transferToken(i, tokenId); + } + + event Deployed(address addr, uint256 salt, address sender); + function deploy(bytes memory code, uint256 salt) public returns(address){ + address addr; + assembly { + addr := create2(10, add(code, 0x20), mload(code), salt) + //if iszero(extcodesize(addr)) { + // revert(0, 0) + //} + } + //emit Deployed(addr, salt, msg.sender); + return addr; + } +} + + + +contract Caller { + constructor() payable public {} + function test() payable public returns (uint256 ){return 1;} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant001.sol b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant001.sol new file mode 100644 index 00000000000..515b9e07724 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant001.sol @@ -0,0 +1,28 @@ +//pragma solidity ^0.4.0; + +contract testConstantContract{ + uint256 public i; + function testPayable() public payable returns (uint256 z) { + i=1; + z=i; + return z; + } + function testNoPayable() public returns (uint256 z) { + i=1; + z=i; + return z; + } + function testView() public view returns (uint256 z) { + uint256 i=1; + return i; + } + function testPure() public pure returns (uint256 z) { + uint256 i=1; + return i; + } + function testView2() public view returns (uint256 z) { + uint256 i=1; + revert(); + return i; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant002.sol b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant002.sol new file mode 100644 index 00000000000..44332e58c51 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant002.sol @@ -0,0 +1,10 @@ +//pragma solidity ^0.4.0; + +contract testConstantContract{ + uint256 public i; + function testNoPayable() public returns (uint256 z) { + i=1; + z=i; + return z; + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant003.sol b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant003.sol new file mode 100644 index 00000000000..03e29fb76b6 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant003.sol @@ -0,0 +1,18 @@ +//pragma solidity ^0.4.0; + +contract testConstantContract{ + function testView() public view returns (uint256 z) { + uint256 i=1; + return i; + } + + function testPure() public pure returns (uint256 z) { + uint256 i=1; + return i; + } + + function testPayable() public payable returns (uint256 z) { + uint256 i=1; + return i; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant004.sol b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant004.sol new file mode 100644 index 00000000000..fce77178ca7 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant004.sol @@ -0,0 +1,8 @@ +//pragma solidity ^0.4.0; + +contract testConstantContract{ +function testPure() public pure returns (uint256 z) { +uint256 i=1; +return i; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant015.sol b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant015.sol new file mode 100644 index 00000000000..d926c43c824 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant015.sol @@ -0,0 +1,24 @@ +contract Factory { + event Deployed(address addr, uint256 salt, address sender); + function deploy(bytes memory code, uint256 salt) public returns(address){ + address addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed(addr, salt, msg.sender); + return addr; + } +} + + + +contract TestConstract { + constructor () public { + } + function plusOne() public returns(uint){ + return 1; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant024.sol b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant024.sol new file mode 100644 index 00000000000..287b0fc9782 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant024.sol @@ -0,0 +1,9 @@ +//pragma solidity ^0.4.0; + +contract testConstantContract{ +function testView() public view returns (uint256 z) { +uint256 i=1; +revert(); +return i; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract.sol new file mode 100644 index 00000000000..4266b9e92ca --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract.sol @@ -0,0 +1,15 @@ +contract testIsContract{ +bool public isContrct; +constructor () public { + isContrct = address(this).isContract; +} +function testIsContractCommand(address a) public returns (bool) { +return (a.isContract); +} +function selfdestructContract(address payable a) public { + selfdestruct(a); +} +function testConstructor() public returns(bool){ + return isContrct; +} +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract001.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract001.sol new file mode 100644 index 00000000000..77aae930b59 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract001.sol @@ -0,0 +1,24 @@ +contract testIsContract{ +bool public isContrct; +constructor () public { + isContrct = address(this).isContract; +} +function testIsContractCommand(address a) public returns (bool) { +return (a.isContract); +} + +function testIsContractView(address a) view public returns (bool) { +return (a.isContract); +} + +function selfdestructContract(address payable a) public { + selfdestruct(a); +} +function testConstructor() public returns(bool){ + return isContrct; +} + +function testConstructorView() public view returns(bool){ + return isContrct; +} +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract002.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract002.sol new file mode 100644 index 00000000000..2fe474fd98c --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract002.sol @@ -0,0 +1,5 @@ +contract testIsContract{ +function testIsContractCommand(address a) public returns (bool) { +return (a.isContract); +} +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand043.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand043.sol new file mode 100644 index 00000000000..04d9f7dde28 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand043.sol @@ -0,0 +1,18 @@ +contract TestBitwiseShift { + + function shlTest(int256 num, int256 input) public returns (bytes32 out) { + assembly { + out := shl(num, input) + } + } + function shrTest(int256 num, int256 input) public returns (bytes32 out) { + assembly { + out := shr(num, input) + } + } + function sarTest(int256 num, int256 input) public returns (bytes32 out) { + assembly { + out := sar(num, input) + } + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand103.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand103.sol new file mode 100644 index 00000000000..7ad130c87c6 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand103.sol @@ -0,0 +1,8 @@ +//pragma solidity ^0.4.0; + +contract testConstantContract{ +function testView() public constant returns (uint256 z) { +uint256 i=1; +return i; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand107.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand107.sol new file mode 100644 index 00000000000..4dcd33ad7b0 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand107.sol @@ -0,0 +1,9 @@ +//pragma solidity ^0.4.0; + + contract testConstantContract{ + int256 public i; + function testPayable() public returns (int z) { + z=1+1; + return z; + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand108.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand108.sol new file mode 100644 index 00000000000..b44d5c82731 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand108.sol @@ -0,0 +1,7 @@ +//pragma solidity ^0.4.0; + + contract testConstantContract{ + function test() pure public returns (int z) { + return 1; + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand109.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand109.sol new file mode 100644 index 00000000000..864f01f7fb4 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand109.sol @@ -0,0 +1,7 @@ +//pragma solidity ^0.4.0; + + contract testConstantContract{ + function test() view public returns (int z) { + return 1; + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmOldCommand001.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmOldCommand001.sol new file mode 100644 index 00000000000..9f3cf079ea1 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/TvmOldCommand001.sol @@ -0,0 +1,11 @@ +//pragma solidity ^0.4.0; + +contract binaryRightContract{ + function binaryMoveR(int i)public returns (int z) { + return z = 5 >> i; + } + function binaryLiftR(int i)public returns (int z) { + return z = 5 << i; + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/VerifyBurnProof001.sol b/framework/src/test/resources/soliditycode_0.5.15/VerifyBurnProof001.sol new file mode 100644 index 00000000000..4173e84de23 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/VerifyBurnProof001.sol @@ -0,0 +1,20 @@ + +contract VerifyBurnProof001Test { + // verifyBurnProof(bytes32[10],bytes32[2],uint64,bytes32[2],bytes32) + // size = 512 + // + + function VerifyBurnProofSize001(bytes32[10] memory output, bytes32[2] memory spendAuthoritySignature, uint64 value, bytes32[2] memory bindingSignature,bytes32 signHash) public returns (bool){ + return verifyBurnProof(output, spendAuthoritySignature, value, bindingSignature, signHash); + } + + function VerifyBurnProofSize002(bytes memory data) public returns (bool, bytes memory){ + // bytes memory empty = ""; + return address(0x1000003).delegatecall(data); + } + + function VerifyBurnProofSize003() public returns (bool, bytes memory){ + bytes memory empty = ""; + return address(0x1000003).delegatecall(empty); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/VerifyMintProof001.sol b/framework/src/test/resources/soliditycode_0.5.15/VerifyMintProof001.sol new file mode 100644 index 00000000000..cb0812c2ef5 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/VerifyMintProof001.sol @@ -0,0 +1,33 @@ + +contract VerifyMintProof001Test { + // verifyMintProof(bytes32[9],bytes32[2],uint64,bytes32,bytes32[33],uint256) + + function VerifyMintProofSize001(bytes32[9] memory output, bytes32[2] memory bindingSignature, uint64 value, bytes32 signHash, bytes32[33] memory frontier,uint256 leafCount) public returns (bytes32[] memory){ + return verifyMintProof(output, bindingSignature, value, signHash, frontier, leafCount); + } + + function VerifyMintProofSize002(bytes memory data) public returns (bool, bytes memory){ +// address verifyMint = address (0x1000001); +// +// assembly { +// let succeeded := delegatecall(sub(gas, 5000), verifyMint, add(data, 0x20), mload(data), 0, 0) +// let size := returndatasize +// let response := mload(0x40) +// mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))) +// mstore(response, size) +// returndatacopy(add(response, 0x20), 0, size) +// switch iszero(succeeded) +// case 1 { +// // throw if delegatecall failed +// revert(add(response, 0x20), size) +// } +// } + + return address(0x1000001).delegatecall(data); + } + + function VerifyMintProofSize003() public returns (bool, bytes memory){ + bytes memory empty = ""; + return address(0x1000001).call(empty); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/abiencode.sol b/framework/src/test/resources/soliditycode_0.5.15/abiencode.sol new file mode 100644 index 00000000000..38fad3454d6 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/abiencode.sol @@ -0,0 +1,16 @@ +pragma experimental ABIEncoderV2; + +// tests encoding from storage arrays + +contract AbiEncode { + int256[2][] tmp_h; + function h(int256[2][] calldata s) external returns (bytes memory) { + tmp_h = s; + return abi.encode(tmp_h); + } + int256[2][2] tmp_i; + function i(int256[2][2] calldata s) external returns (bytes memory) { + tmp_i = s; + return abi.encode(tmp_i); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addMsg001Nonpayable.sol b/framework/src/test/resources/soliditycode_0.5.15/addMsg001Nonpayable.sol new file mode 100644 index 00000000000..d1294f2336a --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/addMsg001Nonpayable.sol @@ -0,0 +1,20 @@ +//pragma solidity ^0.4.24; + +contract IllegalDecorate { + +event log(uint256); +constructor() payable public{} + +function() payable external{} + +function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue)public { +// function transferTokenWithValue(address toAddress, uint256 tokenValue) payable public { +emit log(msg.value); +emit log(msg.tokenvalue); +emit log(msg.tokenid); +toAddress.transferToken(msg.tokenvalue, msg.tokenid); +toAddress.transfer(msg.value); + +} + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addMsg002View.sol b/framework/src/test/resources/soliditycode_0.5.15/addMsg002View.sol new file mode 100644 index 00000000000..423bb68e3ed --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/addMsg002View.sol @@ -0,0 +1,20 @@ +//pragma solidity ^0.4.24; + +contract IllegalDecorate { + +constructor() payable public{} + +function() payable external{} + +event log(uint256); + +function transferTokenWithView(address payable toAddress, uint256 tokenValue) public view{ +emit log(msg.value); +emit log(msg.tokenvalue); +emit log(msg.tokenid); +toAddress.transferToken(msg.tokenvalue, msg.tokenid); +toAddress.transfer(msg.value); +} + +} + diff --git a/framework/src/test/resources/soliditycode_0.5.15/addMsg003Constant.sol b/framework/src/test/resources/soliditycode_0.5.15/addMsg003Constant.sol new file mode 100644 index 00000000000..0f0ab7553e0 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/addMsg003Constant.sol @@ -0,0 +1,19 @@ +//pragma solidity ^0.4.24; + +contract IllegalDecorate { + +constructor() payable public{} + +function() payable external{} + +event log(uint256); + +function transferTokenWithConstant(address payable toAddress, uint256 tokenValue) public constant{ +emit log(msg.value); +emit log(msg.tokenvalue); +emit log(msg.tokenid); +toAddress.transferToken(msg.tokenvalue, msg.tokenid); +toAddress.transfer(msg.value); +} + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addMsg004Pure.sol b/framework/src/test/resources/soliditycode_0.5.15/addMsg004Pure.sol new file mode 100644 index 00000000000..b5d3a4e4aee --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/addMsg004Pure.sol @@ -0,0 +1,19 @@ +//pragma solidity ^0.4.24; + +contract IllegalDecorate { + +constructor() payable public{} + +function() payable external{} + +event log(uint256); + +function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public pure{ +emit log(msg.value); +emit log(msg.tokenvalue); +emit log(msg.tokenid); +toAddress.transferToken(msg.tokenvalue, msg.tokenid); +toAddress.transfer(msg.value); +} + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addTransferToken001Nonpayable.sol b/framework/src/test/resources/soliditycode_0.5.15/addTransferToken001Nonpayable.sol new file mode 100644 index 00000000000..c8d0dcc7560 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/addTransferToken001Nonpayable.sol @@ -0,0 +1,13 @@ +//pragma solidity ^0.4.24; + + contract IllegalDecorate { + + constructor() payable public{} + + function() payable external{} + + function transferTokenWithOutPayable(address payable toAddress,trcToken id, uint256 tokenValue)public { + + toAddress.transferToken(tokenValue, id); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addTransferToken001payable.sol b/framework/src/test/resources/soliditycode_0.5.15/addTransferToken001payable.sol new file mode 100644 index 00000000000..803d66ad75e --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/addTransferToken001payable.sol @@ -0,0 +1,13 @@ +//pragma solidity ^0.4.24; + + contract IllegalDecorate { + + constructor() payable public{} + + function() payable external{} + + function transferTokenWithOutPayable(address payable toAddress,trcToken id, uint256 tokenValue) public payable{ + + toAddress.transferToken(tokenValue, id); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addTransferToken002View.sol b/framework/src/test/resources/soliditycode_0.5.15/addTransferToken002View.sol new file mode 100644 index 00000000000..109f46386ce --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/addTransferToken002View.sol @@ -0,0 +1,15 @@ +//pragma solidity ^0.4.24; + +contract IllegalDecorate { + + constructor() payable public{} + + function() payable external{} + + function transferTokenWithView(address payable toAddress,trcToken id, uint256 tokenValue) public view{ + + toAddress.transferToken(tokenValue, id); + + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addTransferToken003Constant.sol b/framework/src/test/resources/soliditycode_0.5.15/addTransferToken003Constant.sol new file mode 100644 index 00000000000..fb1a2cbbbb4 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/addTransferToken003Constant.sol @@ -0,0 +1,15 @@ +//pragma solidity ^0.4.24; + +contract IllegalDecorate { + + constructor() payable public{} + + function() payable external{} + + function transferTokenWithConstant(address payable toAddress, uint256 tokenValue) public constant{ + + toAddress.transferToken(tokenValue, 0x6e6d62); + + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addTransferToken004Pure.sol b/framework/src/test/resources/soliditycode_0.5.15/addTransferToken004Pure.sol new file mode 100644 index 00000000000..7ea2bf0a40b --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/addTransferToken004Pure.sol @@ -0,0 +1,15 @@ +//pragma solidity ^0.4.24; + +contract IllegalDecorate { + + constructor() payable public{} + + function() payable external{} + + function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public pure{ + + toAddress.transferToken(tokenValue, 0x6e6d62); + + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addTrcToken001Assemble.sol b/framework/src/test/resources/soliditycode_0.5.15/addTrcToken001Assemble.sol new file mode 100644 index 00000000000..a93d9046a3f --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/addTrcToken001Assemble.sol @@ -0,0 +1,62 @@ +//pragma solidity ^0.4.24; + +contract InAssemble { + +mapping(trcToken => uint256) tokenCnt; +mapping(uint256 => mapping(trcToken => trcToken)) cntTokenToken; +constructor () payable public {} +function getBalance (address addr) view public returns(uint256 r) { +assembly{ +r := balance(addr) +} +} + +function getTokenBalanceConstant (address addr, trcToken tokenId) view public returns(uint256 r) { +assembly{ +r := tokenbalance(tokenId, addr) +} +} + +function getTokenBalance (address addr, trcToken tokenId) public returns(uint256 r) { +assembly{ +r := tokenbalance(tokenId, addr) +} +} + +function transferTokenInAssembly(address addr, trcToken tokenId, uint256 tokenValue) public payable { +bytes4 sig = bytes4(keccak256("()")); // function signature + +assembly { +let x := mload(0x40) // get empty storage location +mstore(x,sig) // 4 bytes - place signature in empty storage + +let ret := calltoken(gas, addr, tokenValue, tokenId, +x, // input +0x04, // input size = 4 bytes +x, // output stored at input location, save space +0x0 // output size = 0 bytes +) + +// let ret := calltoken(gas, addr, tokenValue, +// x, // input +// 0x04, // input size = 4 bytes +// x, // output stored at input location, save space +// 0x0 // output size = 0 bytes +// ) // ERROR + + +mstore(0x40, add(x,0x20)) // update free memory pointer +} + +} + +function trcTokenInMap(trcToken tokenId, uint256 tokenValue) public returns(uint256 r) { +tokenCnt[tokenId] += tokenValue; +r = tokenCnt[tokenId]; +} + +function cntTokenTokenInMap(trcToken tokenId1, trcToken tokenId2, uint256 tokenValue) public returns(trcToken r) { +cntTokenToken[tokenValue][tokenId1] = tokenId2; +r = cntTokenToken[tokenValue][tokenId1]; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addTrcToken002Cat.sol b/framework/src/test/resources/soliditycode_0.5.15/addTrcToken002Cat.sol new file mode 100644 index 00000000000..6d9c169330d --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/addTrcToken002Cat.sol @@ -0,0 +1,2051 @@ +//pragma solidity ^0.4.11; + + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + if (newOwner != address(0)) { + owner = newOwner; + } + } + +} + + + + +/// @title A facet of KittyCore that manages special access privileges. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. +contract KittyAccessControl { + // This facet controls access control for CryptoKitties. There are four roles managed here: + // + // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart + // contracts. It is also the only role that can unpause the smart contract. It is initially + // set to the address that created the smart contract in the KittyCore constructor. + // + // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. + // + // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. + // + // It should be noted that these roles are distinct without overlap in their access abilities, the + // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any + // address to any role, the CEO address itself doesn't have the ability to act in those roles. This + // restriction is intentional so that we aren't tempted to use the CEO address frequently out of + // convenience. The less we use an address, the less likely it is that we somehow compromise the + // account. + + /// @dev Emited when contract is upgraded - See README.md for updgrade plan + event ContractUpgrade(address newContract); + + // The addresses of the accounts (or contracts) that can execute actions within each roles. + address public ceoAddress; + address payable public cfoAddress; + address public cooAddress; + + // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked + bool public paused = false; + + /// @dev Access modifier for CEO-only functionality + modifier onlyCEO() { + require(msg.sender == ceoAddress); + _; + } + + /// @dev Access modifier for CFO-only functionality + modifier onlyCFO() { + require(msg.sender == cfoAddress); + _; + } + + /// @dev Access modifier for COO-only functionality + modifier onlyCOO() { + require(msg.sender == cooAddress); + _; + } + + modifier onlyCLevel() { + require( + msg.sender == cooAddress || + msg.sender == ceoAddress || + msg.sender == cfoAddress + ); + _; + } + + /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. + /// @param _newCEO The address of the new CEO + function setCEO(address _newCEO) external onlyCEO { + require(_newCEO != address(0)); + + ceoAddress = _newCEO; + } + + /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. + /// @param _newCFO The address of the new CFO + function setCFO(address payable _newCFO) external onlyCEO { + require(_newCFO != address(0)); + + cfoAddress = _newCFO; + } + + /// @dev Assigns a new address to act as the COO. Only available to the current CEO. + /// @param _newCOO The address of the new COO + function setCOO(address _newCOO) external onlyCEO { + require(_newCOO != address(0)); + + cooAddress = _newCOO; + } + + /*** Pausable functionality adapted from OpenZeppelin ***/ + + /// @dev Modifier to allow actions only when the contract IS NOT paused + modifier whenNotPaused() { + require(!paused); + _; + } + + /// @dev Modifier to allow actions only when the contract IS paused + modifier whenPaused { + require(paused); + _; + } + + /// @dev Called by any "C-level" role to pause the contract. Used only when + /// a bug or exploit is detected and we need to limit damage. + function pause() external onlyCLevel whenNotPaused { + paused = true; + } + + /// @dev Unpauses the smart contract. Can only be called by the CEO, since + /// one reason we may pause the contract is when CFO or COO accounts are + /// compromised. + /// @notice This is public rather than external so it can be called by + /// derived contracts. + function unpause() public onlyCEO whenPaused { + // can't unpause if contract was upgraded + paused = false; + } +} + + + + +/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. +contract KittyBase is KittyAccessControl { + /*** EVENTS ***/ + + /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously + /// includes any time a cat is created through the giveBirth method, but it is also called + /// when a new gen0 cat is created. + event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); + + /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten + /// ownership is assigned, including births. + event Transfer(address from, address to, uint256 tokenId); + + /*** DATA TYPES ***/ + + /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy + /// of this structure, so great care was taken to ensure that it fits neatly into + /// exactly two 256-bit words. Note that the order of the members in this structure + /// is important because of the byte-packing rules used by Ethereum. + /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html + struct Kitty { + // The Kitty's genetic code is packed into these 256-bits, the format is + // sooper-sekret! A cat's genes never change. + uint256 genes; + + // The timestamp from the block when this cat came into existence. + uint64 birthTime; + + // The minimum timestamp after which this cat can engage in breeding + // activities again. This same timestamp is used for the pregnancy + // timer (for matrons) as well as the siring cooldown. + uint64 cooldownEndBlock; + + // The ID of the parents of this kitty, set to 0 for gen0 cats. + // Note that using 32-bit unsigned integers limits us to a "mere" + // 4 billion cats. This number might seem small until you realize + // that Ethereum currently has a limit of about 500 million + // transactions per year! So, this definitely won't be a problem + // for several years (even as Ethereum learns to scale). + uint32 matronId; + uint32 sireId; + + // Set to the ID of the sire cat for matrons that are pregnant, + // zero otherwise. A non-zero value here is how we know a cat + // is pregnant. Used to retrieve the genetic material for the new + // kitten when the birth transpires. + uint32 siringWithId; + + // Set to the index in the cooldown array (see below) that represents + // the current cooldown duration for this Kitty. This starts at zero + // for gen0 cats, and is initialized to floor(generation/2) for others. + // Incremented by one for each successful breeding action, regardless + // of whether this cat is acting as matron or sire. + uint16 cooldownIndex; + + // The "generation number" of this cat. Cats minted by the CK contract + // for sale are called "gen0" and have a generation number of 0. The + // generation number of all other cats is the larger of the two generation + // numbers of their parents, plus one. + // (i.e. max(matron.generation, sire.generation) + 1) + uint16 generation; + } + + /*** CONSTANTS ***/ + + /// @dev A lookup table indicating the cooldown duration after any successful + /// breeding action, called "pregnancy time" for matrons and "siring cooldown" + /// for sires. Designed such that the cooldown roughly doubles each time a cat + /// is bred, encouraging owners not to just keep breeding the same cat over + /// and over again. Caps out at one week (a cat can breed an unbounded number + /// of times, and the maximum cooldown is always seven days). + uint32[14] public cooldowns = [ + uint32(1 minutes), + uint32(2 minutes), + uint32(5 minutes), + uint32(10 minutes), + uint32(30 minutes), + uint32(1 hours), + uint32(2 hours), + uint32(4 hours), + uint32(8 hours), + uint32(16 hours), + uint32(1 days), + uint32(2 days), + uint32(4 days), + uint32(7 days) + ]; + + // An approximation of currently how many seconds are in between blocks. + uint256 public secondsPerBlock = 15; + + /*** STORAGE ***/ + + /// @dev An array containing the Kitty struct for all Kitties in existence. The ID + /// of each cat is actually an index into this array. Note that ID 0 is a negacat, + /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre + /// creature that is both matron and sire... to itself! Has an invalid genetic code. + /// In other words, cat ID 0 is invalid... ;-) + Kitty[] kitties; + + /// @dev A mapping from cat IDs to the address that owns them. All cats have + /// some valid owner address, even gen0 cats are created with a non-zero owner. + mapping (uint256 => address) public kittyIndexToOwner; + + // @dev A mapping from owner address to count of tokens that address owns. + // Used internally inside balanceOf() to resolve ownership count. + mapping (address => uint256) ownershipTokenCount; + + /// @dev A mapping from KittyIDs to an address that has been approved to call + /// transferFrom(). Each Kitty can only have one approved address for transfer + /// at any time. A zero value means no approval is outstanding. + mapping (uint256 => address) public kittyIndexToApproved; + + /// @dev A mapping from KittyIDs to an address that has been approved to use + /// this Kitty for siring via breedWith(). Each Kitty can only have one approved + /// address for siring at any time. A zero value means no approval is outstanding. + mapping (uint256 => address) public sireAllowedToAddress; + + /// @dev The address of the ClockAuction contract that handles sales of Kitties. This + /// same contract handles both peer-to-peer sales as well as the gen0 sales which are + /// initiated every 15 minutes. + SaleClockAuction public saleAuction; + + /// @dev The address of a custom ClockAuction subclassed contract that handles siring + /// auctions. Needs to be separate from saleAuction because the actions taken on success + /// after a sales and siring auction are quite different. + SiringClockAuction public siringAuction; + + /// @dev Assigns ownership of a specific Kitty to an address. + function _transfer(address _from, address _to, uint256 _tokenId) internal { + // Since the number of kittens is capped to 2^32 we can't overflow this + ownershipTokenCount[_to]++; + // transfer ownership + kittyIndexToOwner[_tokenId] = _to; + // When creating new kittens _from is 0x0, but we can't account that address. + if (_from != address(0)) { + ownershipTokenCount[_from]--; + // once the kitten is transferred also clear sire allowances + delete sireAllowedToAddress[_tokenId]; + // clear any previously approved ownership exchange + delete kittyIndexToApproved[_tokenId]; + } + // Emit the transfer event. + emit Transfer(_from, _to, _tokenId); + } + + /// @dev An internal method that creates a new kitty and stores it. This + /// method doesn't do any checking and should only be called when the + /// input data is known to be valid. Will generate both a Birth event + /// and a Transfer event. + /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) + /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) + /// @param _generation The generation number of this cat, must be computed by caller. + /// @param _genes The kitty's genetic code. + /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) + function _createKitty( + uint256 _matronId, + uint256 _sireId, + uint256 _generation, + uint256 _genes, + address _owner + ) + internal + returns (uint) + { + // These requires are not strictly necessary, our calling code should make + // sure that these conditions are never broken. However! _createKitty() is already + // an expensive call (for storage), and it doesn't hurt to be especially careful + // to ensure our data structures are always valid. + require(_matronId == uint256(uint32(_matronId))); + require(_sireId == uint256(uint32(_sireId))); + require(_generation == uint256(uint16(_generation))); + + // New kitty starts with the same cooldown as parent gen/2 + uint16 cooldownIndex = uint16(_generation / 2); + if (cooldownIndex > 13) { + cooldownIndex = 13; + } + + Kitty memory _kitty = Kitty({ + genes: _genes, + birthTime: uint64(now), + cooldownEndBlock: 0, + matronId: uint32(_matronId), + sireId: uint32(_sireId), + siringWithId: 0, + cooldownIndex: cooldownIndex, + generation: uint16(_generation) + }); + uint256 newKittenId = kitties.push(_kitty) - 1; + + // It's probably never going to happen, 4 billion cats is A LOT, but + // let's just be 100% sure we never let this happen. + require(newKittenId == uint256(uint32(newKittenId))); + + // emit the birth event + emit Birth( + _owner, + newKittenId, + uint256(_kitty.matronId), + uint256(_kitty.sireId), + _kitty.genes + ); + + // This will assign ownership, and also emit the Transfer event as + // per ERC721 draft + _transfer(address(0), _owner, newKittenId); + + return newKittenId; + } + + // Any C-level can fix how many seconds per blocks are currently observed. + function setSecondsPerBlock(uint256 secs) external onlyCLevel { + require(secs < cooldowns[0]); + secondsPerBlock = secs; + } +} + + +/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens +/// @author Dieter Shirley (https://github.com/dete) +contract ERC721 { + // Required methods + function totalSupply() public view returns (uint256 total); + function balanceOf(address _owner) public view returns (uint256 balance); + function ownerOf(uint256 _tokenId) external view returns (address owner); + function approve(address _to, uint256 _tokenId) external; + function transfer(address _to, uint256 _tokenId) external; + function transferFrom(address _from, address _to, uint256 _tokenId) external; + + // Events + event Transfer(address from, address to, uint256 tokenId); + event Approval(address owner, address approved, uint256 tokenId); + + // Optional + // function name() public view returns (string name); + // function symbol() public view returns (string symbol); + // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); + // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); + + // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) + function supportsInterface(bytes4 _interfaceID) external view returns (bool); +} + + +/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 +/// See the KittyCore contract documentation to understand how the various contract facets are arranged. +contract KittyOwnership is ERC721, KittyBase { + + /// @notice Name and symbol of the non fungible token, as defined in ERC721. + string public constant name = "CryptoKitties"; + string public constant symbol = "CK"; + + // The contract that will return kitty metadata + ERC721Metadata public erc721Metadata; + + bytes4 constant InterfaceSignature_ERC165 = + bytes4(keccak256('supportsInterface(bytes4)')); + + bytes4 constant InterfaceSignature_ERC721 = + bytes4(keccak256('name()')) ^ + bytes4(keccak256('symbol()')) ^ + bytes4(keccak256('totalSupply()')) ^ + bytes4(keccak256('balanceOf(address)')) ^ + bytes4(keccak256('ownerOf(uint256)')) ^ + bytes4(keccak256('approve(address,uint256)')) ^ + bytes4(keccak256('transfer(address,uint256)')) ^ + bytes4(keccak256('transferFrom(address,address,uint256)')) ^ + bytes4(keccak256('tokensOfOwner(address)')) ^ + bytes4(keccak256('tokenMetadata(uint256,string)')); + + /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). + /// Returns true for any standardized interfaces implemented by this contract. We implement + /// ERC-165 (obviously!) and ERC-721. + function supportsInterface(bytes4 _interfaceID) external view returns (bool) + { + // DEBUG ONLY + //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); + + return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); + } + + /// @dev Set the address of the sibling contract that tracks metadata. + /// CEO only. + function setMetadataAddress(address _contractAddress) public onlyCEO { + erc721Metadata = ERC721Metadata(_contractAddress); + } + + // Internal utility functions: These functions all assume that their input arguments + // are valid. We leave it to public methods to sanitize their inputs and follow + // the required logic. + + /// @dev Checks if a given address is the current owner of a particular Kitty. + /// @param _claimant the address we are validating against. + /// @param _tokenId kitten id, only valid when > 0 + function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { + return kittyIndexToOwner[_tokenId] == _claimant; + } + + /// @dev Checks if a given address currently has transferApproval for a particular Kitty. + /// @param _claimant the address we are confirming kitten is approved for. + /// @param _tokenId kitten id, only valid when > 0 + function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { + return kittyIndexToApproved[_tokenId] == _claimant; + } + + /// @dev Marks an address as being approved for transferFrom(), overwriting any previous + /// approval. Setting _approved to address(0) clears all transfer approval. + /// NOTE: _approve() does NOT send the Approval event. This is intentional because + /// _approve() and transferFrom() are used together for putting Kitties on auction, and + /// there is no value in spamming the log with Approval events in that case. + function _approve(uint256 _tokenId, address _approved) internal { + kittyIndexToApproved[_tokenId] = _approved; + } + + /// @notice Returns the number of Kitties owned by a specific address. + /// @param _owner The owner address to check. + /// @dev Required for ERC-721 compliance + function balanceOf(address _owner) public view returns (uint256 count) { + return ownershipTokenCount[_owner]; + } + + /// @notice Transfers a Kitty to another address. If transferring to a smart + /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or + /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. + /// @param _to The address of the recipient, can be a user or contract. + /// @param _tokenId The ID of the Kitty to transfer. + /// @dev Required for ERC-721 compliance. + function transfer( + address _to, + uint256 _tokenId + ) + external + whenNotPaused + { + // Safety check to prevent against an unexpected 0x0 default. + require(_to != address(0)); + // Disallow transfers to this contract to prevent accidental misuse. + // The contract should never own any kitties (except very briefly + // after a gen0 cat is created and before it goes on auction). + require(_to != address(this)); + // Disallow transfers to the auction contracts to prevent accidental + // misuse. Auction contracts should only take ownership of kitties + // through the allow + transferFrom flow. + require(_to != address(saleAuction)); + require(_to != address(siringAuction)); + + // You can only send your own cat. + require(_owns(msg.sender, _tokenId)); + + // Reassign ownership, clear pending approvals, emit Transfer event. + _transfer(msg.sender, _to, _tokenId); + } + + /// @notice Grant another address the right to transfer a specific Kitty via + /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. + /// @param _to The address to be granted transfer approval. Pass address(0) to + /// clear all approvals. + /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. + /// @dev Required for ERC-721 compliance. + function approve( + address _to, + uint256 _tokenId + ) + external + whenNotPaused + { + // Only an owner can grant transfer approval. + require(_owns(msg.sender, _tokenId)); + + // Register the approval (replacing any previous approval). + _approve(_tokenId, _to); + + // Emit approval event. + emit Approval(msg.sender, _to, _tokenId); + } + + /// @notice Transfer a Kitty owned by another address, for which the calling address + /// has previously been granted transfer approval by the owner. + /// @param _from The address that owns the Kitty to be transfered. + /// @param _to The address that should take ownership of the Kitty. Can be any address, + /// including the caller. + /// @param _tokenId The ID of the Kitty to be transferred. + /// @dev Required for ERC-721 compliance. + function transferFrom( + address _from, + address _to, + uint256 _tokenId + ) + external + whenNotPaused + { + // Safety check to prevent against an unexpected 0x0 default. + require(_to != address(0)); + // Disallow transfers to this contract to prevent accidental misuse. + // The contract should never own any kitties (except very briefly + // after a gen0 cat is created and before it goes on auction). + require(_to != address(this)); + // Check for approval and valid ownership + require(_approvedFor(msg.sender, _tokenId)); + require(_owns(_from, _tokenId)); + + // Reassign ownership (also clears pending approvals and emits Transfer event). + _transfer(_from, _to, _tokenId); + } + + /// @notice Returns the total number of Kitties currently in existence. + /// @dev Required for ERC-721 compliance. + function totalSupply() public view returns (uint) { + return kitties.length - 1; + } + + /// @notice Returns the address currently assigned ownership of a given Kitty. + /// @dev Required for ERC-721 compliance. + function ownerOf(uint256 _tokenId) + external + view + returns (address owner) + { + owner = kittyIndexToOwner[_tokenId]; + + require(owner != address(0)); + } + + /// @notice Returns a list of all Kitty IDs assigned to an address. + /// @param _owner The owner whose Kitties we are interested in. + /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly + /// expensive (it walks the entire Kitty array looking for cats belonging to owner), + /// but it also returns a dynamic array, which is only supported for web3 calls, and + /// not contract-to-contract calls. + function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { + uint256 tokenCount = balanceOf(_owner); + + if (tokenCount == 0) { + // Return an empty array + return new uint256[](0); + } else { + uint256[] memory result = new uint256[](tokenCount); + uint256 totalCats = totalSupply(); + uint256 resultIndex = 0; + + // We count on the fact that all cats have IDs starting at 1 and increasing + // sequentially up to the totalCat count. + uint256 catId; + + for (catId = 1; catId <= totalCats; catId++) { + if (kittyIndexToOwner[catId] == _owner) { + result[resultIndex] = catId; + resultIndex++; + } + } + + return result; + } + } + + /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) + /// This method is licenced under the Apache License. + /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol + function _memcpy(uint _dest, uint _src, uint _len) private view { + // Copy word-length chunks while possible + for(; _len >= 32; _len -= 32) { + assembly { + mstore(_dest, mload(_src)) + } + _dest += 32; + _src += 32; + } + + // Copy remaining bytes + uint256 mask = 256 ** (32 - _len) - 1; + assembly { + let srcpart := and(mload(_src), not(mask)) + let destpart := and(mload(_dest), mask) + mstore(_dest, or(destpart, srcpart)) + } + } + + /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) + /// This method is licenced under the Apache License. + /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol + function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { + string memory outputString = new string(_stringLength); + uint256 outputPtr; + uint256 bytesPtr; + + assembly { + outputPtr := add(outputString, 32) + bytesPtr := _rawBytes + } + + _memcpy(outputPtr, bytesPtr, _stringLength); + + return outputString; + } + + /// @notice Returns a URI pointing to a metadata package for this token conforming to + /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) + /// @param _tokenId The ID number of the Kitty whose metadata should be returned. + function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { + require( address(erc721Metadata) != address(0)); + bytes32[4] memory buffer; + uint256 count; + (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); + + return _toString(buffer, count); + } +} + + + + +/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. +contract KittyBreeding is KittyOwnership { + + /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy + /// timer begins for the matron. + event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); + + /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards + /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by + /// the COO role as the gas price changes. + uint256 public autoBirthFee = 2 sun; + + // Keeps track of number of pregnant kitties. + uint256 public pregnantKitties; + + /// @dev The address of the sibling contract that is used to implement the sooper-sekret + /// genetic combination algorithm. + GeneScienceInterface public geneScience; + + /// @dev Update the address of the genetic contract, can only be called by the CEO. + /// @param _address An address of a GeneScience contract instance to be used from this point forward. + function setGeneScienceAddress(address _address) external onlyCEO { + GeneScienceInterface candidateContract = GeneScienceInterface(_address); + + // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 + require(candidateContract.isGeneScience()); + + // Set the new contract address + geneScience = candidateContract; + } + + /// @dev Checks that a given kitten is able to breed. Requires that the + /// current cooldown is finished (for sires) and also checks that there is + /// no pending pregnancy. + function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { + // In addition to checking the cooldownEndBlock, we also need to check to see if + // the cat has a pending birth; there can be some period of time between the end + // of the pregnacy timer and the birth event. + return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); + } + + /// @dev Check if a sire has authorized breeding with this matron. True if both sire + /// and matron have the same owner, or if the sire has given siring permission to + /// the matron's owner (via approveSiring()). + function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { + address matronOwner = kittyIndexToOwner[_matronId]; + address sireOwner = kittyIndexToOwner[_sireId]; + + // Siring is okay if they have same owner, or if the matron's owner was given + // permission to breed with this sire. + return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); + } + + /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. + /// Also increments the cooldownIndex (unless it has hit the cap). + /// @param _kitten A reference to the Kitty in storage which needs its timer started. + function _triggerCooldown(Kitty storage _kitten) internal { + // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). + _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); + + // Increment the breeding count, clamping it at 13, which is the length of the + // cooldowns array. We could check the array size dynamically, but hard-coding + // this as a constant saves gas. Yay, Solidity! + if (_kitten.cooldownIndex < 13) { + _kitten.cooldownIndex += 1; + } + } + + /// @notice Grants approval to another user to sire with one of your Kitties. + /// @param _addr The address that will be able to sire with your Kitty. Set to + /// address(0) to clear all siring approvals for this Kitty. + /// @param _sireId A Kitty that you own that _addr will now be able to sire with. + function approveSiring(address _addr, uint256 _sireId) + external + whenNotPaused + { + require(_owns(msg.sender, _sireId)); + sireAllowedToAddress[_sireId] = _addr; + } + + /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only + /// be called by the COO address. (This fee is used to offset the gas cost incurred + /// by the autobirth daemon). + function setAutoBirthFee(uint256 val) external onlyCOO { + autoBirthFee = val; + } + + /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation + /// period has passed. + function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { + return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); + } + + /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or + /// in the middle of a siring cooldown). + /// @param _kittyId reference the id of the kitten, any user can inquire about it + function isReadyToBreed(uint256 _kittyId) + public + view + returns (bool) + { + require(_kittyId > 0); + Kitty storage kit = kitties[_kittyId]; + return _isReadyToBreed(kit); + } + + /// @dev Checks whether a kitty is currently pregnant. + /// @param _kittyId reference the id of the kitten, any user can inquire about it + function isPregnant(uint256 _kittyId) + public + view + returns (bool) + { + require(_kittyId > 0); + // A kitty is pregnant if and only if this field is set + return kitties[_kittyId].siringWithId != 0; + } + + /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT + /// check ownership permissions (that is up to the caller). + /// @param _matron A reference to the Kitty struct of the potential matron. + /// @param _matronId The matron's ID. + /// @param _sire A reference to the Kitty struct of the potential sire. + /// @param _sireId The sire's ID + function _isValidMatingPair( + Kitty storage _matron, + uint256 _matronId, + Kitty storage _sire, + uint256 _sireId + ) + private + view + returns(bool) + { + // A Kitty can't breed with itself! + if (_matronId == _sireId) { + return false; + } + + // Kitties can't breed with their parents. + if (_matron.matronId == _sireId || _matron.sireId == _sireId) { + return false; + } + if (_sire.matronId == _matronId || _sire.sireId == _matronId) { + return false; + } + + // We can short circuit the sibling check (below) if either cat is + // gen zero (has a matron ID of zero). + if (_sire.matronId == 0 || _matron.matronId == 0) { + return true; + } + + // Kitties can't breed with full or half siblings. + if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { + return false; + } + if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { + return false; + } + + // Everything seems cool! Let's get DTF. + return true; + } + + /// @dev Internal check to see if a given sire and matron are a valid mating pair for + /// breeding via auction (i.e. skips ownership and siring approval checks). + function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) + internal + view + returns (bool) + { + Kitty storage matron = kitties[_matronId]; + Kitty storage sire = kitties[_sireId]; + return _isValidMatingPair(matron, _matronId, sire, _sireId); + } + + /// @notice Checks to see if two cats can breed together, including checks for + /// ownership and siring approvals. Does NOT check that both cats are ready for + /// breeding (i.e. breedWith could still fail until the cooldowns are finished). + /// TODO: Shouldn't this check pregnancy and cooldowns?!? + /// @param _matronId The ID of the proposed matron. + /// @param _sireId The ID of the proposed sire. + function canBreedWith(uint256 _matronId, uint256 _sireId) + external + view + returns(bool) + { + require(_matronId > 0); + require(_sireId > 0); + Kitty storage matron = kitties[_matronId]; + Kitty storage sire = kitties[_sireId]; + return _isValidMatingPair(matron, _matronId, sire, _sireId) && + _isSiringPermitted(_sireId, _matronId); + } + + /// @dev Internal utility function to initiate breeding, assumes that all breeding + /// requirements have been checked. + function _breedWith(uint256 _matronId, uint256 _sireId) internal { + // Grab a reference to the Kitties from storage. + Kitty storage sire = kitties[_sireId]; + Kitty storage matron = kitties[_matronId]; + + // Mark the matron as pregnant, keeping track of who the sire is. + matron.siringWithId = uint32(_sireId); + + // Trigger the cooldown for both parents. + _triggerCooldown(sire); + _triggerCooldown(matron); + + // Clear siring permission for both parents. This may not be strictly necessary + // but it's likely to avoid confusion! + delete sireAllowedToAddress[_matronId]; + delete sireAllowedToAddress[_sireId]; + + // Every time a kitty gets pregnant, counter is incremented. + pregnantKitties++; + + // Emit the pregnancy event. + emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); + } + + /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you + /// have previously been given Siring approval. Will either make your cat pregnant, or will + /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() + /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) + /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) + function breedWithAuto(uint256 _matronId, uint256 _sireId) + external + payable + whenNotPaused + { + // Checks for payment. + require(msg.value >= autoBirthFee); + + // Caller must own the matron. + require(_owns(msg.sender, _matronId)); + + // Neither sire nor matron are allowed to be on auction during a normal + // breeding operation, but we don't need to check that explicitly. + // For matron: The caller of this function can't be the owner of the matron + // because the owner of a Kitty on auction is the auction house, and the + // auction house will never call breedWith(). + // For sire: Similarly, a sire on auction will be owned by the auction house + // and the act of transferring ownership will have cleared any oustanding + // siring approval. + // Thus we don't need to spend gas explicitly checking to see if either cat + // is on auction. + + // Check that matron and sire are both owned by caller, or that the sire + // has given siring permission to caller (i.e. matron's owner). + // Will fail for _sireId = 0 + require(_isSiringPermitted(_sireId, _matronId)); + + // Grab a reference to the potential matron + Kitty storage matron = kitties[_matronId]; + + // Make sure matron isn't pregnant, or in the middle of a siring cooldown + require(_isReadyToBreed(matron)); + + // Grab a reference to the potential sire + Kitty storage sire = kitties[_sireId]; + + // Make sure sire isn't pregnant, or in the middle of a siring cooldown + require(_isReadyToBreed(sire)); + + // Test that these cats are a valid mating pair. + require(_isValidMatingPair( + matron, + _matronId, + sire, + _sireId + )); + + // All checks passed, kitty gets pregnant! + _breedWith(_matronId, _sireId); + } + + /// @notice Have a pregnant Kitty give birth! + /// @param _matronId A Kitty ready to give birth. + /// @return The Kitty ID of the new kitten. + /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, + /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned + /// to the current owner of the matron. Upon successful completion, both the matron and the + /// new kitten will be ready to breed again. Note that anyone can call this function (if they + /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. + function giveBirth(uint256 _matronId) + external + whenNotPaused + returns(uint256) + { + // Grab a reference to the matron in storage. + Kitty storage matron = kitties[_matronId]; + + // Check that the matron is a valid cat. + require(matron.birthTime != 0); + + // Check that the matron is pregnant, and that its time has come! + require(_isReadyToGiveBirth(matron)); + + // Grab a reference to the sire in storage. + uint256 sireId = matron.siringWithId; + Kitty storage sire = kitties[sireId]; + + // Determine the higher generation number of the two parents + uint16 parentGen = matron.generation; + if (sire.generation > matron.generation) { + parentGen = sire.generation; + } + + // Call the sooper-sekret gene mixing operation. + uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); + + // Make the new kitten! + address owner = kittyIndexToOwner[_matronId]; + uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); + + // Clear the reference to sire from the matron (REQUIRED! Having siringWithId + // set is what marks a matron as being pregnant.) + delete matron.siringWithId; + + // Every time a kitty gives birth counter is decremented. + pregnantKitties--; + + // Send the balance fee to the person who made birth happen. + msg.sender.transfer(autoBirthFee); + + // return the new kitten's ID + return kittenId; + } +} + + + +/// @title Handles creating auctions for sale and siring of kitties. +/// This wrapper of ReverseAuction exists only so that users can create +/// auctions with only one transaction. +contract KittyAuction is KittyBreeding { + + // @notice The auction contract variables are defined in KittyBase to allow + // us to refer to them in KittyOwnership to prevent accidental transfers. + // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. + // `siringAuction` refers to the auction for siring rights of kitties. + + /// @dev Sets the reference to the sale auction. + /// @param _address - Address of sale contract. + function setSaleAuctionAddress(address _address) external onlyCEO { + SaleClockAuction candidateContract = SaleClockAuction(_address); + + // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 + require(candidateContract.isSaleClockAuction()); + + // Set the new contract address + saleAuction = candidateContract; + } + + /// @dev Sets the reference to the siring auction. + /// @param _address - Address of siring contract. + function setSiringAuctionAddress(address _address) external onlyCEO { + SiringClockAuction candidateContract = SiringClockAuction(_address); + + // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 + require(candidateContract.isSiringClockAuction()); + + // Set the new contract address + siringAuction = candidateContract; + } + + /// @dev Put a kitty up for auction. + /// Does some ownership trickery to create auctions in one tx. + function createSaleAuction( + uint256 _kittyId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration + ) + external + whenNotPaused + { + // Auction contract checks input sizes + // If kitty is already on any auction, this will throw + // because it will be owned by the auction contract. + require(_owns(msg.sender, _kittyId)); + // Ensure the kitty is not pregnant to prevent the auction + // contract accidentally receiving ownership of the child. + // NOTE: the kitty IS allowed to be in a cooldown. + require(!isPregnant(_kittyId)); + _approve(_kittyId, address(saleAuction)); + // Sale auction throws if inputs are invalid and clears + // transfer and sire approval after escrowing the kitty. + saleAuction.createAuction( + _kittyId, + _startingPrice, + _endingPrice, + _duration, + msg.sender + ); + } + + /// @dev Put a kitty up for auction to be sire. + /// Performs checks to ensure the kitty can be sired, then + /// delegates to reverse auction. + function createSiringAuction( + uint256 _kittyId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration + ) + external + whenNotPaused + { + // Auction contract checks input sizes + // If kitty is already on any auction, this will throw + // because it will be owned by the auction contract. + require(_owns(msg.sender, _kittyId)); + require(isReadyToBreed(_kittyId)); + _approve(_kittyId, address(siringAuction)); + // Siring auction throws if inputs are invalid and clears + // transfer and sire approval after escrowing the kitty. + siringAuction.createAuction( + _kittyId, + _startingPrice, + _endingPrice, + _duration, + msg.sender + ); + } + + /// @dev Completes a siring auction by bidding. + /// Immediately breeds the winning matron with the sire on auction. + /// @param _sireId - ID of the sire on auction. + /// @param _matronId - ID of the matron owned by the bidder. + function bidOnSiringAuction( + uint256 _sireId, + uint256 _matronId + ) + external + payable + whenNotPaused + { + // Auction contract checks input sizes + require(_owns(msg.sender, _matronId)); + require(isReadyToBreed(_matronId)); + require(_canBreedWithViaAuction(_matronId, _sireId)); + + // Define the current price of the auction. + uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); + require(msg.value >= currentPrice + autoBirthFee); + + // Siring auction will throw if the bid fails. + siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); + _breedWith(uint32(_matronId), uint32(_sireId)); + } + + /// @dev Transfers the balance of the sale auction contract + /// to the KittyCore contract. We use two-step withdrawal to + /// prevent two transfer calls in the auction bid function. + function withdrawAuctionBalances() external onlyCLevel { + saleAuction.withdrawBalance(); + siringAuction.withdrawBalance(); + } +} + + +/// @title all functions related to creating kittens +contract KittyMinting is KittyAuction { + + // Limits the number of cats the contract owner can ever create. + uint256 public constant PROMO_CREATION_LIMIT = 5000; + uint256 public constant GEN0_CREATION_LIMIT = 45000; + + // Constants for gen0 auctions. + uint256 public constant GEN0_STARTING_PRICE = 10 sun; + uint256 public constant GEN0_AUCTION_DURATION = 1 days; + + // Counts the number of cats the contract owner has created. + uint256 public promoCreatedCount; + uint256 public gen0CreatedCount; + + /// @dev we can create promo kittens, up to a limit. Only callable by COO + /// @param _genes the encoded genes of the kitten to be created, any value is accepted + /// @param _owner the future owner of the created kittens. Default to contract COO + function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { + address kittyOwner = _owner; + if (kittyOwner == address(0)) { + kittyOwner = cooAddress; + } + require(promoCreatedCount < PROMO_CREATION_LIMIT); + + promoCreatedCount++; + _createKitty(0, 0, 0, _genes, kittyOwner); + } + + /// @dev Creates a new gen0 kitty with the given genes and + /// creates an auction for it. + function createGen0Auction(uint256 _genes) external onlyCOO { + require(gen0CreatedCount < GEN0_CREATION_LIMIT); + + uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); + _approve(kittyId, address(saleAuction)); + + saleAuction.createAuction( + kittyId, + _computeNextGen0Price(), + 0, + GEN0_AUCTION_DURATION, + address(uint160(address(this))) + ); + + gen0CreatedCount++; + } + + /// @dev Computes the next gen0 auction starting price, given + /// the average of the past 5 prices + 50%. + function _computeNextGen0Price() internal view returns (uint256) { + uint256 avePrice = saleAuction.averageGen0SalePrice(); + + // Sanity check to ensure we don't overflow arithmetic + require(avePrice == uint256(uint128(avePrice))); + + uint256 nextPrice = avePrice + (avePrice / 2); + + // We never auction for less than starting price + if (nextPrice < GEN0_STARTING_PRICE) { + nextPrice = GEN0_STARTING_PRICE; + } + + return nextPrice; + } +} + + + +/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. +contract KittyCore is KittyMinting { + + // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, + // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts + // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are + // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping + // them in their own contracts, we can upgrade them without disrupting the main contract that tracks + // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of + // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. + // Don't worry, I'm sure someone will reverse engineer it soon enough! + // + // Secondly, we break the core contract into multiple files using inheritence, one for each major + // facet of functionality of CK. This allows us to keep related code bundled together while still + // avoiding a single giant file with everything in it. The breakdown is as follows: + // + // - KittyBase: This is where we define the most fundamental code shared throughout the core + // functionality. This includes our main data storage, constants and data types, plus + // internal functions for managing these items. + // + // - KittyAccessControl: This contract manages the various addresses and constraints for operations + // that can be executed only by specific roles. Namely CEO, CFO and COO. + // + // - KittyOwnership: This provides the methods required for basic non-fungible token + // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). + // + // - KittyBreeding: This file contains the methods necessary to breed cats together, including + // keeping track of siring offers, and relies on an external genetic combination contract. + // + // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring + // services. The actual auction functionality is handled in two sibling contracts (one + // for sales and one for siring), while auction creation and bidding is mostly mediated + // through this facet of the core contract. + // + // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. + // We can make up to 5000 "promo" cats that can be given away (especially important when + // the community is new), and all others can only be created and then immediately put up + // for auction via an algorithmically determined starting price. Regardless of how they + // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the + // community to breed, breed, breed! + + // Set in case the core contract is broken and an upgrade is required + address public newContractAddress; + + /// @notice Creates the main CryptoKitties smart contract instance. + constructor() public { + // Starts paused. + paused = true; + + // the creator of the contract is the initial CEO + ceoAddress = msg.sender; + + // the creator of the contract is also the initial COO + cooAddress = msg.sender; + + // start with the mythical kitten 0 - so we don't have generation-0 parent issues + _createKitty(0, 0, 0, uint256(-1), address(0)); + } + + /// @dev Used to mark the smart contract as upgraded, in case there is a serious + /// breaking bug. This method does nothing but keep track of the new contract and + /// emit a message indicating that the new address is set. It's up to clients of this + /// contract to update to the new contract address in that case. (This contract will + /// be paused indefinitely if such an upgrade takes place.) + /// @param _v2Address new address + function setNewAddress(address _v2Address) external onlyCEO whenPaused { + // See README.md for updgrade plan + newContractAddress = _v2Address; + emit ContractUpgrade(_v2Address); + } + + /// @notice No tipping! + /// @dev Reject all Ether from being sent here, unless it's from one of the + /// two auction contracts. (Hopefully, we can prevent user accidents.) + function() external payable { + require( + msg.sender == address(saleAuction) || + msg.sender == address(siringAuction) + ); + } + + /// @notice Returns all the relevant information about a specific kitty. + /// @param _id The ID of the kitty of interest. + function getKitty(uint256 _id) + external + view + returns ( + bool isGestating, + bool isReady, + uint256 cooldownIndex, + uint256 nextActionAt, + uint256 siringWithId, + uint256 birthTime, + uint256 matronId, + uint256 sireId, + uint256 generation, + uint256 genes + ) { + Kitty storage kit = kitties[_id]; + + // if this variable is 0 then it's not gestating + isGestating = (kit.siringWithId != 0); + isReady = (kit.cooldownEndBlock <= block.number); + cooldownIndex = uint256(kit.cooldownIndex); + nextActionAt = uint256(kit.cooldownEndBlock); + siringWithId = uint256(kit.siringWithId); + birthTime = uint256(kit.birthTime); + matronId = uint256(kit.matronId); + sireId = uint256(kit.sireId); + generation = uint256(kit.generation); + genes = kit.genes; + } + + /// @dev Override unpause so it requires all external contract addresses + /// to be set before contract can be unpaused. Also, we can't have + /// newContractAddress set either, because then the contract was upgraded. + /// @notice This is public rather than external so we can call super.unpause + /// without using an expensive CALL. + + function unpause(address payable toAddress, uint256 tokenValue, trcToken tokenId) public onlyCEO whenPaused returns (uint256 r) { + require(address(saleAuction) != address(0)); + require(address(siringAuction) != address(0)); + require(address(geneScience) != address(0)); + require(address(newContractAddress) == address(0)); + toAddress.transferToken(tokenValue, tokenId); + r = address(this).tokenBalance(tokenId); + // Actually unpause the contract. + super.unpause(); + } + + // @dev Allows the CFO to capture the balance available to the contract. + function withdrawBalance() external onlyCFO { + uint256 balance = address(this).balance; + // Subtract all the currently pregnant kittens we have, plus 1 of margin. + uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; + + if (balance > subtractFees) { + cfoAddress.transfer(balance - subtractFees); + } + } +} + + + + + + + + + + + + + +// // Auction wrapper functions + + +// Auction wrapper functions + + + + + + + +/// @title SEKRETOOOO +contract GeneScienceInterface { + + function isGeneScience() public pure returns (bool){ + return true; + } + + /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor + /// @param genes1 genes of mom + /// @param genes2 genes of sire + /// @return the genes that are supposed to be passed down the child + function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ + + return (genes1+genes2+targetBlock)/2; + + +} +} + + + + + + + + + + + + + + + + +/// @title The external contract that is responsible for generating metadata for the kitties, +/// it has one function that will return the data as bytes. +contract ERC721Metadata { + /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. + function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { + if (_tokenId == 1) { + buffer[0] = "Hello World! :D"; + count = 15; + } else if (_tokenId == 2) { + buffer[0] = "I would definitely choose a medi"; + buffer[1] = "um length string."; + count = 49; + } else if (_tokenId == 3) { + buffer[0] = "Lorem ipsum dolor sit amet, mi e"; + buffer[1] = "st accumsan dapibus augue lorem,"; + buffer[2] = " tristique vestibulum id, libero"; + buffer[3] = " suscipit varius sapien aliquam."; + count = 128; + } + } +} + + + + + + + + + + + + + + + +/// @title Auction Core +/// @dev Contains models, variables, and internal methods for the auction. +/// @notice We omit a fallback function to prevent accidental sends to this contract. +contract ClockAuctionBase { + + // Represents an auction on an NFT + struct Auction { + // Current owner of NFT + address payable seller; + // Price (in wei) at beginning of auction + uint128 startingPrice; + // Price (in wei) at end of auction + uint128 endingPrice; + // Duration (in seconds) of auction + uint64 duration; + // Time when auction started + // NOTE: 0 if this auction has been concluded + uint64 startedAt; + } + + // Reference to contract tracking NFT ownership + ERC721 public nonFungibleContract; + + // Cut owner takes on each auction, measured in basis points (1/100 of a percent). + // Values 0-10,000 map to 0%-100% + uint256 public ownerCut; + + // Map from token ID to their corresponding auction. + mapping (uint256 => Auction) tokenIdToAuction; + + event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); + event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); + event AuctionCancelled(uint256 tokenId); + + /// @dev Returns true if the claimant owns the token. + /// @param _claimant - Address claiming to own the token. + /// @param _tokenId - ID of token whose ownership to verify. + function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { + return (nonFungibleContract.ownerOf(_tokenId) == _claimant); + } + + /// @dev Escrows the NFT, assigning ownership to this contract. + /// Throws if the escrow fails. + /// @param _owner - Current owner address of token to escrow. + /// @param _tokenId - ID of token whose approval to verify. + function _escrow(address _owner, uint256 _tokenId) internal { + // it will throw if transfer fails + nonFungibleContract.transferFrom(_owner, address(this), _tokenId); + } + + /// @dev Transfers an NFT owned by this contract to another address. + /// Returns true if the transfer succeeds. + /// @param _receiver - Address to transfer NFT to. + /// @param _tokenId - ID of token to transfer. + function _transfer(address _receiver, uint256 _tokenId) internal { + // it will throw if transfer fails + nonFungibleContract.transfer(_receiver, _tokenId); + } + + /// @dev Adds an auction to the list of open auctions. Also fires the + /// AuctionCreated event. + /// @param _tokenId The ID of the token to be put on auction. + /// @param _auction Auction to add. + function _addAuction(uint256 _tokenId, Auction memory _auction) internal { + // Require that all auctions have a duration of + // at least one minute. (Keeps our math from getting hairy!) + require(_auction.duration >= 1 minutes); + + tokenIdToAuction[_tokenId] = _auction; + + emit AuctionCreated( + uint256(_tokenId), + uint256(_auction.startingPrice), + uint256(_auction.endingPrice), + uint256(_auction.duration) + ); + } + + /// @dev Cancels an auction unconditionally. + function _cancelAuction(uint256 _tokenId, address _seller) internal { + _removeAuction(_tokenId); + _transfer(_seller, _tokenId); + emit AuctionCancelled(_tokenId); + } + + /// @dev Computes the price and transfers winnings. + /// Does NOT transfer ownership of token. + function _bid(uint256 _tokenId, uint256 _bidAmount) + internal + returns (uint256) + { + // Get a reference to the auction struct + Auction storage auction = tokenIdToAuction[_tokenId]; + + // Explicitly check that this auction is currently live. + // (Because of how Ethereum mappings work, we can't just count + // on the lookup above failing. An invalid _tokenId will just + // return an auction object that is all zeros.) + require(_isOnAuction(auction)); + + // Check that the bid is greater than or equal to the current price + uint256 price = _currentPrice(auction); + require(_bidAmount >= price); + + // Grab a reference to the seller before the auction struct + // gets deleted. + address payable seller = auction.seller; + + // The bid is good! Remove the auction before sending the fees + // to the sender so we can't have a reentrancy attack. + _removeAuction(_tokenId); + + // Transfer proceeds to seller (if there are any!) + if (price > 0) { + // Calculate the auctioneer's cut. + // (NOTE: _computeCut() is guaranteed to return a + // value <= price, so this subtraction can't go negative.) + uint256 auctioneerCut = _computeCut(price); + uint256 sellerProceeds = price - auctioneerCut; + + // NOTE: Doing a transfer() in the middle of a complex + // method like this is generally discouraged because of + // reentrancy attacks and DoS attacks if the seller is + // a contract with an invalid fallback function. We explicitly + // guard against reentrancy attacks by removing the auction + // before calling transfer(), and the only thing the seller + // can DoS is the sale of their own asset! (And if it's an + // accident, they can call cancelAuction(). ) + seller.transfer(sellerProceeds); + } + + // Calculate any excess funds included with the bid. If the excess + // is anything worth worrying about, transfer it back to bidder. + // NOTE: We checked above that the bid amount is greater than or + // equal to the price so this cannot underflow. + uint256 bidExcess = _bidAmount - price; + + // Return the funds. Similar to the previous transfer, this is + // not susceptible to a re-entry attack because the auction is + // removed before any transfers occur. + msg.sender.transfer(bidExcess); + + // Tell the world! + emit AuctionSuccessful(_tokenId, price, msg.sender); + + return price; + } + + /// @dev Removes an auction from the list of open auctions. + /// @param _tokenId - ID of NFT on auction. + function _removeAuction(uint256 _tokenId) internal { + delete tokenIdToAuction[_tokenId]; + } + + /// @dev Returns true if the NFT is on auction. + /// @param _auction - Auction to check. + function _isOnAuction(Auction storage _auction) internal view returns (bool) { + return (_auction.startedAt > 0); + } + + /// @dev Returns current price of an NFT on auction. Broken into two + /// functions (this one, that computes the duration from the auction + /// structure, and the other that does the price computation) so we + /// can easily test that the price computation works correctly. + function _currentPrice(Auction storage _auction) + internal + view + returns (uint256) + { + uint256 secondsPassed = 0; + + // A bit of insurance against negative values (or wraparound). + // Probably not necessary (since Ethereum guarnatees that the + // now variable doesn't ever go backwards). + if (now > _auction.startedAt) { + secondsPassed = now - _auction.startedAt; + } + + return _computeCurrentPrice( + _auction.startingPrice, + _auction.endingPrice, + _auction.duration, + secondsPassed + ); + } + + /// @dev Computes the current price of an auction. Factored out + /// from _currentPrice so we can run extensive unit tests. + /// When testing, make this function public and turn on + /// `Current price computation` test suite. + function _computeCurrentPrice( + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration, + uint256 _secondsPassed + ) + internal + pure + returns (uint256) + { + // NOTE: We don't use SafeMath (or similar) in this function because + // all of our public functions carefully cap the maximum values for + // time (at 64-bits) and currency (at 128-bits). _duration is + // also known to be non-zero (see the require() statement in + // _addAuction()) + if (_secondsPassed >= _duration) { + // We've reached the end of the dynamic pricing portion + // of the auction, just return the end price. + return _endingPrice; + } else { + // Starting price can be higher than ending price (and often is!), so + // this delta can be negative. + int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); + + // This multiplication can't overflow, _secondsPassed will easily fit within + // 64-bits, and totalPriceChange will easily fit within 128-bits, their product + // will always fit within 256-bits. + int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); + + // currentPriceChange can be negative, but if so, will have a magnitude + // less that _startingPrice. Thus, this result will always end up positive. + int256 currentPrice = int256(_startingPrice) + currentPriceChange; + + return uint256(currentPrice); + } + } + + /// @dev Computes owner's cut of a sale. + /// @param _price - Sale price of NFT. + function _computeCut(uint256 _price) internal view returns (uint256) { + // NOTE: We don't use SafeMath (or similar) in this function because + // all of our entry functions carefully cap the maximum values for + // currency (at 128-bits), and ownerCut <= 10000 (see the require() + // statement in the ClockAuction constructor). The result of this + // function is always guaranteed to be <= _price. + return _price * ownerCut / 10000; + } + +} + + + + + + + +/** + * @title Pausable + * @dev Base contract which allows children to implement an emergency stop mechanism. + */ +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + /** + * @dev modifier to allow actions only when the contract IS paused + */ + modifier whenNotPaused() { + require(!paused); + _; + } + + /** + * @dev modifier to allow actions only when the contract IS NOT paused + */ + modifier whenPaused { + require(paused); + _; + } + + /** + * @dev called by the owner to pause, triggers stopped state + */ + function pause() onlyOwner whenNotPaused public returns (bool) { + paused = true; + emit Pause(); + return true; + } + + /** + * @dev called by the owner to unpause, returns to normal state + */ + function unpause() onlyOwner whenPaused public returns (bool) { + paused = false; + emit Unpause(); + return true; + } +} + + +/// @title Clock auction for non-fungible tokens. +/// @notice We omit a fallback function to prevent accidental sends to this contract. +contract ClockAuction is Pausable, ClockAuctionBase { + + /// @dev The ERC-165 interface signature for ERC-721. + /// Ref: https://github.com/ethereum/EIPs/issues/165 + /// Ref: https://github.com/ethereum/EIPs/issues/721 + bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); + + /// @dev Constructor creates a reference to the NFT ownership contract + /// and verifies the owner cut is in the valid range. + /// @param _nftAddress - address of a deployed contract implementing + /// the Nonfungible Interface. + /// @param _cut - percent cut the owner takes on each auction, must be + /// between 0-10,000. + constructor(address _nftAddress, uint256 _cut) public { + require(_cut <= 10000); + ownerCut = _cut; + + ERC721 candidateContract = ERC721(_nftAddress); + require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); + nonFungibleContract = candidateContract; + } + + /// @dev Remove all Ether from the contract, which is the owner's cuts + /// as well as any Ether sent directly to the contract address. + /// Always transfers to the NFT contract, but can be called either by + /// the owner or the NFT contract. + function withdrawBalance() external { + address payable nftAddress = address(uint160(address(nonFungibleContract))); + + require( + msg.sender == owner || + msg.sender == nftAddress + ); + // We are using this boolean method to make sure that even if one fails it will still work + bool res = nftAddress.send(address(this).balance); + } + + /// @dev Creates and begins a new auction. + /// @param _tokenId - ID of token to auction, sender must be owner. + /// @param _startingPrice - Price of item (in wei) at beginning of auction. + /// @param _endingPrice - Price of item (in wei) at end of auction. + /// @param _duration - Length of time to move between starting + /// price and ending price (in seconds). + /// @param _seller - Seller, if not the message sender + function createAuction( + uint256 _tokenId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration, + address payable _seller + ) + external + whenNotPaused + { + // Sanity check that no inputs overflow how many bits we've allocated + // to store them in the auction struct. + require(_startingPrice == uint256(uint128(_startingPrice))); + require(_endingPrice == uint256(uint128(_endingPrice))); + require(_duration == uint256(uint64(_duration))); + + require(_owns(msg.sender, _tokenId)); + _escrow(msg.sender, _tokenId); + Auction memory auction = Auction( + _seller, + uint128(_startingPrice), + uint128(_endingPrice), + uint64(_duration), + uint64(now) + ); + _addAuction(_tokenId, auction); + } + + /// @dev Bids on an open auction, completing the auction and transferring + /// ownership of the NFT if enough Ether is supplied. + /// @param _tokenId - ID of token to bid on. + function bid(uint256 _tokenId) + external + payable + whenNotPaused + { + // _bid will throw if the bid or funds transfer fails + _bid(_tokenId, msg.value); + _transfer(msg.sender, _tokenId); + } + + /// @dev Cancels an auction that hasn't been won yet. + /// Returns the NFT to original owner. + /// @notice This is a state-modifying function that can + /// be called while the contract is paused. + /// @param _tokenId - ID of token on auction + function cancelAuction(uint256 _tokenId) + external + { + Auction storage auction = tokenIdToAuction[_tokenId]; + require(_isOnAuction(auction)); + address seller = auction.seller; + require(msg.sender == seller); + _cancelAuction(_tokenId, seller); + } + + /// @dev Cancels an auction when the contract is paused. + /// Only the owner may do this, and NFTs are returned to + /// the seller. This should only be used in emergencies. + /// @param _tokenId - ID of the NFT on auction to cancel. + function cancelAuctionWhenPaused(uint256 _tokenId) + whenPaused + onlyOwner + external + { + Auction storage auction = tokenIdToAuction[_tokenId]; + require(_isOnAuction(auction)); + _cancelAuction(_tokenId, auction.seller); + } + + /// @dev Returns auction info for an NFT on auction. + /// @param _tokenId - ID of NFT on auction. + function getAuction(uint256 _tokenId) + external + view + returns + ( + address seller, + uint256 startingPrice, + uint256 endingPrice, + uint256 duration, + uint256 startedAt + ) { + Auction storage auction = tokenIdToAuction[_tokenId]; + require(_isOnAuction(auction)); + return ( + auction.seller, + auction.startingPrice, + auction.endingPrice, + auction.duration, + auction.startedAt + ); + } + + /// @dev Returns the current price of an auction. + /// @param _tokenId - ID of the token price we are checking. + function getCurrentPrice(uint256 _tokenId) + external + view + returns (uint256) + { + Auction storage auction = tokenIdToAuction[_tokenId]; + require(_isOnAuction(auction)); + return _currentPrice(auction); + } + +} + + +/// @title Reverse auction modified for siring +/// @notice We omit a fallback function to prevent accidental sends to this contract. +contract SiringClockAuction is ClockAuction { + + // @dev Sanity check that allows us to ensure that we are pointing to the + // right auction in our setSiringAuctionAddress() call. + bool public isSiringClockAuction = true; + + // Delegate constructor + constructor(address _nftAddr, uint256 _cut) public + ClockAuction(_nftAddr, _cut) {} + + /// @dev Creates and begins a new auction. Since this function is wrapped, + /// require sender to be KittyCore contract. + /// @param _tokenId - ID of token to auction, sender must be owner. + /// @param _startingPrice - Price of item (in wei) at beginning of auction. + /// @param _endingPrice - Price of item (in wei) at end of auction. + /// @param _duration - Length of auction (in seconds). + /// @param _seller - Seller, if not the message sender + function createAuction( + uint256 _tokenId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration, + address payable _seller + ) + external + { + // Sanity check that no inputs overflow how many bits we've allocated + // to store them in the auction struct. + require(_startingPrice == uint256(uint128(_startingPrice))); + require(_endingPrice == uint256(uint128(_endingPrice))); + require(_duration == uint256(uint64(_duration))); + + require(msg.sender == address(nonFungibleContract)); + _escrow(_seller, _tokenId); + Auction memory auction = Auction( + _seller, + uint128(_startingPrice), + uint128(_endingPrice), + uint64(_duration), + uint64(now) + ); + _addAuction(_tokenId, auction); + } + + /// @dev Places a bid for siring. Requires the sender + /// is the KittyCore contract because all bid methods + /// should be wrapped. Also returns the kitty to the + /// seller rather than the winner. + function bid(uint256 _tokenId) + external + payable + { + require(msg.sender == address(nonFungibleContract)); + address seller = tokenIdToAuction[_tokenId].seller; + // _bid checks that token ID is valid and will throw if bid fails + _bid(_tokenId, msg.value); + // We transfer the kitty back to the seller, the winner will get + // the offspring + _transfer(seller, _tokenId); + } + +} + + + + + +/// @title Clock auction modified for sale of kitties +/// @notice We omit a fallback function to prevent accidental sends to this contract. +contract SaleClockAuction is ClockAuction { + + // @dev Sanity check that allows us to ensure that we are pointing to the + // right auction in our setSaleAuctionAddress() call. + bool public isSaleClockAuction = true; + + // Tracks last 5 sale price of gen0 kitty sales + uint256 public gen0SaleCount; + uint256[5] public lastGen0SalePrices; + + // Delegate constructor + constructor(address _nftAddr, uint256 _cut) public + ClockAuction(_nftAddr, _cut) {} + + /// @dev Creates and begins a new auction. + /// @param _tokenId - ID of token to auction, sender must be owner. + /// @param _startingPrice - Price of item (in wei) at beginning of auction. + /// @param _endingPrice - Price of item (in wei) at end of auction. + /// @param _duration - Length of auction (in seconds). + /// @param _seller - Seller, if not the message sender + function createAuction( + uint256 _tokenId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration, + address payable _seller + ) + external + { + // Sanity check that no inputs overflow how many bits we've allocated + // to store them in the auction struct. + require(_startingPrice == uint256(uint128(_startingPrice))); + require(_endingPrice == uint256(uint128(_endingPrice))); + require(_duration == uint256(uint64(_duration))); + + require(msg.sender == address(nonFungibleContract)); + _escrow(_seller, _tokenId); + Auction memory auction = Auction( + _seller, + uint128(_startingPrice), + uint128(_endingPrice), + uint64(_duration), + uint64(now) + ); + _addAuction(_tokenId, auction); + } + + /// @dev Updates lastSalePrice if seller is the nft contract + /// Otherwise, works the same as default bid method. + function bid(uint256 _tokenId) + external + payable + { + // _bid verifies token ID size + address seller = tokenIdToAuction[_tokenId].seller; + uint256 price = _bid(_tokenId, msg.value); + _transfer(msg.sender, _tokenId); + + // If not a gen0 auction, exit + if (seller == address(nonFungibleContract)) { + // Track gen0 sale prices + lastGen0SalePrices[gen0SaleCount % 5] = price; + gen0SaleCount++; + } + } + + function averageGen0SalePrice() external view returns (uint256) { + uint256 sum = 0; + for (uint256 i = 0; i < 5; i++) { + sum += lastGen0SalePrices[i]; + } + return sum / 5; + } + +} + + + + + + + diff --git a/framework/src/test/resources/soliditycode_0.5.15/addTrcToken002Cat_withFinny.sol b/framework/src/test/resources/soliditycode_0.5.15/addTrcToken002Cat_withFinny.sol new file mode 100644 index 00000000000..2acebceddda --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/addTrcToken002Cat_withFinny.sol @@ -0,0 +1,2051 @@ +//pragma solidity ^0.4.11; + + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + if (newOwner != address(0)) { + owner = newOwner; + } + } + +} + + + + +/// @title A facet of KittyCore that manages special access privileges. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. +contract KittyAccessControl { + // This facet controls access control for CryptoKitties. There are four roles managed here: + // + // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart + // contracts. It is also the only role that can unpause the smart contract. It is initially + // set to the address that created the smart contract in the KittyCore constructor. + // + // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. + // + // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. + // + // It should be noted that these roles are distinct without overlap in their access abilities, the + // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any + // address to any role, the CEO address itself doesn't have the ability to act in those roles. This + // restriction is intentional so that we aren't tempted to use the CEO address frequently out of + // convenience. The less we use an address, the less likely it is that we somehow compromise the + // account. + + /// @dev Emited when contract is upgraded - See README.md for updgrade plan + event ContractUpgrade(address newContract); + + // The addresses of the accounts (or contracts) that can execute actions within each roles. + address public ceoAddress; + address payable public cfoAddress; + address public cooAddress; + + // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked + bool public paused = false; + + /// @dev Access modifier for CEO-only functionality + modifier onlyCEO() { + require(msg.sender == ceoAddress); + _; + } + + /// @dev Access modifier for CFO-only functionality + modifier onlyCFO() { + require(msg.sender == cfoAddress); + _; + } + + /// @dev Access modifier for COO-only functionality + modifier onlyCOO() { + require(msg.sender == cooAddress); + _; + } + + modifier onlyCLevel() { + require( + msg.sender == cooAddress || + msg.sender == ceoAddress || + msg.sender == cfoAddress + ); + _; + } + + /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. + /// @param _newCEO The address of the new CEO + function setCEO(address _newCEO) external onlyCEO { + require(_newCEO != address(0)); + + ceoAddress = _newCEO; + } + + /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. + /// @param _newCFO The address of the new CFO + function setCFO(address payable _newCFO) external onlyCEO { + require(_newCFO != address(0)); + + cfoAddress = _newCFO; + } + + /// @dev Assigns a new address to act as the COO. Only available to the current CEO. + /// @param _newCOO The address of the new COO + function setCOO(address _newCOO) external onlyCEO { + require(_newCOO != address(0)); + + cooAddress = _newCOO; + } + + /*** Pausable functionality adapted from OpenZeppelin ***/ + + /// @dev Modifier to allow actions only when the contract IS NOT paused + modifier whenNotPaused() { + require(!paused); + _; + } + + /// @dev Modifier to allow actions only when the contract IS paused + modifier whenPaused { + require(paused); + _; + } + + /// @dev Called by any "C-level" role to pause the contract. Used only when + /// a bug or exploit is detected and we need to limit damage. + function pause() external onlyCLevel whenNotPaused { + paused = true; + } + + /// @dev Unpauses the smart contract. Can only be called by the CEO, since + /// one reason we may pause the contract is when CFO or COO accounts are + /// compromised. + /// @notice This is public rather than external so it can be called by + /// derived contracts. + function unpause() public onlyCEO whenPaused { + // can't unpause if contract was upgraded + paused = false; + } +} + + + + +/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. +contract KittyBase is KittyAccessControl { + /*** EVENTS ***/ + + /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously + /// includes any time a cat is created through the giveBirth method, but it is also called + /// when a new gen0 cat is created. + event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); + + /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten + /// ownership is assigned, including births. + event Transfer(address from, address to, uint256 tokenId); + + /*** DATA TYPES ***/ + + /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy + /// of this structure, so great care was taken to ensure that it fits neatly into + /// exactly two 256-bit words. Note that the order of the members in this structure + /// is important because of the byte-packing rules used by Ethereum. + /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html + struct Kitty { + // The Kitty's genetic code is packed into these 256-bits, the format is + // sooper-sekret! A cat's genes never change. + uint256 genes; + + // The timestamp from the block when this cat came into existence. + uint64 birthTime; + + // The minimum timestamp after which this cat can engage in breeding + // activities again. This same timestamp is used for the pregnancy + // timer (for matrons) as well as the siring cooldown. + uint64 cooldownEndBlock; + + // The ID of the parents of this kitty, set to 0 for gen0 cats. + // Note that using 32-bit unsigned integers limits us to a "mere" + // 4 billion cats. This number might seem small until you realize + // that Ethereum currently has a limit of about 500 million + // transactions per year! So, this definitely won't be a problem + // for several years (even as Ethereum learns to scale). + uint32 matronId; + uint32 sireId; + + // Set to the ID of the sire cat for matrons that are pregnant, + // zero otherwise. A non-zero value here is how we know a cat + // is pregnant. Used to retrieve the genetic material for the new + // kitten when the birth transpires. + uint32 siringWithId; + + // Set to the index in the cooldown array (see below) that represents + // the current cooldown duration for this Kitty. This starts at zero + // for gen0 cats, and is initialized to floor(generation/2) for others. + // Incremented by one for each successful breeding action, regardless + // of whether this cat is acting as matron or sire. + uint16 cooldownIndex; + + // The "generation number" of this cat. Cats minted by the CK contract + // for sale are called "gen0" and have a generation number of 0. The + // generation number of all other cats is the larger of the two generation + // numbers of their parents, plus one. + // (i.e. max(matron.generation, sire.generation) + 1) + uint16 generation; + } + + /*** CONSTANTS ***/ + + /// @dev A lookup table indicating the cooldown duration after any successful + /// breeding action, called "pregnancy time" for matrons and "siring cooldown" + /// for sires. Designed such that the cooldown roughly doubles each time a cat + /// is bred, encouraging owners not to just keep breeding the same cat over + /// and over again. Caps out at one week (a cat can breed an unbounded number + /// of times, and the maximum cooldown is always seven days). + uint32[14] public cooldowns = [ + uint32(1 minutes), + uint32(2 minutes), + uint32(5 minutes), + uint32(10 minutes), + uint32(30 minutes), + uint32(1 hours), + uint32(2 hours), + uint32(4 hours), + uint32(8 hours), + uint32(16 hours), + uint32(1 days), + uint32(2 days), + uint32(4 days), + uint32(7 days) + ]; + + // An approximation of currently how many seconds are in between blocks. + uint256 public secondsPerBlock = 15; + + /*** STORAGE ***/ + + /// @dev An array containing the Kitty struct for all Kitties in existence. The ID + /// of each cat is actually an index into this array. Note that ID 0 is a negacat, + /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre + /// creature that is both matron and sire... to itself! Has an invalid genetic code. + /// In other words, cat ID 0 is invalid... ;-) + Kitty[] kitties; + + /// @dev A mapping from cat IDs to the address that owns them. All cats have + /// some valid owner address, even gen0 cats are created with a non-zero owner. + mapping (uint256 => address) public kittyIndexToOwner; + + // @dev A mapping from owner address to count of tokens that address owns. + // Used internally inside balanceOf() to resolve ownership count. + mapping (address => uint256) ownershipTokenCount; + + /// @dev A mapping from KittyIDs to an address that has been approved to call + /// transferFrom(). Each Kitty can only have one approved address for transfer + /// at any time. A zero value means no approval is outstanding. + mapping (uint256 => address) public kittyIndexToApproved; + + /// @dev A mapping from KittyIDs to an address that has been approved to use + /// this Kitty for siring via breedWith(). Each Kitty can only have one approved + /// address for siring at any time. A zero value means no approval is outstanding. + mapping (uint256 => address) public sireAllowedToAddress; + + /// @dev The address of the ClockAuction contract that handles sales of Kitties. This + /// same contract handles both peer-to-peer sales as well as the gen0 sales which are + /// initiated every 15 minutes. + SaleClockAuction public saleAuction; + + /// @dev The address of a custom ClockAuction subclassed contract that handles siring + /// auctions. Needs to be separate from saleAuction because the actions taken on success + /// after a sales and siring auction are quite different. + SiringClockAuction public siringAuction; + + /// @dev Assigns ownership of a specific Kitty to an address. + function _transfer(address _from, address _to, uint256 _tokenId) internal { + // Since the number of kittens is capped to 2^32 we can't overflow this + ownershipTokenCount[_to]++; + // transfer ownership + kittyIndexToOwner[_tokenId] = _to; + // When creating new kittens _from is 0x0, but we can't account that address. + if (_from != address(0)) { + ownershipTokenCount[_from]--; + // once the kitten is transferred also clear sire allowances + delete sireAllowedToAddress[_tokenId]; + // clear any previously approved ownership exchange + delete kittyIndexToApproved[_tokenId]; + } + // Emit the transfer event. + emit Transfer(_from, _to, _tokenId); + } + + /// @dev An internal method that creates a new kitty and stores it. This + /// method doesn't do any checking and should only be called when the + /// input data is known to be valid. Will generate both a Birth event + /// and a Transfer event. + /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) + /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) + /// @param _generation The generation number of this cat, must be computed by caller. + /// @param _genes The kitty's genetic code. + /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) + function _createKitty( + uint256 _matronId, + uint256 _sireId, + uint256 _generation, + uint256 _genes, + address _owner + ) + internal + returns (uint) + { + // These requires are not strictly necessary, our calling code should make + // sure that these conditions are never broken. However! _createKitty() is already + // an expensive call (for storage), and it doesn't hurt to be especially careful + // to ensure our data structures are always valid. + require(_matronId == uint256(uint32(_matronId))); + require(_sireId == uint256(uint32(_sireId))); + require(_generation == uint256(uint16(_generation))); + + // New kitty starts with the same cooldown as parent gen/2 + uint16 cooldownIndex = uint16(_generation / 2); + if (cooldownIndex > 13) { + cooldownIndex = 13; + } + + Kitty memory _kitty = Kitty({ + genes: _genes, + birthTime: uint64(now), + cooldownEndBlock: 0, + matronId: uint32(_matronId), + sireId: uint32(_sireId), + siringWithId: 0, + cooldownIndex: cooldownIndex, + generation: uint16(_generation) + }); + uint256 newKittenId = kitties.push(_kitty) - 1; + + // It's probably never going to happen, 4 billion cats is A LOT, but + // let's just be 100% sure we never let this happen. + require(newKittenId == uint256(uint32(newKittenId))); + + // emit the birth event + emit Birth( + _owner, + newKittenId, + uint256(_kitty.matronId), + uint256(_kitty.sireId), + _kitty.genes + ); + + // This will assign ownership, and also emit the Transfer event as + // per ERC721 draft + _transfer(address(0), _owner, newKittenId); + + return newKittenId; + } + + // Any C-level can fix how many seconds per blocks are currently observed. + function setSecondsPerBlock(uint256 secs) external onlyCLevel { + require(secs < cooldowns[0]); + secondsPerBlock = secs; + } +} + + +/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens +/// @author Dieter Shirley (https://github.com/dete) +contract ERC721 { + // Required methods + function totalSupply() public view returns (uint256 total); + function balanceOf(address _owner) public view returns (uint256 balance); + function ownerOf(uint256 _tokenId) external view returns (address owner); + function approve(address _to, uint256 _tokenId) external; + function transfer(address _to, uint256 _tokenId) external; + function transferFrom(address _from, address _to, uint256 _tokenId) external; + + // Events + event Transfer(address from, address to, uint256 tokenId); + event Approval(address owner, address approved, uint256 tokenId); + + // Optional + // function name() public view returns (string name); + // function symbol() public view returns (string symbol); + // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); + // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); + + // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) + function supportsInterface(bytes4 _interfaceID) external view returns (bool); +} + + +/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 +/// See the KittyCore contract documentation to understand how the various contract facets are arranged. +contract KittyOwnership is ERC721, KittyBase { + + /// @notice Name and symbol of the non fungible token, as defined in ERC721. + string public constant name = "CryptoKitties"; + string public constant symbol = "CK"; + + // The contract that will return kitty metadata + ERC721Metadata public erc721Metadata; + + bytes4 constant InterfaceSignature_ERC165 = + bytes4(keccak256('supportsInterface(bytes4)')); + + bytes4 constant InterfaceSignature_ERC721 = + bytes4(keccak256('name()')) ^ + bytes4(keccak256('symbol()')) ^ + bytes4(keccak256('totalSupply()')) ^ + bytes4(keccak256('balanceOf(address)')) ^ + bytes4(keccak256('ownerOf(uint256)')) ^ + bytes4(keccak256('approve(address,uint256)')) ^ + bytes4(keccak256('transfer(address,uint256)')) ^ + bytes4(keccak256('transferFrom(address,address,uint256)')) ^ + bytes4(keccak256('tokensOfOwner(address)')) ^ + bytes4(keccak256('tokenMetadata(uint256,string)')); + + /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). + /// Returns true for any standardized interfaces implemented by this contract. We implement + /// ERC-165 (obviously!) and ERC-721. + function supportsInterface(bytes4 _interfaceID) external view returns (bool) + { + // DEBUG ONLY + //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); + + return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); + } + + /// @dev Set the address of the sibling contract that tracks metadata. + /// CEO only. + function setMetadataAddress(address _contractAddress) public onlyCEO { + erc721Metadata = ERC721Metadata(_contractAddress); + } + + // Internal utility functions: These functions all assume that their input arguments + // are valid. We leave it to public methods to sanitize their inputs and follow + // the required logic. + + /// @dev Checks if a given address is the current owner of a particular Kitty. + /// @param _claimant the address we are validating against. + /// @param _tokenId kitten id, only valid when > 0 + function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { + return kittyIndexToOwner[_tokenId] == _claimant; + } + + /// @dev Checks if a given address currently has transferApproval for a particular Kitty. + /// @param _claimant the address we are confirming kitten is approved for. + /// @param _tokenId kitten id, only valid when > 0 + function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { + return kittyIndexToApproved[_tokenId] == _claimant; + } + + /// @dev Marks an address as being approved for transferFrom(), overwriting any previous + /// approval. Setting _approved to address(0) clears all transfer approval. + /// NOTE: _approve() does NOT send the Approval event. This is intentional because + /// _approve() and transferFrom() are used together for putting Kitties on auction, and + /// there is no value in spamming the log with Approval events in that case. + function _approve(uint256 _tokenId, address _approved) internal { + kittyIndexToApproved[_tokenId] = _approved; + } + + /// @notice Returns the number of Kitties owned by a specific address. + /// @param _owner The owner address to check. + /// @dev Required for ERC-721 compliance + function balanceOf(address _owner) public view returns (uint256 count) { + return ownershipTokenCount[_owner]; + } + + /// @notice Transfers a Kitty to another address. If transferring to a smart + /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or + /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. + /// @param _to The address of the recipient, can be a user or contract. + /// @param _tokenId The ID of the Kitty to transfer. + /// @dev Required for ERC-721 compliance. + function transfer( + address _to, + uint256 _tokenId + ) + external + whenNotPaused + { + // Safety check to prevent against an unexpected 0x0 default. + require(_to != address(0)); + // Disallow transfers to this contract to prevent accidental misuse. + // The contract should never own any kitties (except very briefly + // after a gen0 cat is created and before it goes on auction). + require(_to != address(this)); + // Disallow transfers to the auction contracts to prevent accidental + // misuse. Auction contracts should only take ownership of kitties + // through the allow + transferFrom flow. + require(_to != address(saleAuction)); + require(_to != address(siringAuction)); + + // You can only send your own cat. + require(_owns(msg.sender, _tokenId)); + + // Reassign ownership, clear pending approvals, emit Transfer event. + _transfer(msg.sender, _to, _tokenId); + } + + /// @notice Grant another address the right to transfer a specific Kitty via + /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. + /// @param _to The address to be granted transfer approval. Pass address(0) to + /// clear all approvals. + /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. + /// @dev Required for ERC-721 compliance. + function approve( + address _to, + uint256 _tokenId + ) + external + whenNotPaused + { + // Only an owner can grant transfer approval. + require(_owns(msg.sender, _tokenId)); + + // Register the approval (replacing any previous approval). + _approve(_tokenId, _to); + + // Emit approval event. + emit Approval(msg.sender, _to, _tokenId); + } + + /// @notice Transfer a Kitty owned by another address, for which the calling address + /// has previously been granted transfer approval by the owner. + /// @param _from The address that owns the Kitty to be transfered. + /// @param _to The address that should take ownership of the Kitty. Can be any address, + /// including the caller. + /// @param _tokenId The ID of the Kitty to be transferred. + /// @dev Required for ERC-721 compliance. + function transferFrom( + address _from, + address _to, + uint256 _tokenId + ) + external + whenNotPaused + { + // Safety check to prevent against an unexpected 0x0 default. + require(_to != address(0)); + // Disallow transfers to this contract to prevent accidental misuse. + // The contract should never own any kitties (except very briefly + // after a gen0 cat is created and before it goes on auction). + require(_to != address(this)); + // Check for approval and valid ownership + require(_approvedFor(msg.sender, _tokenId)); + require(_owns(_from, _tokenId)); + + // Reassign ownership (also clears pending approvals and emits Transfer event). + _transfer(_from, _to, _tokenId); + } + + /// @notice Returns the total number of Kitties currently in existence. + /// @dev Required for ERC-721 compliance. + function totalSupply() public view returns (uint) { + return kitties.length - 1; + } + + /// @notice Returns the address currently assigned ownership of a given Kitty. + /// @dev Required for ERC-721 compliance. + function ownerOf(uint256 _tokenId) + external + view + returns (address owner) + { + owner = kittyIndexToOwner[_tokenId]; + + require(owner != address(0)); + } + + /// @notice Returns a list of all Kitty IDs assigned to an address. + /// @param _owner The owner whose Kitties we are interested in. + /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly + /// expensive (it walks the entire Kitty array looking for cats belonging to owner), + /// but it also returns a dynamic array, which is only supported for web3 calls, and + /// not contract-to-contract calls. + function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { + uint256 tokenCount = balanceOf(_owner); + + if (tokenCount == 0) { + // Return an empty array + return new uint256[](0); + } else { + uint256[] memory result = new uint256[](tokenCount); + uint256 totalCats = totalSupply(); + uint256 resultIndex = 0; + + // We count on the fact that all cats have IDs starting at 1 and increasing + // sequentially up to the totalCat count. + uint256 catId; + + for (catId = 1; catId <= totalCats; catId++) { + if (kittyIndexToOwner[catId] == _owner) { + result[resultIndex] = catId; + resultIndex++; + } + } + + return result; + } + } + + /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) + /// This method is licenced under the Apache License. + /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol + function _memcpy(uint _dest, uint _src, uint _len) private view { + // Copy word-length chunks while possible + for(; _len >= 32; _len -= 32) { + assembly { + mstore(_dest, mload(_src)) + } + _dest += 32; + _src += 32; + } + + // Copy remaining bytes + uint256 mask = 256 ** (32 - _len) - 1; + assembly { + let srcpart := and(mload(_src), not(mask)) + let destpart := and(mload(_dest), mask) + mstore(_dest, or(destpart, srcpart)) + } + } + + /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) + /// This method is licenced under the Apache License. + /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol + function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { + string memory outputString = new string(_stringLength); + uint256 outputPtr; + uint256 bytesPtr; + + assembly { + outputPtr := add(outputString, 32) + bytesPtr := _rawBytes + } + + _memcpy(outputPtr, bytesPtr, _stringLength); + + return outputString; + } + + /// @notice Returns a URI pointing to a metadata package for this token conforming to + /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) + /// @param _tokenId The ID number of the Kitty whose metadata should be returned. + function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { + require( address(erc721Metadata) != address(0)); + bytes32[4] memory buffer; + uint256 count; + (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); + + return _toString(buffer, count); + } +} + + + + +/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. +contract KittyBreeding is KittyOwnership { + + /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy + /// timer begins for the matron. + event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); + + /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards + /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by + /// the COO role as the gas price changes. + uint256 public autoBirthFee = 2 finney; + + // Keeps track of number of pregnant kitties. + uint256 public pregnantKitties; + + /// @dev The address of the sibling contract that is used to implement the sooper-sekret + /// genetic combination algorithm. + GeneScienceInterface public geneScience; + + /// @dev Update the address of the genetic contract, can only be called by the CEO. + /// @param _address An address of a GeneScience contract instance to be used from this point forward. + function setGeneScienceAddress(address _address) external onlyCEO { + GeneScienceInterface candidateContract = GeneScienceInterface(_address); + + // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 + require(candidateContract.isGeneScience()); + + // Set the new contract address + geneScience = candidateContract; + } + + /// @dev Checks that a given kitten is able to breed. Requires that the + /// current cooldown is finished (for sires) and also checks that there is + /// no pending pregnancy. + function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { + // In addition to checking the cooldownEndBlock, we also need to check to see if + // the cat has a pending birth; there can be some period of time between the end + // of the pregnacy timer and the birth event. + return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); + } + + /// @dev Check if a sire has authorized breeding with this matron. True if both sire + /// and matron have the same owner, or if the sire has given siring permission to + /// the matron's owner (via approveSiring()). + function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { + address matronOwner = kittyIndexToOwner[_matronId]; + address sireOwner = kittyIndexToOwner[_sireId]; + + // Siring is okay if they have same owner, or if the matron's owner was given + // permission to breed with this sire. + return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); + } + + /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. + /// Also increments the cooldownIndex (unless it has hit the cap). + /// @param _kitten A reference to the Kitty in storage which needs its timer started. + function _triggerCooldown(Kitty storage _kitten) internal { + // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). + _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); + + // Increment the breeding count, clamping it at 13, which is the length of the + // cooldowns array. We could check the array size dynamically, but hard-coding + // this as a constant saves gas. Yay, Solidity! + if (_kitten.cooldownIndex < 13) { + _kitten.cooldownIndex += 1; + } + } + + /// @notice Grants approval to another user to sire with one of your Kitties. + /// @param _addr The address that will be able to sire with your Kitty. Set to + /// address(0) to clear all siring approvals for this Kitty. + /// @param _sireId A Kitty that you own that _addr will now be able to sire with. + function approveSiring(address _addr, uint256 _sireId) + external + whenNotPaused + { + require(_owns(msg.sender, _sireId)); + sireAllowedToAddress[_sireId] = _addr; + } + + /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only + /// be called by the COO address. (This fee is used to offset the gas cost incurred + /// by the autobirth daemon). + function setAutoBirthFee(uint256 val) external onlyCOO { + autoBirthFee = val; + } + + /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation + /// period has passed. + function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { + return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); + } + + /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or + /// in the middle of a siring cooldown). + /// @param _kittyId reference the id of the kitten, any user can inquire about it + function isReadyToBreed(uint256 _kittyId) + public + view + returns (bool) + { + require(_kittyId > 0); + Kitty storage kit = kitties[_kittyId]; + return _isReadyToBreed(kit); + } + + /// @dev Checks whether a kitty is currently pregnant. + /// @param _kittyId reference the id of the kitten, any user can inquire about it + function isPregnant(uint256 _kittyId) + public + view + returns (bool) + { + require(_kittyId > 0); + // A kitty is pregnant if and only if this field is set + return kitties[_kittyId].siringWithId != 0; + } + + /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT + /// check ownership permissions (that is up to the caller). + /// @param _matron A reference to the Kitty struct of the potential matron. + /// @param _matronId The matron's ID. + /// @param _sire A reference to the Kitty struct of the potential sire. + /// @param _sireId The sire's ID + function _isValidMatingPair( + Kitty storage _matron, + uint256 _matronId, + Kitty storage _sire, + uint256 _sireId + ) + private + view + returns(bool) + { + // A Kitty can't breed with itself! + if (_matronId == _sireId) { + return false; + } + + // Kitties can't breed with their parents. + if (_matron.matronId == _sireId || _matron.sireId == _sireId) { + return false; + } + if (_sire.matronId == _matronId || _sire.sireId == _matronId) { + return false; + } + + // We can short circuit the sibling check (below) if either cat is + // gen zero (has a matron ID of zero). + if (_sire.matronId == 0 || _matron.matronId == 0) { + return true; + } + + // Kitties can't breed with full or half siblings. + if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { + return false; + } + if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { + return false; + } + + // Everything seems cool! Let's get DTF. + return true; + } + + /// @dev Internal check to see if a given sire and matron are a valid mating pair for + /// breeding via auction (i.e. skips ownership and siring approval checks). + function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) + internal + view + returns (bool) + { + Kitty storage matron = kitties[_matronId]; + Kitty storage sire = kitties[_sireId]; + return _isValidMatingPair(matron, _matronId, sire, _sireId); + } + + /// @notice Checks to see if two cats can breed together, including checks for + /// ownership and siring approvals. Does NOT check that both cats are ready for + /// breeding (i.e. breedWith could still fail until the cooldowns are finished). + /// TODO: Shouldn't this check pregnancy and cooldowns?!? + /// @param _matronId The ID of the proposed matron. + /// @param _sireId The ID of the proposed sire. + function canBreedWith(uint256 _matronId, uint256 _sireId) + external + view + returns(bool) + { + require(_matronId > 0); + require(_sireId > 0); + Kitty storage matron = kitties[_matronId]; + Kitty storage sire = kitties[_sireId]; + return _isValidMatingPair(matron, _matronId, sire, _sireId) && + _isSiringPermitted(_sireId, _matronId); + } + + /// @dev Internal utility function to initiate breeding, assumes that all breeding + /// requirements have been checked. + function _breedWith(uint256 _matronId, uint256 _sireId) internal { + // Grab a reference to the Kitties from storage. + Kitty storage sire = kitties[_sireId]; + Kitty storage matron = kitties[_matronId]; + + // Mark the matron as pregnant, keeping track of who the sire is. + matron.siringWithId = uint32(_sireId); + + // Trigger the cooldown for both parents. + _triggerCooldown(sire); + _triggerCooldown(matron); + + // Clear siring permission for both parents. This may not be strictly necessary + // but it's likely to avoid confusion! + delete sireAllowedToAddress[_matronId]; + delete sireAllowedToAddress[_sireId]; + + // Every time a kitty gets pregnant, counter is incremented. + pregnantKitties++; + + // Emit the pregnancy event. + emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); + } + + /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you + /// have previously been given Siring approval. Will either make your cat pregnant, or will + /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() + /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) + /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) + function breedWithAuto(uint256 _matronId, uint256 _sireId) + external + payable + whenNotPaused + { + // Checks for payment. + require(msg.value >= autoBirthFee); + + // Caller must own the matron. + require(_owns(msg.sender, _matronId)); + + // Neither sire nor matron are allowed to be on auction during a normal + // breeding operation, but we don't need to check that explicitly. + // For matron: The caller of this function can't be the owner of the matron + // because the owner of a Kitty on auction is the auction house, and the + // auction house will never call breedWith(). + // For sire: Similarly, a sire on auction will be owned by the auction house + // and the act of transferring ownership will have cleared any oustanding + // siring approval. + // Thus we don't need to spend gas explicitly checking to see if either cat + // is on auction. + + // Check that matron and sire are both owned by caller, or that the sire + // has given siring permission to caller (i.e. matron's owner). + // Will fail for _sireId = 0 + require(_isSiringPermitted(_sireId, _matronId)); + + // Grab a reference to the potential matron + Kitty storage matron = kitties[_matronId]; + + // Make sure matron isn't pregnant, or in the middle of a siring cooldown + require(_isReadyToBreed(matron)); + + // Grab a reference to the potential sire + Kitty storage sire = kitties[_sireId]; + + // Make sure sire isn't pregnant, or in the middle of a siring cooldown + require(_isReadyToBreed(sire)); + + // Test that these cats are a valid mating pair. + require(_isValidMatingPair( + matron, + _matronId, + sire, + _sireId + )); + + // All checks passed, kitty gets pregnant! + _breedWith(_matronId, _sireId); + } + + /// @notice Have a pregnant Kitty give birth! + /// @param _matronId A Kitty ready to give birth. + /// @return The Kitty ID of the new kitten. + /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, + /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned + /// to the current owner of the matron. Upon successful completion, both the matron and the + /// new kitten will be ready to breed again. Note that anyone can call this function (if they + /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. + function giveBirth(uint256 _matronId) + external + whenNotPaused + returns(uint256) + { + // Grab a reference to the matron in storage. + Kitty storage matron = kitties[_matronId]; + + // Check that the matron is a valid cat. + require(matron.birthTime != 0); + + // Check that the matron is pregnant, and that its time has come! + require(_isReadyToGiveBirth(matron)); + + // Grab a reference to the sire in storage. + uint256 sireId = matron.siringWithId; + Kitty storage sire = kitties[sireId]; + + // Determine the higher generation number of the two parents + uint16 parentGen = matron.generation; + if (sire.generation > matron.generation) { + parentGen = sire.generation; + } + + // Call the sooper-sekret gene mixing operation. + uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); + + // Make the new kitten! + address owner = kittyIndexToOwner[_matronId]; + uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); + + // Clear the reference to sire from the matron (REQUIRED! Having siringWithId + // set is what marks a matron as being pregnant.) + delete matron.siringWithId; + + // Every time a kitty gives birth counter is decremented. + pregnantKitties--; + + // Send the balance fee to the person who made birth happen. + msg.sender.transfer(autoBirthFee); + + // return the new kitten's ID + return kittenId; + } +} + + + +/// @title Handles creating auctions for sale and siring of kitties. +/// This wrapper of ReverseAuction exists only so that users can create +/// auctions with only one transaction. +contract KittyAuction is KittyBreeding { + + // @notice The auction contract variables are defined in KittyBase to allow + // us to refer to them in KittyOwnership to prevent accidental transfers. + // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. + // `siringAuction` refers to the auction for siring rights of kitties. + + /// @dev Sets the reference to the sale auction. + /// @param _address - Address of sale contract. + function setSaleAuctionAddress(address _address) external onlyCEO { + SaleClockAuction candidateContract = SaleClockAuction(_address); + + // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 + require(candidateContract.isSaleClockAuction()); + + // Set the new contract address + saleAuction = candidateContract; + } + + /// @dev Sets the reference to the siring auction. + /// @param _address - Address of siring contract. + function setSiringAuctionAddress(address _address) external onlyCEO { + SiringClockAuction candidateContract = SiringClockAuction(_address); + + // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 + require(candidateContract.isSiringClockAuction()); + + // Set the new contract address + siringAuction = candidateContract; + } + + /// @dev Put a kitty up for auction. + /// Does some ownership trickery to create auctions in one tx. + function createSaleAuction( + uint256 _kittyId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration + ) + external + whenNotPaused + { + // Auction contract checks input sizes + // If kitty is already on any auction, this will throw + // because it will be owned by the auction contract. + require(_owns(msg.sender, _kittyId)); + // Ensure the kitty is not pregnant to prevent the auction + // contract accidentally receiving ownership of the child. + // NOTE: the kitty IS allowed to be in a cooldown. + require(!isPregnant(_kittyId)); + _approve(_kittyId, address(saleAuction)); + // Sale auction throws if inputs are invalid and clears + // transfer and sire approval after escrowing the kitty. + saleAuction.createAuction( + _kittyId, + _startingPrice, + _endingPrice, + _duration, + msg.sender + ); + } + + /// @dev Put a kitty up for auction to be sire. + /// Performs checks to ensure the kitty can be sired, then + /// delegates to reverse auction. + function createSiringAuction( + uint256 _kittyId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration + ) + external + whenNotPaused + { + // Auction contract checks input sizes + // If kitty is already on any auction, this will throw + // because it will be owned by the auction contract. + require(_owns(msg.sender, _kittyId)); + require(isReadyToBreed(_kittyId)); + _approve(_kittyId, address(siringAuction)); + // Siring auction throws if inputs are invalid and clears + // transfer and sire approval after escrowing the kitty. + siringAuction.createAuction( + _kittyId, + _startingPrice, + _endingPrice, + _duration, + msg.sender + ); + } + + /// @dev Completes a siring auction by bidding. + /// Immediately breeds the winning matron with the sire on auction. + /// @param _sireId - ID of the sire on auction. + /// @param _matronId - ID of the matron owned by the bidder. + function bidOnSiringAuction( + uint256 _sireId, + uint256 _matronId + ) + external + payable + whenNotPaused + { + // Auction contract checks input sizes + require(_owns(msg.sender, _matronId)); + require(isReadyToBreed(_matronId)); + require(_canBreedWithViaAuction(_matronId, _sireId)); + + // Define the current price of the auction. + uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); + require(msg.value >= currentPrice + autoBirthFee); + + // Siring auction will throw if the bid fails. + siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); + _breedWith(uint32(_matronId), uint32(_sireId)); + } + + /// @dev Transfers the balance of the sale auction contract + /// to the KittyCore contract. We use two-step withdrawal to + /// prevent two transfer calls in the auction bid function. + function withdrawAuctionBalances() external onlyCLevel { + saleAuction.withdrawBalance(); + siringAuction.withdrawBalance(); + } +} + + +/// @title all functions related to creating kittens +contract KittyMinting is KittyAuction { + + // Limits the number of cats the contract owner can ever create. + uint256 public constant PROMO_CREATION_LIMIT = 5000; + uint256 public constant GEN0_CREATION_LIMIT = 45000; + + // Constants for gen0 auctions. + uint256 public constant GEN0_STARTING_PRICE = 10 finney; + uint256 public constant GEN0_AUCTION_DURATION = 1 days; + + // Counts the number of cats the contract owner has created. + uint256 public promoCreatedCount; + uint256 public gen0CreatedCount; + + /// @dev we can create promo kittens, up to a limit. Only callable by COO + /// @param _genes the encoded genes of the kitten to be created, any value is accepted + /// @param _owner the future owner of the created kittens. Default to contract COO + function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { + address kittyOwner = _owner; + if (kittyOwner == address(0)) { + kittyOwner = cooAddress; + } + require(promoCreatedCount < PROMO_CREATION_LIMIT); + + promoCreatedCount++; + _createKitty(0, 0, 0, _genes, kittyOwner); + } + + /// @dev Creates a new gen0 kitty with the given genes and + /// creates an auction for it. + function createGen0Auction(uint256 _genes) external onlyCOO { + require(gen0CreatedCount < GEN0_CREATION_LIMIT); + + uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); + _approve(kittyId, address(saleAuction)); + + saleAuction.createAuction( + kittyId, + _computeNextGen0Price(), + 0, + GEN0_AUCTION_DURATION, + address(uint160(address(this))) + ); + + gen0CreatedCount++; + } + + /// @dev Computes the next gen0 auction starting price, given + /// the average of the past 5 prices + 50%. + function _computeNextGen0Price() internal view returns (uint256) { + uint256 avePrice = saleAuction.averageGen0SalePrice(); + + // Sanity check to ensure we don't overflow arithmetic + require(avePrice == uint256(uint128(avePrice))); + + uint256 nextPrice = avePrice + (avePrice / 2); + + // We never auction for less than starting price + if (nextPrice < GEN0_STARTING_PRICE) { + nextPrice = GEN0_STARTING_PRICE; + } + + return nextPrice; + } +} + + + +/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. +contract KittyCore is KittyMinting { + + // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, + // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts + // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are + // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping + // them in their own contracts, we can upgrade them without disrupting the main contract that tracks + // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of + // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. + // Don't worry, I'm sure someone will reverse engineer it soon enough! + // + // Secondly, we break the core contract into multiple files using inheritence, one for each major + // facet of functionality of CK. This allows us to keep related code bundled together while still + // avoiding a single giant file with everything in it. The breakdown is as follows: + // + // - KittyBase: This is where we define the most fundamental code shared throughout the core + // functionality. This includes our main data storage, constants and data types, plus + // internal functions for managing these items. + // + // - KittyAccessControl: This contract manages the various addresses and constraints for operations + // that can be executed only by specific roles. Namely CEO, CFO and COO. + // + // - KittyOwnership: This provides the methods required for basic non-fungible token + // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). + // + // - KittyBreeding: This file contains the methods necessary to breed cats together, including + // keeping track of siring offers, and relies on an external genetic combination contract. + // + // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring + // services. The actual auction functionality is handled in two sibling contracts (one + // for sales and one for siring), while auction creation and bidding is mostly mediated + // through this facet of the core contract. + // + // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. + // We can make up to 5000 "promo" cats that can be given away (especially important when + // the community is new), and all others can only be created and then immediately put up + // for auction via an algorithmically determined starting price. Regardless of how they + // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the + // community to breed, breed, breed! + + // Set in case the core contract is broken and an upgrade is required + address public newContractAddress; + + /// @notice Creates the main CryptoKitties smart contract instance. + constructor() public { + // Starts paused. + paused = true; + + // the creator of the contract is the initial CEO + ceoAddress = msg.sender; + + // the creator of the contract is also the initial COO + cooAddress = msg.sender; + + // start with the mythical kitten 0 - so we don't have generation-0 parent issues + _createKitty(0, 0, 0, uint256(-1), address(0)); + } + + /// @dev Used to mark the smart contract as upgraded, in case there is a serious + /// breaking bug. This method does nothing but keep track of the new contract and + /// emit a message indicating that the new address is set. It's up to clients of this + /// contract to update to the new contract address in that case. (This contract will + /// be paused indefinitely if such an upgrade takes place.) + /// @param _v2Address new address + function setNewAddress(address _v2Address) external onlyCEO whenPaused { + // See README.md for updgrade plan + newContractAddress = _v2Address; + emit ContractUpgrade(_v2Address); + } + + /// @notice No tipping! + /// @dev Reject all Ether from being sent here, unless it's from one of the + /// two auction contracts. (Hopefully, we can prevent user accidents.) + function() external payable { + require( + msg.sender == address(saleAuction) || + msg.sender == address(siringAuction) + ); + } + + /// @notice Returns all the relevant information about a specific kitty. + /// @param _id The ID of the kitty of interest. + function getKitty(uint256 _id) + external + view + returns ( + bool isGestating, + bool isReady, + uint256 cooldownIndex, + uint256 nextActionAt, + uint256 siringWithId, + uint256 birthTime, + uint256 matronId, + uint256 sireId, + uint256 generation, + uint256 genes + ) { + Kitty storage kit = kitties[_id]; + + // if this variable is 0 then it's not gestating + isGestating = (kit.siringWithId != 0); + isReady = (kit.cooldownEndBlock <= block.number); + cooldownIndex = uint256(kit.cooldownIndex); + nextActionAt = uint256(kit.cooldownEndBlock); + siringWithId = uint256(kit.siringWithId); + birthTime = uint256(kit.birthTime); + matronId = uint256(kit.matronId); + sireId = uint256(kit.sireId); + generation = uint256(kit.generation); + genes = kit.genes; + } + + /// @dev Override unpause so it requires all external contract addresses + /// to be set before contract can be unpaused. Also, we can't have + /// newContractAddress set either, because then the contract was upgraded. + /// @notice This is public rather than external so we can call super.unpause + /// without using an expensive CALL. + + function unpause(address payable toAddress, uint256 tokenValue, trcToken tokenId) public onlyCEO whenPaused returns (uint256 r) { + require(address(saleAuction) != address(0)); + require(address(siringAuction) != address(0)); + require(address(geneScience) != address(0)); + require(address(newContractAddress) == address(0)); + toAddress.transferToken(tokenValue, tokenId); + r = address(this).tokenBalance(tokenId); + // Actually unpause the contract. + super.unpause(); + } + + // @dev Allows the CFO to capture the balance available to the contract. + function withdrawBalance() external onlyCFO { + uint256 balance = address(this).balance; + // Subtract all the currently pregnant kittens we have, plus 1 of margin. + uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; + + if (balance > subtractFees) { + cfoAddress.transfer(balance - subtractFees); + } + } +} + + + + + + + + + + + + + +// // Auction wrapper functions + + +// Auction wrapper functions + + + + + + + +/// @title SEKRETOOOO +contract GeneScienceInterface { + + function isGeneScience() public pure returns (bool){ + return true; + } + + /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor + /// @param genes1 genes of mom + /// @param genes2 genes of sire + /// @return the genes that are supposed to be passed down the child + function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ + + return (genes1+genes2+targetBlock)/2; + + +} +} + + + + + + + + + + + + + + + + +/// @title The external contract that is responsible for generating metadata for the kitties, +/// it has one function that will return the data as bytes. +contract ERC721Metadata { + /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. + function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { + if (_tokenId == 1) { + buffer[0] = "Hello World! :D"; + count = 15; + } else if (_tokenId == 2) { + buffer[0] = "I would definitely choose a medi"; + buffer[1] = "um length string."; + count = 49; + } else if (_tokenId == 3) { + buffer[0] = "Lorem ipsum dolor sit amet, mi e"; + buffer[1] = "st accumsan dapibus augue lorem,"; + buffer[2] = " tristique vestibulum id, libero"; + buffer[3] = " suscipit varius sapien aliquam."; + count = 128; + } + } +} + + + + + + + + + + + + + + + +/// @title Auction Core +/// @dev Contains models, variables, and internal methods for the auction. +/// @notice We omit a fallback function to prevent accidental sends to this contract. +contract ClockAuctionBase { + + // Represents an auction on an NFT + struct Auction { + // Current owner of NFT + address payable seller; + // Price (in wei) at beginning of auction + uint128 startingPrice; + // Price (in wei) at end of auction + uint128 endingPrice; + // Duration (in seconds) of auction + uint64 duration; + // Time when auction started + // NOTE: 0 if this auction has been concluded + uint64 startedAt; + } + + // Reference to contract tracking NFT ownership + ERC721 public nonFungibleContract; + + // Cut owner takes on each auction, measured in basis points (1/100 of a percent). + // Values 0-10,000 map to 0%-100% + uint256 public ownerCut; + + // Map from token ID to their corresponding auction. + mapping (uint256 => Auction) tokenIdToAuction; + + event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); + event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); + event AuctionCancelled(uint256 tokenId); + + /// @dev Returns true if the claimant owns the token. + /// @param _claimant - Address claiming to own the token. + /// @param _tokenId - ID of token whose ownership to verify. + function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { + return (nonFungibleContract.ownerOf(_tokenId) == _claimant); + } + + /// @dev Escrows the NFT, assigning ownership to this contract. + /// Throws if the escrow fails. + /// @param _owner - Current owner address of token to escrow. + /// @param _tokenId - ID of token whose approval to verify. + function _escrow(address _owner, uint256 _tokenId) internal { + // it will throw if transfer fails + nonFungibleContract.transferFrom(_owner, address(this), _tokenId); + } + + /// @dev Transfers an NFT owned by this contract to another address. + /// Returns true if the transfer succeeds. + /// @param _receiver - Address to transfer NFT to. + /// @param _tokenId - ID of token to transfer. + function _transfer(address _receiver, uint256 _tokenId) internal { + // it will throw if transfer fails + nonFungibleContract.transfer(_receiver, _tokenId); + } + + /// @dev Adds an auction to the list of open auctions. Also fires the + /// AuctionCreated event. + /// @param _tokenId The ID of the token to be put on auction. + /// @param _auction Auction to add. + function _addAuction(uint256 _tokenId, Auction memory _auction) internal { + // Require that all auctions have a duration of + // at least one minute. (Keeps our math from getting hairy!) + require(_auction.duration >= 1 minutes); + + tokenIdToAuction[_tokenId] = _auction; + + emit AuctionCreated( + uint256(_tokenId), + uint256(_auction.startingPrice), + uint256(_auction.endingPrice), + uint256(_auction.duration) + ); + } + + /// @dev Cancels an auction unconditionally. + function _cancelAuction(uint256 _tokenId, address _seller) internal { + _removeAuction(_tokenId); + _transfer(_seller, _tokenId); + emit AuctionCancelled(_tokenId); + } + + /// @dev Computes the price and transfers winnings. + /// Does NOT transfer ownership of token. + function _bid(uint256 _tokenId, uint256 _bidAmount) + internal + returns (uint256) + { + // Get a reference to the auction struct + Auction storage auction = tokenIdToAuction[_tokenId]; + + // Explicitly check that this auction is currently live. + // (Because of how Ethereum mappings work, we can't just count + // on the lookup above failing. An invalid _tokenId will just + // return an auction object that is all zeros.) + require(_isOnAuction(auction)); + + // Check that the bid is greater than or equal to the current price + uint256 price = _currentPrice(auction); + require(_bidAmount >= price); + + // Grab a reference to the seller before the auction struct + // gets deleted. + address payable seller = auction.seller; + + // The bid is good! Remove the auction before sending the fees + // to the sender so we can't have a reentrancy attack. + _removeAuction(_tokenId); + + // Transfer proceeds to seller (if there are any!) + if (price > 0) { + // Calculate the auctioneer's cut. + // (NOTE: _computeCut() is guaranteed to return a + // value <= price, so this subtraction can't go negative.) + uint256 auctioneerCut = _computeCut(price); + uint256 sellerProceeds = price - auctioneerCut; + + // NOTE: Doing a transfer() in the middle of a complex + // method like this is generally discouraged because of + // reentrancy attacks and DoS attacks if the seller is + // a contract with an invalid fallback function. We explicitly + // guard against reentrancy attacks by removing the auction + // before calling transfer(), and the only thing the seller + // can DoS is the sale of their own asset! (And if it's an + // accident, they can call cancelAuction(). ) + seller.transfer(sellerProceeds); + } + + // Calculate any excess funds included with the bid. If the excess + // is anything worth worrying about, transfer it back to bidder. + // NOTE: We checked above that the bid amount is greater than or + // equal to the price so this cannot underflow. + uint256 bidExcess = _bidAmount - price; + + // Return the funds. Similar to the previous transfer, this is + // not susceptible to a re-entry attack because the auction is + // removed before any transfers occur. + msg.sender.transfer(bidExcess); + + // Tell the world! + emit AuctionSuccessful(_tokenId, price, msg.sender); + + return price; + } + + /// @dev Removes an auction from the list of open auctions. + /// @param _tokenId - ID of NFT on auction. + function _removeAuction(uint256 _tokenId) internal { + delete tokenIdToAuction[_tokenId]; + } + + /// @dev Returns true if the NFT is on auction. + /// @param _auction - Auction to check. + function _isOnAuction(Auction storage _auction) internal view returns (bool) { + return (_auction.startedAt > 0); + } + + /// @dev Returns current price of an NFT on auction. Broken into two + /// functions (this one, that computes the duration from the auction + /// structure, and the other that does the price computation) so we + /// can easily test that the price computation works correctly. + function _currentPrice(Auction storage _auction) + internal + view + returns (uint256) + { + uint256 secondsPassed = 0; + + // A bit of insurance against negative values (or wraparound). + // Probably not necessary (since Ethereum guarnatees that the + // now variable doesn't ever go backwards). + if (now > _auction.startedAt) { + secondsPassed = now - _auction.startedAt; + } + + return _computeCurrentPrice( + _auction.startingPrice, + _auction.endingPrice, + _auction.duration, + secondsPassed + ); + } + + /// @dev Computes the current price of an auction. Factored out + /// from _currentPrice so we can run extensive unit tests. + /// When testing, make this function public and turn on + /// `Current price computation` test suite. + function _computeCurrentPrice( + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration, + uint256 _secondsPassed + ) + internal + pure + returns (uint256) + { + // NOTE: We don't use SafeMath (or similar) in this function because + // all of our public functions carefully cap the maximum values for + // time (at 64-bits) and currency (at 128-bits). _duration is + // also known to be non-zero (see the require() statement in + // _addAuction()) + if (_secondsPassed >= _duration) { + // We've reached the end of the dynamic pricing portion + // of the auction, just return the end price. + return _endingPrice; + } else { + // Starting price can be higher than ending price (and often is!), so + // this delta can be negative. + int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); + + // This multiplication can't overflow, _secondsPassed will easily fit within + // 64-bits, and totalPriceChange will easily fit within 128-bits, their product + // will always fit within 256-bits. + int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); + + // currentPriceChange can be negative, but if so, will have a magnitude + // less that _startingPrice. Thus, this result will always end up positive. + int256 currentPrice = int256(_startingPrice) + currentPriceChange; + + return uint256(currentPrice); + } + } + + /// @dev Computes owner's cut of a sale. + /// @param _price - Sale price of NFT. + function _computeCut(uint256 _price) internal view returns (uint256) { + // NOTE: We don't use SafeMath (or similar) in this function because + // all of our entry functions carefully cap the maximum values for + // currency (at 128-bits), and ownerCut <= 10000 (see the require() + // statement in the ClockAuction constructor). The result of this + // function is always guaranteed to be <= _price. + return _price * ownerCut / 10000; + } + +} + + + + + + + +/** + * @title Pausable + * @dev Base contract which allows children to implement an emergency stop mechanism. + */ +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + /** + * @dev modifier to allow actions only when the contract IS paused + */ + modifier whenNotPaused() { + require(!paused); + _; + } + + /** + * @dev modifier to allow actions only when the contract IS NOT paused + */ + modifier whenPaused { + require(paused); + _; + } + + /** + * @dev called by the owner to pause, triggers stopped state + */ + function pause() onlyOwner whenNotPaused public returns (bool) { + paused = true; + emit Pause(); + return true; + } + + /** + * @dev called by the owner to unpause, returns to normal state + */ + function unpause() onlyOwner whenPaused public returns (bool) { + paused = false; + emit Unpause(); + return true; + } +} + + +/// @title Clock auction for non-fungible tokens. +/// @notice We omit a fallback function to prevent accidental sends to this contract. +contract ClockAuction is Pausable, ClockAuctionBase { + + /// @dev The ERC-165 interface signature for ERC-721. + /// Ref: https://github.com/ethereum/EIPs/issues/165 + /// Ref: https://github.com/ethereum/EIPs/issues/721 + bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); + + /// @dev Constructor creates a reference to the NFT ownership contract + /// and verifies the owner cut is in the valid range. + /// @param _nftAddress - address of a deployed contract implementing + /// the Nonfungible Interface. + /// @param _cut - percent cut the owner takes on each auction, must be + /// between 0-10,000. + constructor(address _nftAddress, uint256 _cut) public { + require(_cut <= 10000); + ownerCut = _cut; + + ERC721 candidateContract = ERC721(_nftAddress); + require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); + nonFungibleContract = candidateContract; + } + + /// @dev Remove all Ether from the contract, which is the owner's cuts + /// as well as any Ether sent directly to the contract address. + /// Always transfers to the NFT contract, but can be called either by + /// the owner or the NFT contract. + function withdrawBalance() external { + address payable nftAddress = address(uint160(address(nonFungibleContract))); + + require( + msg.sender == owner || + msg.sender == nftAddress + ); + // We are using this boolean method to make sure that even if one fails it will still work + bool res = nftAddress.send(address(this).balance); + } + + /// @dev Creates and begins a new auction. + /// @param _tokenId - ID of token to auction, sender must be owner. + /// @param _startingPrice - Price of item (in wei) at beginning of auction. + /// @param _endingPrice - Price of item (in wei) at end of auction. + /// @param _duration - Length of time to move between starting + /// price and ending price (in seconds). + /// @param _seller - Seller, if not the message sender + function createAuction( + uint256 _tokenId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration, + address payable _seller + ) + external + whenNotPaused + { + // Sanity check that no inputs overflow how many bits we've allocated + // to store them in the auction struct. + require(_startingPrice == uint256(uint128(_startingPrice))); + require(_endingPrice == uint256(uint128(_endingPrice))); + require(_duration == uint256(uint64(_duration))); + + require(_owns(msg.sender, _tokenId)); + _escrow(msg.sender, _tokenId); + Auction memory auction = Auction( + _seller, + uint128(_startingPrice), + uint128(_endingPrice), + uint64(_duration), + uint64(now) + ); + _addAuction(_tokenId, auction); + } + + /// @dev Bids on an open auction, completing the auction and transferring + /// ownership of the NFT if enough Ether is supplied. + /// @param _tokenId - ID of token to bid on. + function bid(uint256 _tokenId) + external + payable + whenNotPaused + { + // _bid will throw if the bid or funds transfer fails + _bid(_tokenId, msg.value); + _transfer(msg.sender, _tokenId); + } + + /// @dev Cancels an auction that hasn't been won yet. + /// Returns the NFT to original owner. + /// @notice This is a state-modifying function that can + /// be called while the contract is paused. + /// @param _tokenId - ID of token on auction + function cancelAuction(uint256 _tokenId) + external + { + Auction storage auction = tokenIdToAuction[_tokenId]; + require(_isOnAuction(auction)); + address seller = auction.seller; + require(msg.sender == seller); + _cancelAuction(_tokenId, seller); + } + + /// @dev Cancels an auction when the contract is paused. + /// Only the owner may do this, and NFTs are returned to + /// the seller. This should only be used in emergencies. + /// @param _tokenId - ID of the NFT on auction to cancel. + function cancelAuctionWhenPaused(uint256 _tokenId) + whenPaused + onlyOwner + external + { + Auction storage auction = tokenIdToAuction[_tokenId]; + require(_isOnAuction(auction)); + _cancelAuction(_tokenId, auction.seller); + } + + /// @dev Returns auction info for an NFT on auction. + /// @param _tokenId - ID of NFT on auction. + function getAuction(uint256 _tokenId) + external + view + returns + ( + address seller, + uint256 startingPrice, + uint256 endingPrice, + uint256 duration, + uint256 startedAt + ) { + Auction storage auction = tokenIdToAuction[_tokenId]; + require(_isOnAuction(auction)); + return ( + auction.seller, + auction.startingPrice, + auction.endingPrice, + auction.duration, + auction.startedAt + ); + } + + /// @dev Returns the current price of an auction. + /// @param _tokenId - ID of the token price we are checking. + function getCurrentPrice(uint256 _tokenId) + external + view + returns (uint256) + { + Auction storage auction = tokenIdToAuction[_tokenId]; + require(_isOnAuction(auction)); + return _currentPrice(auction); + } + +} + + +/// @title Reverse auction modified for siring +/// @notice We omit a fallback function to prevent accidental sends to this contract. +contract SiringClockAuction is ClockAuction { + + // @dev Sanity check that allows us to ensure that we are pointing to the + // right auction in our setSiringAuctionAddress() call. + bool public isSiringClockAuction = true; + + // Delegate constructor + constructor(address _nftAddr, uint256 _cut) public + ClockAuction(_nftAddr, _cut) {} + + /// @dev Creates and begins a new auction. Since this function is wrapped, + /// require sender to be KittyCore contract. + /// @param _tokenId - ID of token to auction, sender must be owner. + /// @param _startingPrice - Price of item (in wei) at beginning of auction. + /// @param _endingPrice - Price of item (in wei) at end of auction. + /// @param _duration - Length of auction (in seconds). + /// @param _seller - Seller, if not the message sender + function createAuction( + uint256 _tokenId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration, + address payable _seller + ) + external + { + // Sanity check that no inputs overflow how many bits we've allocated + // to store them in the auction struct. + require(_startingPrice == uint256(uint128(_startingPrice))); + require(_endingPrice == uint256(uint128(_endingPrice))); + require(_duration == uint256(uint64(_duration))); + + require(msg.sender == address(nonFungibleContract)); + _escrow(_seller, _tokenId); + Auction memory auction = Auction( + _seller, + uint128(_startingPrice), + uint128(_endingPrice), + uint64(_duration), + uint64(now) + ); + _addAuction(_tokenId, auction); + } + + /// @dev Places a bid for siring. Requires the sender + /// is the KittyCore contract because all bid methods + /// should be wrapped. Also returns the kitty to the + /// seller rather than the winner. + function bid(uint256 _tokenId) + external + payable + { + require(msg.sender == address(nonFungibleContract)); + address seller = tokenIdToAuction[_tokenId].seller; + // _bid checks that token ID is valid and will throw if bid fails + _bid(_tokenId, msg.value); + // We transfer the kitty back to the seller, the winner will get + // the offspring + _transfer(seller, _tokenId); + } + +} + + + + + +/// @title Clock auction modified for sale of kitties +/// @notice We omit a fallback function to prevent accidental sends to this contract. +contract SaleClockAuction is ClockAuction { + + // @dev Sanity check that allows us to ensure that we are pointing to the + // right auction in our setSaleAuctionAddress() call. + bool public isSaleClockAuction = true; + + // Tracks last 5 sale price of gen0 kitty sales + uint256 public gen0SaleCount; + uint256[5] public lastGen0SalePrices; + + // Delegate constructor + constructor(address _nftAddr, uint256 _cut) public + ClockAuction(_nftAddr, _cut) {} + + /// @dev Creates and begins a new auction. + /// @param _tokenId - ID of token to auction, sender must be owner. + /// @param _startingPrice - Price of item (in wei) at beginning of auction. + /// @param _endingPrice - Price of item (in wei) at end of auction. + /// @param _duration - Length of auction (in seconds). + /// @param _seller - Seller, if not the message sender + function createAuction( + uint256 _tokenId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration, + address payable _seller + ) + external + { + // Sanity check that no inputs overflow how many bits we've allocated + // to store them in the auction struct. + require(_startingPrice == uint256(uint128(_startingPrice))); + require(_endingPrice == uint256(uint128(_endingPrice))); + require(_duration == uint256(uint64(_duration))); + + require(msg.sender == address(nonFungibleContract)); + _escrow(_seller, _tokenId); + Auction memory auction = Auction( + _seller, + uint128(_startingPrice), + uint128(_endingPrice), + uint64(_duration), + uint64(now) + ); + _addAuction(_tokenId, auction); + } + + /// @dev Updates lastSalePrice if seller is the nft contract + /// Otherwise, works the same as default bid method. + function bid(uint256 _tokenId) + external + payable + { + // _bid verifies token ID size + address seller = tokenIdToAuction[_tokenId].seller; + uint256 price = _bid(_tokenId, msg.value); + _transfer(msg.sender, _tokenId); + + // If not a gen0 auction, exit + if (seller == address(nonFungibleContract)) { + // Track gen0 sale prices + lastGen0SalePrices[gen0SaleCount % 5] = price; + gen0SaleCount++; + } + } + + function averageGen0SalePrice() external view returns (uint256) { + uint256 sum = 0; + for (uint256 i = 0; i < 5; i++) { + sum += lastGen0SalePrices[i]; + } + return sum / 5; + } + +} + + + + + + + diff --git a/framework/src/test/resources/soliditycode_0.5.15/addressCheckNew.sol b/framework/src/test/resources/soliditycode_0.5.15/addressCheckNew.sol new file mode 100644 index 00000000000..3c10b8c680d --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/addressCheckNew.sol @@ -0,0 +1,9 @@ +pragma experimental ABIEncoderV2; +contract testIsContract{ + function checkAddress(address addr) public returns (address){ + return addr; + } + function checkAddress2(address addr) pure public returns(address){ + return addr; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addressCheckOld.sol b/framework/src/test/resources/soliditycode_0.5.15/addressCheckOld.sol new file mode 100644 index 00000000000..6c6b15d1736 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/addressCheckOld.sol @@ -0,0 +1,8 @@ +contract testIsContract{ + function checkAddress(address addr) public returns (address){ + return addr; + } + function checkAddress2(address addr) pure public returns (address){ + return addr; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/altbn.sol b/framework/src/test/resources/soliditycode_0.5.15/altbn.sol new file mode 100644 index 00000000000..ee6ca1a98c9 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/altbn.sol @@ -0,0 +1,63 @@ +pragma solidity ^0.5.12; + +contract AltBn128 { + constructor() public payable {} + function callBn256Add(bytes32 ax, bytes32 ay, bytes32 bx, bytes32 by) public returns (bytes32[2] memory result) { + bytes32[4] memory input; + input[0] = ax; + input[1] = ay; + input[2] = bx; + input[3] = by; + assembly { + let success := call(gas, 0x06, 0, input, 0x80, result, 0x40) + } + + } + + function callBn256AddNoValue(bytes32 ax, bytes32 ay, bytes32 bx, bytes32 by) public returns + (bytes32[2] memory result) { + bytes32[4] memory input; + input[0] = ax; + input[1] = ay; + input[2] = bx; + input[3] = by; + assembly { + let success := call(gas, 0xac, 0, input, 0x80, result, 0x40) + } + } + + function callBn256ScalarMul(bytes32 x, bytes32 y, bytes32 scalar) public returns (bytes32[2] memory result) { + bytes32[3] memory input; + input[0] = x; + input[1] = y; + input[2] = scalar; + assembly { + let success := call(gas, 0x07, 0, input, 0x60, result, 0x40) + switch success + case 0 { + revert(0,0) + } + } + } + + function callBn256Pairing(bytes memory input) public returns (bytes32 result) { + // input is a serialized bytes stream of (a1, b1, a2, b2, ..., ak, bk) from (G_1 x G_2)^k + uint256 len = input.length; + require(len % 192 == 0); + assembly { + let memPtr := mload(0x40) + let success := call(gas, 0x08, 0, add(input, 0x20), len, memPtr, 0x20) + switch success + case 0 { + revert(0,0) + } default { + result := mload(memPtr) + } + } + } + + function convert(uint256 num) public view returns(bytes32) { + return bytes32(num); + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/arrayLength001.sol b/framework/src/test/resources/soliditycode_0.5.15/arrayLength001.sol new file mode 100644 index 00000000000..1c7e4e9dac2 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/arrayLength001.sol @@ -0,0 +1,16 @@ + +contract Test { + byte[] a; + + function ChangeSize() external returns(byte[] memory) { + a.push(0x01); + a.length = 3; + + a.length ++; + a.length --; + a.length --; + + a.pop(); + return a; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/assemblyTest.sol b/framework/src/test/resources/soliditycode_0.5.15/assemblyTest.sol new file mode 100644 index 00000000000..6da31ff7b6f --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/assemblyTest.sol @@ -0,0 +1,62 @@ +pragma solidity ^0.5.12; + +contract assemblyTest { + + uint constant x = 1; + uint constant y = x; + function getZuint() public view returns (uint) { + uint z = y + 1; + assembly { + z := y + } + return z; + } + + function getZuint2() public returns (uint) { + uint z = y + 1; + assembly { + z := y + } + return z; + } + + bool constant bool1 = true; + bool constant bool2 = bool1; + function getZbool() public view returns (bool) { + bool z; + assembly { + z := bool2 + } + return z; + } + + function getZbool2() public returns (bool) { + bool z; + assembly { + z := bool2 + } + return z; + } + + +// string constant string1 = "abc"; +// string constant string2 = string1; +// function getZstring() public view returns (string memory) { +// string memory z; +// assembly { +// z := string2 +// } +// return z; +// } + + +// address origin1 = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; +// address origin2 = origin1; +// function getZaddress() public view returns (address) { +// address z; +// assembly { +// z := origin2 +// } +// return z; +// } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest1DivideInt.sol b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest1DivideInt.sol new file mode 100644 index 00000000000..ca38896acee --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest1DivideInt.sol @@ -0,0 +1,7 @@ +//pragma solidity ^0.4.0; + +contract divideIHaveArgsReturnStorage{ +function divideIHaveArgsReturn(int x,int y) public returns (int z) { +return z = x / y; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest2FindArgsContractMinTest.sol b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest2FindArgsContractMinTest.sol new file mode 100644 index 00000000000..b8565d2578e --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest2FindArgsContractMinTest.sol @@ -0,0 +1,10 @@ +//pragma solidity ^0.4.0; +contract findArgsIContract{ +function findArgsByIndex1(uint i) public returns (uint z) { +uint[] memory a = new uint[](3); +a[0]=1; +a[1]=2; +a[2]=3; +return a[i]; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest3ByteMinContract.sol b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest3ByteMinContract.sol new file mode 100644 index 00000000000..6d846fad7f4 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest3ByteMinContract.sol @@ -0,0 +1,11 @@ +pragma solidity >0.5.0; +contract byteContract{ +bytes b; +function testBytesGet(uint i) public returns (bytes1){ +b = new bytes(3); +b[0]=0x0b; +b[1]=0x0c; +b[2]=0x0d; +return b[i]; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest4Enum.sol b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest4Enum.sol new file mode 100644 index 00000000000..4a740d4a089 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest4Enum.sol @@ -0,0 +1,13 @@ +//pragma solidity ^0.4.4; + +contract enumContract { + enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } + ActionChoices _choice; + function setGoStraight(ActionChoices choice) public { + _choice = choice; + } + + function getChoice() public returns (ActionChoices) { + return _choice; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest5MoveRight.sol b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest5MoveRight.sol new file mode 100644 index 00000000000..7194520fb09 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest5MoveRight.sol @@ -0,0 +1,7 @@ +//pragma solidity ^0.4.0; + +contract binaryRightContract{ + function binaryMoveR(int i)public returns (int z) { + return z = 5 >> i; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest6UninitializedContract.sol b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest6UninitializedContract.sol new file mode 100644 index 00000000000..1ff2215abdb --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest6UninitializedContract.sol @@ -0,0 +1,27 @@ +//pragma solidity ^0.4.0; +contract uni { +function b(int x, int y) internal returns (int) +{ + return x * y; +} + +function test1() external returns (int) +{ + // Variable containing a function pointer + function (int, int) internal returns (int) funcPtr; + + funcPtr = b; + + // This call to funcPtr will succeed + return funcPtr(4, 5); +} + +function test2() external returns (int) +{ + // Variable containing a function pointer + function (int, int) internal returns (int) funcPtr; + + // This call will fail because funcPtr is still a zero-initialized function pointer + return funcPtr(4, 5); +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest7TestAssertContract.sol b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest7TestAssertContract.sol new file mode 100644 index 00000000000..0bfd6fbd04e --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest7TestAssertContract.sol @@ -0,0 +1,15 @@ +pragma solidity >0.5.0; +contract TestThrowsContract{ + function testAssert() public{ + assert(1==2); + } + function testRequire() public{ + require(2==1); + } + function testRevert() public{ + revert(); + } + function testThrow() public{ + revert(); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign.sol b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign.sol new file mode 100644 index 00000000000..9e1c1b289b5 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign.sol @@ -0,0 +1,14 @@ +pragma experimental ABIEncoderV2; +contract Demo { + + function testArray2(bytes memory data) public returns(bool, bytes memory){ + return address(0x9).delegatecall(data); + } + + function testArray4(bytes memory data) public { + //address(0x1).delegatecall(data); + } + //function testArray3(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { + //address(0x9).delegatecall(hash,signatures,addresses); + //} +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign001.sol b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign001.sol new file mode 100644 index 00000000000..57e051ce415 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign001.sol @@ -0,0 +1,10 @@ +pragma experimental ABIEncoderV2; +contract Demo { + function testPure(bytes32 hash, bytes[] memory signatures, address[] memory addresses) pure public returns(bytes32){ + return batchvalidatesign(hash, signatures, addresses); + } + + function testArray(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns(bytes32){ + return batchvalidatesign(hash, signatures, addresses); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign002.sol b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign002.sol new file mode 100644 index 00000000000..375cec3a2a2 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign002.sol @@ -0,0 +1,8 @@ +pragma experimental ABIEncoderV2; +contract Demo { + function testArray(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns(bytes32){ + + return batchvalidatesign(hash, signatures, addresses); + + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign003.sol b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign003.sol new file mode 100644 index 00000000000..c43536af499 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign003.sol @@ -0,0 +1,11 @@ +pragma experimental ABIEncoderV2; + +contract Demo { +bytes32 public result; +constructor (bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { + result = batchvalidatesign(hash, signatures, addresses); +} +function testConstructor() public returns(bytes32){ + return result; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign005.sol b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign005.sol new file mode 100644 index 00000000000..3a6ca362973 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign005.sol @@ -0,0 +1,14 @@ +pragma experimental ABIEncoderV2; +contract Demo { + + function testArray2(bytes memory data) public returns(bool, bytes memory){ + return address(0x9).delegatecall(data); + } + + function testArray4(bytes memory data) public { + //address(0x1).delegatecall(data); + } + function testArray3(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { + //address(0x9).delegatecall(hash,signatures,addresses); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign007.sol b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign007.sol new file mode 100644 index 00000000000..974ffb34efe --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign007.sol @@ -0,0 +1,17 @@ +pragma experimental ABIEncoderV2; + +contract Demo { + bytes32 public result; + + constructor (bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { + result = batchvalidatesign(hash, signatures, addresses); + } + + function testConstructor() public returns(bytes32){ + return result; + } + + function testConstructorPure() public view returns(bytes32){ + return result; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign02.sol b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign02.sol new file mode 100644 index 00000000000..375cec3a2a2 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign02.sol @@ -0,0 +1,8 @@ +pragma experimental ABIEncoderV2; +contract Demo { + function testArray(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns(bytes32){ + + return batchvalidatesign(hash, signatures, addresses); + + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/callValueGasPure.sol b/framework/src/test/resources/soliditycode_0.5.15/callValueGasPure.sol new file mode 100644 index 00000000000..ed4877e1ce4 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/callValueGasPure.sol @@ -0,0 +1,8 @@ + +contract C { +function check(address a) external pure returns (bool success) { + a.call.value(42).gas(42); + a.call.gas(42); + //a.call.value(1).gas(42)("fwefewf"); +} +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/calldata.sol b/framework/src/test/resources/soliditycode_0.5.15/calldata.sol new file mode 100644 index 00000000000..6e877ac1b2f --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/calldata.sol @@ -0,0 +1,33 @@ +pragma experimental ABIEncoderV2; + +contract C { + struct S { uint256 a; } + + function f(S calldata s) external returns (bytes memory) { + return abi.encode(s); + } + + function g(S calldata s) external returns (bytes memory) { + return this.f(s); + } + + function m(uint256[] calldata) external pure returns (bytes memory) { + return msg.data; + } + function h(uint8[] calldata s) external pure returns (bytes memory) { + return abi.encode(s); + } + function i(uint8[][2] calldata s, uint256 which) external view returns (bytes memory) { + return this.h(s[which]); + } + function j(bytes calldata s) external pure returns (bytes memory) { + return abi.encode(s); + } + function k(bytes[2] calldata s, uint256 which) external view returns (bytes memory) { + return this.j(s[which]); + } + function l(function() external returns (uint)[] calldata s) external returns (uint, uint, uint) { + assert(s.length == 3); + return (s[0](), s[1](), s[2]()); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/callvalue.sol b/framework/src/test/resources/soliditycode_0.5.15/callvalue.sol new file mode 100644 index 00000000000..ee2a30342c5 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/callvalue.sol @@ -0,0 +1,9 @@ +contract Callvalue { +function check() public payable returns(uint) { + uint256 wad; + assembly { + wad := callvalue + } + return wad; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/chainid001.sol b/framework/src/test/resources/soliditycode_0.5.15/chainid001.sol new file mode 100644 index 00000000000..c057a83b325 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/chainid001.sol @@ -0,0 +1,20 @@ +pragma solidity ^0.5.12; + +contract IstanbulTest { + constructor() public payable {} + function getId() public view returns(uint256){ + uint256 id; + assembly { + id := chainid() + } + return id; + } + + function getBalance(address src) public view returns(uint256){ + return address(src).balance; + } + + function getBalance() public view returns(uint256){ + return address(this).balance; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/codeSaftySupport.sol b/framework/src/test/resources/soliditycode_0.5.15/codeSaftySupport.sol new file mode 100644 index 00000000000..45a4beee384 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/codeSaftySupport.sol @@ -0,0 +1,19 @@ +//pragma solidity ^0.4.24; + +contract IllegalDecorate { + +constructor() payable public{} + +function() payable external{} + +event log(uint256); + +function transferToken(address payable toAddress, uint256 tokenValue) public payable { +emit log(msg.value); +emit log(msg.tokenvalue); +emit log(msg.tokenid); +toAddress.transferToken(msg.tokenvalue, msg.tokenid); +toAddress.transfer(msg.value); +} + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/codeSaftyUnsupport.sol b/framework/src/test/resources/soliditycode_0.5.15/codeSaftyUnsupport.sol new file mode 100644 index 00000000000..220d66b2257 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/codeSaftyUnsupport.sol @@ -0,0 +1,56 @@ +//pragma solidity ^0.4.24; + +contract SubC { + +event log(string); + +function () payable external{} + +function receiveToken() payable public{} + +function getBalance() view public returns (uint256 r) { +r = address(this).balance; +} +} + +contract UseDot { +constructor() payable public{} +function() payable external{} +mapping(address => mapping(trcToken => uint256)) sender_tokens; + +function trigger1(address payable addr, trcToken tokenInputId) payable public { + //address(SubC(addr)).call.value(1000).tokenId(tokenInputId)(abi.encodeWithSignature("receiveToken()")); // ERROR +} + +function trigger2(address payable addr) payable public { +// addr.transferToken.value(10)(10, 0x6e6d62); // ERROR +} + +function trigger3(address payable addr) payable public { + // address(SubC(addr)).receiveToken.tokenvalue(10)(); // ERROR +} + +function trigger4(address payable addr) payable public { + //SubC(addr).receiveToken.tokenId(0x6e6d62)(); // ERROR +} + +function trigger5(address payable addr) payable public { + SubC(addr).receiveToken.value(10)(); +} + +function trigger6(address payable addr, trcToken tokenId) payable public { +address(SubC(addr)).call.value(1000)(abi.encodeWithSignature("transferToken(uint256, trcToken)", 10, tokenId)); +} + +function trigger7(address addr) payable public { + //sender_tokens[msg.sender][msg.tokenid] += msg.tokenvalue; // compile success, no necessary to trigger +} + +function trigger8(address addr) public payable returns(bytes memory r){ +// r = msg.data; // compile success, no necessary to trigger +} + +function getBalance() public returns (uint256 r){ +r = address(this).balance; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage001.sol b/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage001.sol new file mode 100644 index 00000000000..1f584923a55 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage001.sol @@ -0,0 +1,159 @@ +contract NotView { + uint256 public num = 123; + function setnum() public returns(uint256){ + num = num + 15; + return num; + } +} +contract NotViewInterface{ + function setnum() public returns(uint256); +} +contract UseNotView { + function setnumuseproxy(address contractAddress) public returns(uint256){ + NotViewInterface inter = NotViewInterface(contractAddress); + return inter.setnum(); + } +} +contract viewCall { + bool stopped = false; + int i = 32482989; + int i2 = -32482989; + uint ui = 23487823; + address origin = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; + bytes32 b32 = bytes32(uint256(0xdCad3a6d3569DF655070DEd0)); + bytes bs = new bytes(3); + string s = "123qwe"; + enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } + ActionChoices choice = ActionChoices.GoRight; + int64[] b = [-1, 2, -3]; + int32[2][] tmp_h = [[1,2],[3,4],[5,6]]; + int256[2][2] tmp_i = [[11,22],[33,44]]; + mapping (address => uint256) public mapa; + constructor() payable public{ + mapa[address(0x00)] = 34; + } + event log(int); + event log(uint); + event log(bool); + event log(address); + event log(bytes32); + event log(bytes); + event log(string); + event log(ActionChoices); + event log(int64[]); + event log(int32[2][]); + event log(int256[2][2]); + function changeBool(bool param) public returns (bool){ + stopped = param; + emit log(stopped); + return stopped; + } + function getBool() public returns (bool){ + emit log(stopped); + return stopped; + } + function changeInt(int param) public returns (int){ + i = param; + emit log(i); + return i; + } + function getInt() public returns (int){ + emit log(i); + return i; + } + function changeNegativeInt(int param) public returns (int){ + i2 = param; + emit log(i2); + return i2; + } + function getNegativeInt() public returns (int){ + emit log(i2); + return i2; + } + function changeUint(uint param) public returns (uint){ + ui = param; + emit log(ui); + return ui; + } + function getUint() public returns (uint){ + emit log(ui); + return ui; + } + function changeAddress(address param) public returns (address){ + origin = param; + emit log(origin); + return origin; + } + function getAddress() public returns (address){ + emit log(origin); + return origin; + } + function changeBytes32(bytes32 param) public returns (bytes32){ + b32 = param; + emit log(b32); + return b32; + } + function getBytes32() public returns (bytes32){ + emit log(b32); + return b32; + } + function changeBytes(bytes memory param) public returns (bytes memory){ + bs = param; + emit log(bs); + return bs; + } + function getBytes() public returns (bytes memory){ + emit log(bs); + return bs; + } + function changeString(string memory param) public returns (string memory){ + s = param; + emit log(s); + return s; + } + function getString() public returns (string memory){ + emit log(s); + return s; + } + function changeActionChoices(ActionChoices param) public returns (ActionChoices){ + choice = param; + emit log(choice); + return choice; + } + function getActionChoices() public returns (ActionChoices){ + emit log(choice); + return choice; + } + function changeInt64NegativeArray(int64[] memory param) public returns (int64[] memory){ + b = param; + emit log(b); + return b; + } + function getInt64NegativeArray() public returns (int64[] memory){ + emit log(b); + return b; + } + function changeInt32Array(int32[2][] memory param) public returns (int32[2][] memory){ + tmp_h = param; + emit log(tmp_h); + return tmp_h; + } + function getInt32Array() public returns (int32[2][] memory){ + emit log(tmp_h); + return tmp_h; + } + function changeInt256Array(int256[2][2] memory param) public returns (int256[2][2] memory){ + tmp_i = param; + emit log(tmp_i); + return tmp_i; + } + function getInt256Array() public returns (int256[2][2] memory){ + emit log(tmp_i); + return tmp_i; + } + function setMapping(uint256 param) public returns (uint256){ + mapa[msg.sender] = param; + return mapa[msg.sender]; + + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage002.sol b/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage002.sol new file mode 100644 index 00000000000..1ceba5e87d2 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage002.sol @@ -0,0 +1,16 @@ +contract NotView { + uint256 public num = 123; + function setnum() public returns(uint256){ + num = num + 15; + return num; + } +} +contract NotViewInterface{ + function setnum() public view returns(uint256); +} +contract UseNotView { + function setnumuseproxy(address contractAddress) public view returns(uint256){ + NotViewInterface inter = NotViewInterface(contractAddress); + return inter.setnum(); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage0425.sol b/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage0425.sol new file mode 100644 index 00000000000..8ecf771626d --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage0425.sol @@ -0,0 +1,156 @@ +contract constantCall { + bool stopped = false; + int i = 32482989; + int i2 = -32482989; + uint ui = 23487823; + address origin = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; + bytes32 b32 = 0xb55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105c; + bytes bs = new bytes(9); + string s = "123qwe"; + enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } + ActionChoices choice = ActionChoices.SitStill; + int64[] b = [91, 2, 333]; + int32[2][] tmp_h = [[1,2],[3,4],[5,6]]; + int256[2][2] tmp_i = [[11,22],[33,44]]; + mapping (address => uint256) public mapa; + + constructor() payable public{ + mapa[address(0x00)] = 88; + } + event log(int); + event log(uint); + event log(bool); + event log(address); + event log(bytes32); + event log(bytes); + event log(string); + event log(ActionChoices); + event log(int64[]); + event log(int32[2][]); + event log(int256[2][2]); + + function changeBool(bool param) public constant returns (bool){ + stopped = param; + log(stopped); + return stopped; + } + function getBool() public constant returns (bool){ + log(stopped); + return stopped; + } + + function changeInt(int param) public returns (int){ + i = param; + log(i); + return i; + } + function getInt() public returns (int){ + log(i); + return i; + } + + function changeNegativeInt(int param) public constant returns (int){ + i2 = param; + log(i2); + return i2; + } + function getNegativeInt() public constant returns (int){ + log(i2); + return i2; + } + + function changeUint(uint param) public returns (uint){ + ui = param; + log(ui); + return ui; + } + function getUint() public returns (uint){ + log(ui); + return ui; + } + + function changeAddress(address param) public constant returns (address){ + origin = param; + log(origin); + return origin; + } + function getAddress() public constant returns (address){ + log(origin); + return origin; + } + + function changeBytes32(bytes32 param) public constant returns (bytes32){ + b32 = param; + log(b32); + return b32; + } + function getBytes32() public returns (bytes32){ + log(b32); + return b32; + } + + function changeBytes(bytes param) public constant returns (bytes){ + bs = param; + log(bs); + return bs; + } + function getBytes() public constant returns (bytes){ + log(bs); + return bs; + } + + function changeString(string param) public constant returns (string){ + s = param; + log(s); + return s; + } + function getString() public returns (string){ + log(s); + return s; + } + + function changeActionChoices(ActionChoices param) public constant returns (ActionChoices){ + choice = param; + log(choice); + return choice; + } + function getActionChoices() public constant returns (ActionChoices){ + log(choice); + return choice; + } + + function changeInt64NegativeArray(int64[] param) public constant returns (int64[]){ + b = param; + log(b); + return b; + } + function getInt64NegativeArray() public constant returns (int64[]){ + log(b); + return b; + } + + function changeInt32Array(int32[2][] param) public returns (int32[2][]){ + tmp_h = param; + log(tmp_h); + return tmp_h; + } + function getInt32Array() public constant returns (int32[2][]){ + log(tmp_h); + return tmp_h; + } + + function changeInt256Array(int256[2][2] param) public returns (int256[2][2]){ + tmp_i = param; + log(tmp_i); + return tmp_i; + } + function getInt256Array() public constant returns (int256[2][2]){ + log(tmp_i); + return tmp_i; + } + function setMapping(uint256 param) public returns (uint256){ + mapa[msg.sender] = param; + return mapa[msg.sender]; + + } +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/constantContract001.sol b/framework/src/test/resources/soliditycode_0.5.15/constantContract001.sol new file mode 100644 index 00000000000..ab97b450235 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/constantContract001.sol @@ -0,0 +1,8 @@ +//pragma solidity ^0.4.0; + +contract testConstantContract{ +function testPure(uint256 x,uint256 y) public pure returns (uint256 z) { +uint256 i=1; +return i + x + y; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGetterContract.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGetterContract.sol new file mode 100644 index 00000000000..ba090f061dd --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGetterContract.sol @@ -0,0 +1,17 @@ +//pragma solidity ^0.4.0; + + +contract getterContract { + +constructor() public payable{} +function() external payable{} + +uint public c = msg.value; + +function getDataUsingAccessor() public payable returns (uint){ + +return c; + +} + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test1Grammar001.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test1Grammar001.sol new file mode 100644 index 00000000000..1d0ad6e3d3f --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test1Grammar001.sol @@ -0,0 +1,18 @@ +pragma solidity >0.5.0; +contract FunctionSelector { + function select(bool useB, uint x) public returns (uint z) { + //var f = a; + //if (useB) f = b; + //return f(x); + if (useB) + return b(x); + else + return a(x); + } +function a(uint x) public returns (uint z) { + return x * x; + } +function b(uint x) public returns (uint z) { + return 2 * x; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test2Grammar002.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test2Grammar002.sol new file mode 100644 index 00000000000..df9d5c88839 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test2Grammar002.sol @@ -0,0 +1,44 @@ +//pragma solidity ^0.4.16; +library Set { + // We define a new struct datatype that will be used to + // hold its data in the calling contract. + struct Data { mapping(uint => bool) flags; } + + // Note that the first parameter is of type "storage + // reference" and thus only its storage address and not + // its contents is passed as part of the call. This is a + // special feature of library functions. It is idiomatic + // to call the first parameter 'self', if the function can + // be seen as a method of that object. + function insert(Data storage self, uint value) public returns (bool) { + if (self.flags[value]) + return false; // already there + self.flags[value] = true; + return true; + } + + function remove(Data storage self, uint value) public returns (bool) { + if (!self.flags[value]) + return false; // not there + self.flags[value] = false; + return true; + } + + function contains(Data storage self, uint value) public returns (bool) { + return self.flags[value]; + } +} + + +contract C { + Set.Data knownValues; + + function register (uint value) public{ + // The library functions can be called without a + // specific instance of the library, since the + // "instance" will be the current contract. + if (!Set.insert(knownValues, value)) + revert(); + } + // In this contract, we can also directly access knownValues.flags, if we want. +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test3Grammar003.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test3Grammar003.sol new file mode 100644 index 00000000000..ce56f5c9912 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test3Grammar003.sol @@ -0,0 +1,44 @@ +//pragma solidity ^0.4.11; + +library Set { + struct Data { mapping(uint => bool) flags; } + + function insert(Data storage self, uint value) public + returns (bool) + { + if (self.flags[value]) + return false; // already there + self.flags[value] = true; + return true; + } + + function remove(Data storage self, uint value) public + returns (bool) + { + if (!self.flags[value]) + return false; // not there + self.flags[value] = false; + return true; + } + + function contains(Data storage self, uint value) public + returns (bool) + { + return self.flags[value]; + } +} + + +contract C { + using Set for Set.Data; // this is the crucial change + Set.Data knownValues; + + function register(uint value) public{ + // Here, all variables of type Set.Data have + // corresponding member functions. + // The following function call is identical to + // Set.insert(knownValues, value) + if (!knownValues.insert(value)) + revert(); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test4Grammar004.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test4Grammar004.sol new file mode 100644 index 00000000000..b36d171a912 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test4Grammar004.sol @@ -0,0 +1,31 @@ +//pragma solidity ^0.4.0; + +library Search { + function indexOf(uint[] storage self, uint value) public returns (uint) { + for (uint i = 0; i < self.length; i++) + if (self[i] == value) return i; + return uint(-1); + } +} + + +contract C { + using Search for uint[]; + uint[] public data; + + function append(uint value) public{ + data.push(value); + } + + function replace(uint _old, uint _new) public{ + // This performs the library function call + uint index = data.indexOf(_old); + if (index == uint(-1)) + data.push(_new); + else + data[index] = _new; + } + function getData(uint256 index) public returns(uint256){ + return data[index]; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test5Grammar006.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test5Grammar006.sol new file mode 100644 index 00000000000..805476a9e4a --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test5Grammar006.sol @@ -0,0 +1,38 @@ +// pragma solidity ^0.4.0; +contract InfoFeed { +function d1(uint x) public{ + assembly{ + function f(x) -> y { switch x case 0 { y := 1 } default { y := mul(x, f(sub(x, 1))) } } + } + } + function d2(uint x) public{ + assembly { x := mul(1, add(2, 3))} + } + function f(uint x) public{ + assembly { x := sub(x, 1) } + + } + function d(uint x) public{ + assembly{ + let x := add(2, 3) let y := mload(0x40) x := add(x, y) + } + } + function d4(uint x) public{ + // Error: The labels 'repeat' is disallowed. Please use "if", "switch", "for" or function calls instead + //assembly{let x := 10 repeat: x := sub(x, 1) jumpi(repeat, eq(x, 0)) + x = x; + //} + } + function d5(uint x) public{ + assembly{ + function f(x) -> y { switch x case 0 { y := mul(x, 2) } default { y := 0 } } + + } + } + + function d6(uint x) public{ + assembly{ + function f(x) -> y { for { let i := 0 } lt(i, x) { i := add(i, 1) } { y := mul(2, y) } } + } + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test1Grammar007_1.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test1Grammar007_1.sol new file mode 100644 index 00000000000..6e3ac0bfd1e --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test1Grammar007_1.sol @@ -0,0 +1,60 @@ +//pragma solidity ^0.4.19; +contract Doug{ + mapping (bytes32 => uint) public contracts; + constructor() public{ + contracts['hww'] = 1; + contracts['brian'] = 2; + contracts['zzy'] = 7; + } + + function getDougName(string memory _name) public view returns(string memory) { + return _name; + } + + function getDougAge(uint _age) public pure returns(uint) { + return 3 ** _age; + } +} + +contract DogInterface { + function getDougAge(uint _age) public returns (uint); + function contracts(bytes32 name) public returns (uint); +} +contract main{ + + event FetchContract(address dogInterfaceAddress, address sender, bytes32 name); + + address public DOUG; + + address dogInterfaceAddress; + DogInterface dogContract ; + + function setDOUG(address _doug) public { + DOUG = _doug; + } + + constructor(address addr) public{ + dogInterfaceAddress = addr; + dogContract = DogInterface(dogInterfaceAddress); + } + + function dougOfage(uint _age) public returns(uint) { + + uint num = dogContract.getDougAge(_age); + return _age+num; + // return num; + } + + function uintOfName(bytes32 _name) public returns (uint) { + + dogContract.contracts(_name); + emit FetchContract(dogInterfaceAddress, msg.sender, _name); + + } + + // function getTest(string _name) public view returns(string) { + // string memory newName = _name ; + // DogInterface(DOUG).getDougName(newName); + // return newName; + // } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test1Grammar007_2.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test1Grammar007_2.sol new file mode 100644 index 00000000000..6e3ac0bfd1e --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test1Grammar007_2.sol @@ -0,0 +1,60 @@ +//pragma solidity ^0.4.19; +contract Doug{ + mapping (bytes32 => uint) public contracts; + constructor() public{ + contracts['hww'] = 1; + contracts['brian'] = 2; + contracts['zzy'] = 7; + } + + function getDougName(string memory _name) public view returns(string memory) { + return _name; + } + + function getDougAge(uint _age) public pure returns(uint) { + return 3 ** _age; + } +} + +contract DogInterface { + function getDougAge(uint _age) public returns (uint); + function contracts(bytes32 name) public returns (uint); +} +contract main{ + + event FetchContract(address dogInterfaceAddress, address sender, bytes32 name); + + address public DOUG; + + address dogInterfaceAddress; + DogInterface dogContract ; + + function setDOUG(address _doug) public { + DOUG = _doug; + } + + constructor(address addr) public{ + dogInterfaceAddress = addr; + dogContract = DogInterface(dogInterfaceAddress); + } + + function dougOfage(uint _age) public returns(uint) { + + uint num = dogContract.getDougAge(_age); + return _age+num; + // return num; + } + + function uintOfName(bytes32 _name) public returns (uint) { + + dogContract.contracts(_name); + emit FetchContract(dogInterfaceAddress, msg.sender, _name); + + } + + // function getTest(string _name) public view returns(string) { + // string memory newName = _name ; + // DogInterface(DOUG).getDougName(newName); + // return newName; + // } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test2Grammar008.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test2Grammar008.sol new file mode 100644 index 00000000000..c9c5d614d2d --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test2Grammar008.sol @@ -0,0 +1,14 @@ +//pragma solidity ^0.4.19; +contract Feline { + function utterance() public returns (bytes32); + + function getContractName() public returns (string memory){ + return "Feline"; + } +} + + +contract Cat is Feline { + function utterance() public returns (bytes32) { return "miaow"; } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test3Grammar010.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test3Grammar010.sol new file mode 100644 index 00000000000..a7749dfcc71 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test3Grammar010.sol @@ -0,0 +1,10 @@ +//pragma solidity ^0.4.0; +contract InfoFeed { +function info() public payable returns (uint ret) { return 42; } +} +contract Consumer { +constructor() payable public{} +InfoFeed feed; +function setFeed(address addr) public { feed = InfoFeed(addr); } +function callFeed() public payable { feed.info.value(10).gas(800)(); } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test4Grammar011.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test4Grammar011.sol new file mode 100644 index 00000000000..921b52a6080 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test4Grammar011.sol @@ -0,0 +1,11 @@ +//pragma solidity ^0.4.0; +contract C { +function f(uint key, uint value) public returns(uint) { +return key; +// do something +} +function g() public { +// named arguments +f({value: 2, key: 3}); +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test4Grammar012.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test4Grammar012.sol new file mode 100644 index 00000000000..45e6d3aaf6e --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test4Grammar012.sol @@ -0,0 +1,24 @@ +//pragma solidity ^0.4.24; +contract rTest { +function info() public payable returns (uint,address,bytes4,uint,uint,uint,address,uint) { +//function info() public payable returns (address ,uint,uint,uint,bytes32,uint,bytes,uint,address,bytes4,uint,uint,uint,address,uint) { +//var a = block.coinbase ; +//var b = block.difficulty; +//var c = block.gaslimit; +//var d = block.number; +//var e = block.blockhash(0); +//var e = d; +//var f = block.timestamp; +//bytes memory g = msg.data; +uint256 h = gasleft(); +address payable i = msg.sender; +bytes4 j = msg.sig; +uint256 k = msg.value; +uint256 l = now; +uint256 m = tx.gasprice; +address payable n = tx.origin; +uint256 o = address(this).balance; +return (h,i,j,k,l,m,n,o); +//return (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o); +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test6Grammar013.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test6Grammar013.sol new file mode 100644 index 00000000000..56f97191ea0 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test6Grammar013.sol @@ -0,0 +1,24 @@ +//pragma solidity ^0.4.4; +contract Counter { +uint count = 0; +address payable owner; +//function Counter() public{ +constructor() public{ +owner = msg.sender; +} +function increment() public { +uint step = 10; +if (owner == msg.sender) { +count = count + step; +} +} +function getCount() public returns (uint){ +return count; +} +function kill() public{ +if (owner == msg.sender) { +selfdestruct(owner); +//selfdestruct(address(owner)); +} +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test1Grammar014.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test1Grammar014.sol new file mode 100644 index 00000000000..9190e902056 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test1Grammar014.sol @@ -0,0 +1,68 @@ +//pragma solidity ^0.4.4; +contract A { +uint256 public numberForB; +address public senderForB; +function callTest(address bAddress, uint256 _number) public{ + +//bAddress.call(bytes4(sha3("setValue(uint256)")), _number); // B's storage is set, A is not modified +bAddress.call(abi.encodeWithSignature("setValue(uint256)",_number)); // B's storage is set, A is not modified +} +function callcodeTest(address bAddress, uint256 _number) public{ +//bAddress.callcode(bytes4(sha3("setValue(uint256)")), _number); // A's storage is set, B is not modified +bAddress.delegatecall(abi.encodeWithSignature("setValue(uint256)", _number)); // A's storage is set, B is not modified +} +function delegatecallTest(address bAddress, uint256 _number) public{ +//bAddress.delegatecall(bytes4(sha3("setValue(uint256)")), _number); // A's storage is set, B is not modified +bAddress.delegatecall(abi.encodeWithSignature("setValue(uint256)", _number)); // A's storage is set, B is not modified +} + +function callAddTest(address bAddress) public{ +//bAddress.call(bytes4(sha3("add()"))); // B's storage is set, A is not modified +bAddress.call(abi.encodeWithSignature("add()")); // B's storage is set, A is not modified +//bAddress.call(bytes4(sha3("add()"))); // B's storage is set, A is not modified +bAddress.call(abi.encodeWithSignature("add()")); // B's storage is set, A is not modified +} +function getnumberForB() public returns(uint256){ + return numberForB; + } + function getsenderForB() public returns(address){ + return senderForB; + } +} +contract B { +uint256 public numberForB; +address public senderForB; +address public addr11; +mapping(uint256=>address) public addr1; +mapping(uint256=>address) public addr2; +event ssss(uint256); +function setValue(uint256 _number) public{ + +emit ssss(_number); +numberForB = _number; +senderForB = msg.sender; +// senderForB is A if invoked by A's callTest. B's storage will be updated +// senderForB is A if invoked by A's callcodeTest. None of B's storage is updated +// senderForB is OWNER if invoked by A's delegatecallTest. None of B's storage is updated +} + +function add() public{ +numberForB=numberForB+1; +C c1 = new C(); +addr1[numberForB]=c1.getAddress(); +addr11 = c1.getAddress(); +C c2 = new C(); +addr2[numberForB] = c2.getAddress(); +} +function getnumberForB() public returns(uint256){ + return numberForB; + } + function getsenderForB() public returns(address){ + return senderForB; + } +} +contract C { +function getAddress() public view returns(address){ +return address(this); +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test2Grammar015.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test2Grammar015.sol new file mode 100644 index 00000000000..51aa0843890 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test2Grammar015.sol @@ -0,0 +1,39 @@ +//pragma solidity ^0.4.0; + +contract ExecuteFallback{ + + //回退事件,会把调用的数据打印出来 + event FallbackCalled(bytes data); + //fallback函数,注意是没有名字的,没有参数,没有返回值的 + function() external{ + emit FallbackCalled(msg.data); + } + + //调用已存在函数的事件,会把调用的原始数据,请求参数打印出来 + event ExistFuncCalled(bytes data, uint256 para); + //一个存在的函数 + function existFunc(uint256 para) public{ + emit ExistFuncCalled(msg.data, para); + } + + // 模拟从外部对一个存在的函数发起一个调用,将直接调用函数 + function callExistFunc() public{ + bytes4 funcIdentifier = bytes4(keccak256("existFunc(uint256)")); + //this.call(funcIdentifier, uint256(1)); + address(this).call(abi.encode(funcIdentifier, uint256(1))); + } + + //模拟从外部对一个不存在的函数发起一个调用,由于匹配不到函数,将调用回退函数 + function callNonExistFunc() public{ + bytes4 funcIdentifier = bytes4(keccak256("functionNotExist()")); + //this.call(funcIdentifier); + address(this).call(abi.encode(funcIdentifier)); + } + + function ExistFuncCalledTopic() view public returns(bytes32){ + return keccak256("ExistFuncCalled(bytes,uint256)"); + } + function FallbackCalledTopic() view public returns(bytes32){ + return keccak256("FallbackCalled(bytes)"); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test3Grammar016.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test3Grammar016.sol new file mode 100644 index 00000000000..11eb8f9cc70 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test3Grammar016.sol @@ -0,0 +1,23 @@ +//pragma solidity ^0.4.0; +contract C { +uint private data; +function f(uint a) private returns(uint b) { return a + 1; } +function setData(uint a) public { data = a; } +function getData() public returns(uint) { return data; } +function compute(uint a, uint b) internal returns (uint) { return a+b; } +} +contract D { +function readData() public{ +C c = new C(); +//uint local = c.f(7); // error: member "f" is not visible +c.setData(3); +uint local = c.getData(); +// local = c.compute(3, 5); // error: member "compute" is not visible +} +} +contract E is C { +function g() public { +C c = new C(); +uint val = compute(3, 5); // access to internal member (from derived to parent contract) +} +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test4Grammar017.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test4Grammar017.sol new file mode 100644 index 00000000000..23fcdec76f0 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test4Grammar017.sol @@ -0,0 +1,50 @@ +//pragma solidity ^0.4.0; +contract CrowdFunding{ +struct Funder{ +address addr; +uint amount; +} + +struct Campaign{ +address payable beneficiary; +uint goal; +uint amount; +uint funderNum; +mapping(uint => Funder) funders; +} + +uint compaingnID; +mapping (uint => Campaign) campaigns; + +function candidate(address payable beneficiary, uint goal) public payable returns (uint compaingnID){ +// initialize +campaigns[compaingnID++] = Campaign(beneficiary, goal, 0, 0); +} + +function vote(uint compaingnID) payable public { +Campaign storage c = campaigns[compaingnID]; + +//another way to initialize +c.funders[c.funderNum++] = Funder({addr: msg.sender, amount: msg.value}); +c.amount += msg.value; +} + +function check(uint comapingnId) public payable returns (bool){ + Campaign memory c = campaigns[comapingnId]; + + if(c.amount < c.goal){ + return false; + } + + uint amount = c.amount; + // incase send much more + c.amount = 0; + // address payable addr = address(uint160(c.beneficiary)); + //if(! addr.send(amount)){ + + if (! c.beneficiary.send(amount)){ + revert(); + } + return true; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test5Grammar018.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test5Grammar018.sol new file mode 100644 index 00000000000..ddd6deb040f --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test5Grammar018.sol @@ -0,0 +1,37 @@ +//pragma solidity ^0.4.0; + + +contract Grammar18{ + function testAddmod() public returns (uint z) { + //计算(x + y)%k,其中以任意精度执行加法,并且不在2 ** 256处围绕 + z=addmod(2, 2, 3); + return z; + } + function testMulmod() public returns (uint z) { +//计算(x * y)%k,其中乘法以任意精度执行,并且不会在2 ** 256处循环。 + z=mulmod(2, 3, 4); + return z; + } + + function testKeccak256() public returns(bytes32){ + //计算的(紧凑)参数的Ethereum-SHA-3(Keccak-256)的散列 + return keccak256("11"); + } + + function testSha256() public returns(bytes32){ + //计算(紧密包装)参数的SHA-256散列 + return sha256("11"); + } + function testSha3() public returns(bytes32){ + //计算(紧密包装)参数的SHA-256散列 + //return sha3("11"); + return keccak256("11"); + } + + function testRipemd160() public returns(bytes32){ + //计算(紧密包装)参数的RIPEMD-160哈希值 + return ripemd160("11"); + } + + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test6Grammar019.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test6Grammar019.sol new file mode 100644 index 00000000000..30418539865 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test6Grammar019.sol @@ -0,0 +1,12 @@ +//pragma solidity ^0.4.0; +contract timetest { + +constructor() public { +require( 1 == 1 seconds); +require(1 minutes == 60 seconds); +require(1 hours == 60 minutes); +require(1 days == 24 hours); +require(1 weeks == 7 days); +//require(1 years == 365 days); +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test7Grammar020.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test7Grammar020.sol new file mode 100644 index 00000000000..1b960e6e313 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test7Grammar020.sol @@ -0,0 +1,8 @@ +//pragma solidity ^0.4.0; +contract trxtest { + +function test() public { +require(1 trx == 1000000 sun); + +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInnerContract.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInnerContract.sol new file mode 100644 index 00000000000..bc183931c88 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInnerContract.sol @@ -0,0 +1,32 @@ +//pragma solidity ^0.4.0; + + + +contract InnerContract { + + constructor() public payable{} + function() external payable{} + + function messageI() payable public returns (uint ret) { + + + + } + +} + + + +contract OuterContract { + + + constructor() public payable{} + function() external payable{} + + function callInner(address payable addr) payable public returns (uint) { + + return InnerContract(addr).messageI.value(1)(); + + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction001.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction001.sol new file mode 100644 index 00000000000..8baba262e87 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction001.sol @@ -0,0 +1,42 @@ +//pragma solidity ^0.4.24; + +contract A{ + constructor() payable public{} + function() payable external{} + function test1(address payable cAddr) public payable{ + B b1 = (new B).value(10)();//1.1 + B b2 = new B();//1.2 + address(b2).transfer(5);//1.3 + b2.callCGetZero(cAddr, 1);//1.4 + b2.callCGetZero(cAddr,2);//1.6 + } + function test2(address payable cAddress,uint256 amount) public payable{ + cAddress.call.value(amount)(abi.encodeWithSignature("newBAndTransfer()"));//2.1 + cAddress.call.value(amount + 1)(abi.encodeWithSignature("newBAndTransfer()"));//2.6 + } +} + +contract B{ + constructor() payable public{} + function() payable external{} + function getOne() payable public returns(uint256){ + return 1; + } + function callCGetZero(address payable cAddress,uint256 amount) public{ + cAddress.call.value(amount)(abi.encodeWithSignature("getZero()"));//1.5,1.7 + } +} + +contract C{ + constructor() payable public{} + function() payable external{} + function getZero() payable public returns(uint256){ + return 0; + } + function newBAndTransfer() payable public returns(uint256){ + B b1 = (new B).value(7)();//2.2,2.7 + b1.getOne();//2.3,2.8 + B b2 = (new B).value(3)();//2.4,2.9 + b2.getOne();//2.5,2.10 + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction002.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction002.sol new file mode 100644 index 00000000000..42231b7c960 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction002.sol @@ -0,0 +1,21 @@ +//pragma solidity ^0.4.24; + +contract A{ + constructor() payable public{} + function() payable external{} + + function test2(address cAddress,uint256 amount) public payable{ + //cAddress.call.value(amount)();//2.1 + cAddress.call.value(amount)("");//2.1 + } +} + + +contract C{ + constructor() payable public{} + function() payable external{} + function getZero() payable public returns(uint256){ + return 0; + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction003.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction003.sol new file mode 100644 index 00000000000..0910a0c4a2b --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction003.sol @@ -0,0 +1,31 @@ +//pragma solidity ^0.4.24; + + contract A{ + uint256 public num = 0; + constructor() public payable{} + function transfer() payable public{ + B b = (new B).value(10)();//1 + + } + function getBalance() public returns(uint256){ + return address(this).balance; + } + } + contract B{ + uint256 public num = 0; + function f() payable public returns(bool) { + return true; + } + constructor() public payable {} + function payC(address payable c, bool isRevert) public{ + c.transfer(1);//4 + if (isRevert) { + revert(); + } + } + function getBalance() public returns(uint256){ + return address(this).balance; + } + function () payable external{} + } + diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction004.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction004.sol new file mode 100644 index 00000000000..c7866dddb58 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction004.sol @@ -0,0 +1,25 @@ +//pragma solidity ^0.4.24; + +contract A{ + constructor () payable public{} + function test(address payable toAddress) public payable{ + selfdestruct(toAddress); + } + function () payable external{} + function getBalance() public view returns(uint256){ + return address(this).balance; + } +} +contract B{ + function() external payable{} + function kill(address contractAddres, address toAddress) payable public { + contractAddres.call(abi.encodeWithSignature("test(address)",address(this))); + } + function kill2() public{ + A a = new A(); + a.test(address(this)); + } + function getBalance() public view returns(uint256){ + return address(this).balance; + } +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction005.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction005.sol new file mode 100644 index 00000000000..6e83c423b38 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction005.sol @@ -0,0 +1,54 @@ +//pragma solidity ^0.4.24; + +contract A{ + constructor() payable public{} + function() payable external{} + function test1() public payable{ + B b1 = (new B).value(10)();//1.1 + b1.callCGetZero(false); + b1.callCGetZero(true);//1.4 + } + function test2() public payable{ + C c1 = (new C).value(10)();//1.1 + c1.newBAndTransfer(false); + c1.newBAndTransfer(true);//1.4 + + } + function getBalance() view public returns(uint256){ + return address(this).balance; + } +} + +contract B{ + constructor() payable public{} + function() payable external{} + function getOne() payable public returns(uint256){ + return 1; + } + function callCGetZero(bool success) public payable{ + if(!success){ + assert(1==2); + } + } + function getBalance() view public returns(uint256){ + return address(this).balance; + } +} + +contract C{ + uint256 public flag=0; + constructor() payable public{} + function() payable external{} + function getZero() payable public returns(uint256){ + return 0; + } + function newBAndTransfer(bool success) payable public returns(uint256){ + flag = 1; + if(!success){ + require(2==1); + } + } + function getFlag() public returns(uint256){ + return flag; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction006.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction006.sol new file mode 100644 index 00000000000..6bc548690a5 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction006.sol @@ -0,0 +1,54 @@ +//pragma solidity ^0.4.24; + +contract A{ + constructor() payable public{} + function() payable external{} + function test1() public payable{ + B b1 = (new B).value(10)();//1.1 + b1.callCGetZero(true);//1.4 + b1.callCGetZero(false); + } + function test2() public payable{ + C c1 = (new C).value(10)();//1.1 + c1.newBAndTransfer(true);//1.4 + c1.newBAndTransfer(false); + + } + function getBalance() view public returns(uint256){ + return address(this).balance; + } +} + +contract B{ + constructor() payable public{} + function() payable external{} + function getOne() payable public returns(uint256){ + return 1; + } + function callCGetZero(bool success) public payable{ + if(!success){ + assert(1==2); + } + } + function getBalance() view public returns(uint256){ + return address(this).balance; + } +} + +contract C{ + uint256 public flag=0; + constructor() payable public{} + function() payable external{} + function getZero() payable public returns(uint256){ + return 0; + } + function newBAndTransfer(bool success) payable public returns(uint256){ + flag = 1; + if(!success){ + require(2==1); + } + } + function getFlag() public returns(uint256){ + return flag; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test1InternalTransaction007.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test1InternalTransaction007.sol new file mode 100644 index 00000000000..229bf82fa2d --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test1InternalTransaction007.sol @@ -0,0 +1,38 @@ +//pragma solidity ^0.4.24; + +contract A{ + constructor() payable public{} + function() payable external{} + function test1(address cAddr) public payable{ + B b1 = (new B).value(10)();//1.1 + B b2 = new B();//1.2 + address(b2).transfer(5);//1.3 + b2.callCGetZero();//1.4 + } + function test2(address cAddress,uint256 amount) public payable{ + cAddress.call.value(amount)(abi.encodeWithSignature("newBAndTransfer()"));//2.1 + } +} + +contract B{ + constructor() payable public{} + function() payable external{} + function getOne() payable public returns(uint256){ + return 1; + } + function callCGetZero() public{ + assert(1==2); + + } +} + +contract C{ + constructor() payable public{} + function() payable external{} + function getZero() payable public returns(uint256){ + return 0; + } + function newBAndTransfer() payable public returns(uint256){ + require(2==1); + } +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test2InternalTransaction008.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test2InternalTransaction008.sol new file mode 100644 index 00000000000..a75fba4f14b --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test2InternalTransaction008.sol @@ -0,0 +1,60 @@ +//pragma solidity ^0.4.24; + +contract A{ + constructor() payable public{} + function() payable external{} + + function testAssert(address bAddress,uint256 amount) public payable{ + bAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("callCGetZero(bool)",false));//2.1 + bAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("callCGetZero(bool)",true)); + } + function testRequire(address cAddress,uint256 amount) public payable{ + cAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("newBAndTransfer(bool)",false));//2.1 + cAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("newBAndTransfer(bool)",true)); + } + function testAssert1(address bAddress,uint256 amount) public payable{ + bAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("callCGetZero(bool)",true)); + bAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("callCGetZero(bool)",false));//2.1 + } + function testtRequire2(address cAddress,uint256 amount) public payable{ + cAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("newBAndTransfer(bool)",true)); + cAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("newBAndTransfer(bool)",false));//2.1 + } + function getBalance() view public returns(uint256){ + return address(this).balance; + } +} + +contract B{ + constructor() payable public{} + function() payable external{} + function getOne() payable public returns(uint256){ + return 1; + } + function callCGetZero(bool success) payable public{ + if(!success){ + assert(1==2); + } + } + function getBalance() view public returns(uint256){ + return address(this).balance; + } +} + +contract C{ + uint256 public flag=0; + constructor() payable public{} + function() payable external{} + function getZero() payable public returns(uint256){ + return 0; + } + function newBAndTransfer(bool success) payable public returns(uint256){ + flag = 1; + if(!success){ + require(2==1); + } + } + function getFlag() public returns(uint256){ + return flag; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test3InternalTransaction009.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test3InternalTransaction009.sol new file mode 100644 index 00000000000..1a7df822511 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test3InternalTransaction009.sol @@ -0,0 +1,47 @@ +//pragma solidity ^0.4.24; + +contract A{ + constructor() payable public{} + function() payable external{} + function test1(address cAddr,address dcontract,address baddress) public payable{ + B b1 = (new B).value(10)();//1.1 + address(b1).transfer(5);//1.3 + b1.callCGetZero(cAddr, 1);//1.4 + b1.getOne(dcontract,baddress); + } +} + +contract B{ + constructor() payable public{} + function() payable external{} + function getOne(address contractAddres, address toAddress) payable public{ + contractAddres.call(abi.encodeWithSignature("suicide1(address)",address(this))); + + } + function callCGetZero(address cAddress,uint256 amount) public{ + cAddress.call.value(amount)(abi.encodeWithSignature("getZero()"));//1.5,1.7 + } +} + +contract C{ + constructor() payable public{} + function() payable external{} + function getZero() payable public returns(uint256){ + return 0; + } + function newBAndTransfer() payable public{ + B b1 = (new B).value(7)();//2.2,2.7 + B b2 = (new B).value(3)();//2.4,2.9 + } +} + +contract D{ + constructor () payable public{} + function suicide1(address payable toAddress) public payable{ + selfdestruct(toAddress); + } + function () payable external{} + function getBalance() public view returns(uint256){ + return address(this).balance; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test4InternalTransaction010.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test4InternalTransaction010.sol new file mode 100644 index 00000000000..7f34b2bfe08 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test4InternalTransaction010.sol @@ -0,0 +1,186 @@ +//pragma solidity ^0.4.24; + + contract A{ + uint256 public num = 0; + constructor() public payable{} + function transfer() payable public{ + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + + } + function transfer2() payable public{ + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + + } + function getBalance() public returns(uint256) { + return address(this).balance; + } + } + contract B{ + uint256 public num = 0; + function f() payable public returns(bool) { + return true; + } + constructor() public payable {} + function payC(address payable c, bool isRevert) public{ + c.transfer(1);//4 + if (isRevert) { + revert(); + } + } + function getBalance() public returns(uint256){ + return address(this).balance; + } + function () payable external{} + } + diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test4InternalTransaction010_1.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test4InternalTransaction010_1.sol new file mode 100644 index 00000000000..c77fe76f5fa --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test4InternalTransaction010_1.sol @@ -0,0 +1,210 @@ +pragma solidity ^0.4.24; + + contract A{ + uint256 public num = 0; + constructor() public payable{} + function transfer() payable public{ + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + } + function transfer2() payable public{ + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + + } + function getBalance() returns(uint256){ + return this.balance; + } + } + contract B{ + uint256 public num = 0; + function f() payable returns(bool) { + return true; + } + constructor() public payable {} + function payC(address c, bool isRevert) public{ + c.transfer(1);//4 + if (isRevert) { + revert(); + } + } + function getBalance() returns(uint256){ + return this.balance; + } + function () payable{} + } + + \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test5InternalTransaction012.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test5InternalTransaction012.sol new file mode 100644 index 00000000000..ce2798888fe --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test5InternalTransaction012.sol @@ -0,0 +1,51 @@ +//pragma solidity ^0.4.24; + +contract A{ + constructor() payable public{} + function() payable external{} + function test1(address bAddr,address eAddr) public payable{ + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + } + +} + +contract B{ + constructor() payable public{} + function() payable external{} + function getOne() payable public returns(uint256){ + return 1; + } + function testNN(address eAddress) public payable{ + D d1=(new D).value(1000)(); + d1.getOne(eAddress); + } +} + +contract C{ + constructor() payable public{} + function() payable external{} + function getZero() payable public returns(uint256){ + return 0; + } + function newBAndTransfer() payable public returns(uint256){ + require(2==1); + } +} +contract E{ + constructor() payable public{} + function() payable external{} + function getZero() payable public returns(uint256){ + return 0; + } + function newBAndTransfer() payable public returns(uint256){ + require(2==1); + } +} +contract D{ + constructor() payable public{} + function() payable external{} + function getOne(address eAddress) payable public returns(uint256){ + eAddress.call.value(1)(abi.encodeWithSignature("getZero()"));//2.1 + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction013.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction013.sol new file mode 100644 index 00000000000..bc1d3dbe6cd --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction013.sol @@ -0,0 +1,56 @@ +//pragma solidity ^0.4.24; + +contract A{ + constructor() payable public{} + function() payable external{} + function test1(address dAddr) public payable{ + B b1 = (new B).value(10)();//1.1 + b1.testNN(dAddr,2);//1.6 + // C c1 = (new C).value(1000000000000)();//1.2 + // E e1 = (new E).value(1)();//1.2 + } + function test2(address cAddress,uint256 amount) public payable{ + cAddress.call.value(amount)(abi.encodeWithSignature("newBAndTransfer()"));//2.1 + } +} + +contract B{ + constructor() payable public{} + function() payable external{} + function getOne() payable public returns(uint256){ + return 1; + } + function testNN(address dAddress,uint256 amount) public payable{ + // D d1=(new D)(); + dAddress.call.value(amount)(abi.encodeWithSignature("getOne()"));//2.1 + } +} + +contract C{ + constructor() payable public{} + function() payable external{} + function getZero() payable public returns(uint256){ + return 0; + } + function newBAndTransfer() payable public returns(uint256){ + require(2==1); + } +} +contract E{ + constructor() payable public{} + function() payable external{} + function getZero() payable public returns(uint256){ + return 0; + } + function newBAndTransfer() payable public returns(uint256){ + require(2==1); + } +} +contract D{ + constructor() payable public{} + function() payable external{} + function getOne() payable public returns(uint256){ + E e = (new E).value(5)(); + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction014.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction014.sol new file mode 100644 index 00000000000..b3bbfc9a7db --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction014.sol @@ -0,0 +1,38 @@ +contract callerContract { + constructor() payable public{} + function() payable external{} + function sendToB(address called_address,address c) public payable{ + called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); + } + function sendToB2(address called_address,address c) public payable{ + called_address.call(abi.encodeWithSignature("transferTo(address)",c)); + } + function sendToB3(address called_address,address c) public payable{ + called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); + } +} + + contract calledContract { + function() payable external {} + constructor() payable public{} + function transferTo(address payable toAddress)public payable{ + toAddress.transfer(5); + } + + function setIinC(address c) public payable{ + c.call.value(5)(abi.encodeWithSignature("setI()")); + } + + } + + contract c{ + uint256 public i=0; + constructor() public payable{} + function getBalance() public view returns(uint256){ + return address(this).balance; + } + function setI() payable public{ + i=5; + } + function() payable external{} + } diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction015.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction015.sol new file mode 100644 index 00000000000..0426d650da4 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction015.sol @@ -0,0 +1,60 @@ +//pragma solidity ^0.4.24; + +contract A{ + constructor() payable public{} + function() payable external{} + function test1(address dAddr,address eAddr) public payable{ + B b1 = (new B).value(10)();//1.1 + b1.testNN(dAddr,2,eAddr);//1.6 + // C c1 = (new C).value(1000000000000)();//1.2 + // E e1 = (new E).value(1)();//1.2 + } + function test2(address cAddress,uint256 amount) public payable{ + cAddress.call.value(amount)(abi.encodeWithSignature("newBAndTransfer()"));//2.1 + } +} + +contract B{ + constructor() payable public{} + function() payable external{} + function getOne() payable public returns(uint256){ + return 1; + } + function testNN(address dAddress,uint256 amount,address eAddress) public payable{ + // D d1=(new D)(); + dAddress.call.value(amount)(abi.encodeWithSignature("getOne(address)",address(this)));//2.1 + } +} + +contract C{ + constructor() payable public{} + function() payable external{} + function getZero() payable public returns(uint256){ + return 0; + } + function newBAndTransfer() payable public returns(uint256){ + require(2==1); + } +} +contract E{ + constructor() payable public{} + function() payable external{} + function getZero() payable public returns(uint256){ + return 0; + } + function newBAndTransfer() payable public returns(uint256){ + require(2==1); + } + function suicide(address payable toAddress) public payable{ + selfdestruct(toAddress); + } +} +contract D{ + constructor() payable public{} + function() payable external{} + function getOne(address payable eAddress) payable public{ + E e = (new E).value(5)(); + e.suicide(eAddress); + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction016.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction016.sol new file mode 100644 index 00000000000..f97217fe169 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction016.sol @@ -0,0 +1,174 @@ +//pragma solidity ^0.4.24; + + contract A{ + uint256 public num = 0; + constructor() public payable{} + function () payable external{} + function transfer() payable public{ + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + B b1=(new B).value(1)();//1 + address payable aaa=address(this); + b1.suicide1(aaa); + } + function transfer2() payable public{ + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + B b1=(new B).value(1)();//1 + address payable aaa=address(this); + b1.suicide1(aaa); + } + function getBalance() public returns(uint256){ + return address(this).balance; + } + } + contract B{ + uint256 public num = 0; + function f() payable public returns(bool) { + return true; + } + constructor() public payable {} + function payC(address payable c, bool isRevert) public{ + c.transfer(1);//4 + if (isRevert) { + revert(); + } + } + function getBalance() public returns(uint256){ + return address(this).balance; + } + function () payable external{} + function suicide1(address payable toAddress) public payable{ + selfdestruct(toAddress); + } + } + diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction017.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction017.sol new file mode 100644 index 00000000000..ebe570fd8af --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction017.sol @@ -0,0 +1,199 @@ +//pragma solidity ^0.4.24; + + contract A{ + uint256 public num = 0; + constructor() public payable{} + function transfer(address payable Address) payable public{ + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + + B b=(new B).value(1)();//1 + selfdestruct(Address); + } + function transfer2() payable public{ + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + (new B).value(1)();//1 + + } + function getBalance() public returns(uint256){ + return address(this).balance; + } + } + contract B{ + uint256 public num = 0; + function f() payable public returns(bool) { + return true; + } + constructor() public payable {} + function payC(address payable c, bool isRevert) public{ + c.transfer(1);//4 + if (isRevert) { + revert(); + } + } + function getBalance() public returns(uint256){ + return address(this).balance; + } + function () payable external{} + } + diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction018.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction018.sol new file mode 100644 index 00000000000..a59c587b233 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction018.sol @@ -0,0 +1,97 @@ +//pragma solidity ^0.4.24; + +contract A{ + constructor() payable public{} + function() payable external{} + function test1(address payable bAddr,address eAddr) public payable{ + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 + + } + +} + +contract B{ + constructor() payable public{} + function() payable external{} + function getOne() payable public returns(uint256){ + return 1; + } + function testNN(address eAddress) public payable { + D d1=(new D).value(100)(); + d1.getOne(eAddress); + } +} + +contract C{ + constructor() payable public{} + function() payable external{} + function getZero() payable public returns(uint256){ + return 0; + } + function newBAndTransfer() payable public returns(uint256){ + require(2==1); + } +} +contract E{ + constructor() payable public{} + function() payable external{} + function getZero() payable public returns(uint256){ + return 0; + } + function newBAndTransfer() payable public returns(uint256){ + require(2==1); + } +} +contract D{ + constructor() payable public{} + function() payable external{} + function getOne(address eAddress) payable public returns(uint256){ + eAddress.call.value(1)(abi.encodeWithSignature("getZero()"));//2.1 + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage001.sol b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage001.sol new file mode 100644 index 00000000000..4c04cf5c6fb --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage001.sol @@ -0,0 +1,9 @@ +//pragma solidity ^0.4.0; + +contract divideIHaveArgsReturnStorage{ +constructor() payable public{} +function() payable external{} +function divideIHaveArgsReturn(int x,int y) public payable returns (int z) { +return z = x / y; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage002.sol b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage002.sol new file mode 100644 index 00000000000..ca38896acee --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage002.sol @@ -0,0 +1,7 @@ +//pragma solidity ^0.4.0; + +contract divideIHaveArgsReturnStorage{ +function divideIHaveArgsReturn(int x,int y) public returns (int z) { +return z = x / y; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage003.sol b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage003.sol new file mode 100644 index 00000000000..ca38896acee --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage003.sol @@ -0,0 +1,7 @@ +//pragma solidity ^0.4.0; + +contract divideIHaveArgsReturnStorage{ +function divideIHaveArgsReturn(int x,int y) public returns (int z) { +return z = x / y; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage004.sol b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage004.sol new file mode 100644 index 00000000000..ca38896acee --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage004.sol @@ -0,0 +1,7 @@ +//pragma solidity ^0.4.0; + +contract divideIHaveArgsReturnStorage{ +function divideIHaveArgsReturn(int x,int y) public returns (int z) { +return z = x / y; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage005.sol b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage005.sol new file mode 100644 index 00000000000..7b943aee5c1 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage005.sol @@ -0,0 +1,51 @@ +contract timeoutTest { + string public iarray1; + // cpu + function oneCpu() public { + require(1==1); + } + + function storage8Char() public { + iarray1 = "12345678"; + } + + function testUseCpu(uint256 a) public returns (uint256){ + uint256 count = 0; + for (uint256 i = 0; i < a; i++) { + count++; + } + return count; + } + + + uint256[] public iarray; + uint public calculatedFibNumber; + mapping(address=>mapping(address=>uint256)) public m; + + function testUseStorage(uint256 a) public returns (uint256){ + uint256 count = 0; + for (uint256 i = 0; i < a; i++) { + count++; + iarray.push(i); + } + return count; + } + + // stack + //uint n = 0; + uint yy = 0; + function test() public { + //n += 1; + yy += 1; + test(); + } + + function setFibonacci(uint n) public returns (uint256){ + calculatedFibNumber = fibonacci(n); + return calculatedFibNumber; + } + + function fibonacci(uint n) internal returns (uint) { + return fibonacci(n - 1) + fibonacci(n - 2); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage006.sol b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage006.sol new file mode 100644 index 00000000000..9c20c82dc02 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage006.sol @@ -0,0 +1,18 @@ +//pragma solidity ^0.4.0; +contract AA{ + uint256 public count=0; + constructor () payable public{} + function init(address payable addr, uint256 max) payable public { + count =0; + this.hack(addr,max); + } + function hack(address payable addr, uint256 max) payable public { + while (count < max) { + count = count +1; + this.hack(addr,max); + } + if (count == max) { + addr.send(20); + } + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractOriginEnergyLimit001.sol b/framework/src/test/resources/soliditycode_0.5.15/contractOriginEnergyLimit001.sol new file mode 100644 index 00000000000..212614935f6 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractOriginEnergyLimit001.sol @@ -0,0 +1,11 @@ +//pragma solidity ^0.4.0; + +contract findArgsContractTest{ + function findArgsByIndexTest(uint i) public returns (uint z) { + uint[] memory a = new uint[](3); + a[0]=1; + a[1]=2; + a[2]=3; + return a[i]; + } +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractOriginEnergyLimit004.sol b/framework/src/test/resources/soliditycode_0.5.15/contractOriginEnergyLimit004.sol new file mode 100644 index 00000000000..212614935f6 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractOriginEnergyLimit004.sol @@ -0,0 +1,11 @@ +//pragma solidity ^0.4.0; + +contract findArgsContractTest{ + function findArgsByIndexTest(uint i) public returns (uint z) { + uint[] memory a = new uint[](3); + a[0]=1; + a[1]=2; + a[2]=3; + return a[i]; + } +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractOtherToTrcToken.sol b/framework/src/test/resources/soliditycode_0.5.15/contractOtherToTrcToken.sol new file mode 100644 index 00000000000..74afd5d0e54 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractOtherToTrcToken.sol @@ -0,0 +1,41 @@ +//pragma solidity ^0.4.24; + +contract ConvertType { + +constructor() payable public{} + +function() payable external{} + +//function stringToTrctoken(address payable toAddress, string memory tokenStr, uint256 tokenValue) public { +// trcToken t = trcToken(tokenStr); // ERROR +// toAddress.transferToken(tokenValue, tokenStr); // ERROR +//} + +function uint256ToTrctoken(address payable toAddress, uint256 tokenValue, uint256 tokenInt) public { + trcToken t = trcToken(tokenInt); // OK + toAddress.transferToken(tokenValue, t); // OK + toAddress.transferToken(tokenValue, tokenInt); // OK +} + +function addressToTrctoken(address payable toAddress, uint256 tokenValue, address adr) public { + trcToken t = trcToken(adr); // OK + toAddress.transferToken(tokenValue, t); // OK +//toAddress.transferToken(tokenValue, adr); // ERROR +} + +//function bytesToTrctoken(address payable toAddress, bytes memory b, uint256 tokenValue) public { + // trcToken t = trcToken(b); // ERROR + // toAddress.transferToken(tokenValue, b); // ERROR +//} + +function bytes32ToTrctoken(address payable toAddress, uint256 tokenValue, bytes32 b32) public { + trcToken t = trcToken(b32); // OK + toAddress.transferToken(tokenValue, t); // OK +// toAddress.transferToken(tokenValue, b32); // ERROR +} + +//function arrayToTrctoken(address payable toAddress, uint256[] memory arr, uint256 tokenValue) public { +//trcToken t = trcToken(arr); // ERROR +// toAddress.transferToken(tokenValue, arr); // ERROR +//} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario001.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario001.sol new file mode 100644 index 00000000000..ca38896acee --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractScenario001.sol @@ -0,0 +1,7 @@ +//pragma solidity ^0.4.0; + +contract divideIHaveArgsReturnStorage{ +function divideIHaveArgsReturn(int x,int y) public returns (int z) { +return z = x / y; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario002.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario002.sol new file mode 100644 index 00000000000..aa9deda79ef --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractScenario002.sol @@ -0,0 +1,53 @@ +//pragma solidity ^0.4.0; +contract TronNative{ + + address public voteContractAddress= address(0x10001); + address public freezeBalanceAddress = address(0x10002); + address public unFreezeBalanceAddress = address(0x10003); + address public withdrawBalanceAddress = address(0x10004); + address public approveProposalAddress = address(0x10005); + address public createProposalAddress = address(0x10006); + address public deleteProposalAddress = address(0x10007); + constructor () payable public {} + + function voteForSingleWitness (address payable witnessAddr, uint256 voteValue) public{ + // method 1: + voteContractAddress.delegatecall(abi.encode(witnessAddr,voteValue)); + } + + function voteUsingAssembly (address witnessAddr, uint256 voteValue) public{ + // method 2: + assembly{ + mstore(0x80,witnessAddr) + mstore(0xa0,voteValue) + // gas, address, in, size, out, size + if iszero(delegatecall(0, 0x10001, 0x80, 0x40, 0x80, 0x0)) { + revert(0, 0) + } + } + } + + function freezeBalance(uint256 frozen_Balance,uint256 frozen_Duration) public { + freezeBalanceAddress.delegatecall(abi.encode(frozen_Balance,frozen_Duration)); + } + + function unFreezeBalance() public { + unFreezeBalanceAddress.delegatecall(""); + } + + function withdrawBalance() public { + withdrawBalanceAddress.delegatecall(""); + } + + function approveProposal(uint256 id, bool isApprove) public { + approveProposalAddress.delegatecall(abi.encode(id,isApprove)); + } + + function createProposal(bytes32 [] memory data) public { + createProposalAddress.delegatecall(abi.encode(data)); + } + + function deleteProposal(uint256 id) public{ + deleteProposalAddress.delegatecall(abi.encode(id)); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario003.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario003.sol new file mode 100644 index 00000000000..ca38896acee --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractScenario003.sol @@ -0,0 +1,7 @@ +//pragma solidity ^0.4.0; + +contract divideIHaveArgsReturnStorage{ +function divideIHaveArgsReturn(int x,int y) public returns (int z) { +return z = x / y; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario004.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario004.sol new file mode 100644 index 00000000000..b3ca2687b4c --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractScenario004.sol @@ -0,0 +1,88 @@ +//pragma solidity ^0.4.11; + +contract TronToken { + + string public name = "Tronix"; // token name + string public symbol = "TRX"; // token symbol + uint256 public decimals = 6; // token digit + + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + + uint256 public totalSupply = 0; + bool public stopped = false; + + uint256 constant valueFounder = 100000000000000000; + address owner = address(0x0); + + modifier isOwner { + assert(owner == msg.sender); + _; + } + + modifier isRunning { + assert (!stopped); + _; + } + + modifier validAddress { + assert(address(0x0) != msg.sender); + _; + } + + constructor(address _addressFounder) public { + owner = msg.sender; + totalSupply = valueFounder; + balanceOf[_addressFounder] = valueFounder; + emit Transfer(address(0x0), _addressFounder, valueFounder); + } + + function transfer(address _to, uint256 _value) isRunning validAddress public returns (bool success) { + require(balanceOf[msg.sender] >= _value); + require(balanceOf[_to] + _value >= balanceOf[_to]); + balanceOf[msg.sender] -= _value; + balanceOf[_to] += _value; + emit Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint256 _value) isRunning validAddress public returns (bool success) { + require(balanceOf[_from] >= _value); + require(balanceOf[_to] + _value >= balanceOf[_to]); + require(allowance[_from][msg.sender] >= _value); + balanceOf[_to] += _value; + balanceOf[_from] -= _value; + allowance[_from][msg.sender] -= _value; + emit Transfer(_from, _to, _value); + return true; + } + + function approve(address _spender, uint256 _value) isRunning validAddress public returns (bool success) { + require(_value == 0 || allowance[msg.sender][_spender] == 0); + allowance[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + function stop() isOwner public { + stopped = true; + } + + function start() isOwner public { + stopped = false; + } + + function setName(string memory _name) isOwner public { + name = _name; + } + + function burn(uint256 _value) public { + require(balanceOf[msg.sender] >= _value); + balanceOf[msg.sender] -= _value; + balanceOf[address(0x0)] += _value; + emit Transfer(msg.sender, address(0x0), _value); + } + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario005.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario005.sol new file mode 100644 index 00000000000..d46098cd410 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractScenario005.sol @@ -0,0 +1,103 @@ +//pragma solidity ^0.4.16; + +interface token { + function transfer(address receiver, uint amount) external; +} + +contract Crowdsale { + address payable public beneficiary = 0x1b228F5D9f934c7bb18Aaa86F90418932888E7b4; // 募资成功后的收款方 + uint public fundingGoal = 10000000; // 募资额度 + uint public amountRaised = 1000000; // 参与数量 + uint public deadline; // 募资截止期 + + uint public price; // token 与以太坊的汇率 , token卖多少钱 + token public tokenReward; // 要卖的token + + mapping(address => uint256) public balanceOf; + + bool fundingGoalReached = false; // 众筹是否达到目标 + bool crowdsaleClosed = false; // 众筹是否结束 + + /** + * 事件可以用来跟踪信息 + **/ + event GoalReached(address recipient, uint totalAmountRaised); + event FundTransfer(address backer, uint amount, bool isContribution); + + /** + * 构造函数, 设置相关属性 + */ + constructor( + address payable ifSuccessfulSendTo, + uint fundingGoalInEthers, + uint durationInMinutes, + uint finneyCostOfEachToken, + address addressOfTokenUsedAsReward) public{ + beneficiary = ifSuccessfulSendTo; + fundingGoal = fundingGoalInEthers * 1 sun; + deadline = now + durationInMinutes * 1 minutes; + price = finneyCostOfEachToken * 1 trx; + tokenReward = token(addressOfTokenUsedAsReward); // 传入已发布的 token 合约的地址来创建实例 + } + + /** + * 无函数名的Fallback函数, + * 在向合约转账时,这个函数会被调用 + */ + function () payable external{ + require(!crowdsaleClosed); + uint amount = msg.value; + balanceOf[msg.sender] += amount; + amountRaised += amount; + tokenReward.transfer(msg.sender, amount / price); + emit FundTransfer(msg.sender, amount, true); + } + + /** + * 定义函数修改器modifier(作用和Python的装饰器很相似) + * 用于在函数执行前检查某种前置条件(判断通过之后才会继续执行该方法) + * _ 表示继续执行之后的代码 + **/ + modifier afterDeadline() { if (now >= deadline) _; } + + /** + * 判断众筹是否完成融资目标, 这个方法使用了afterDeadline函数修改器 + * + */ + function checkGoalReached() afterDeadline public{ + if (amountRaised >= fundingGoal) { + fundingGoalReached = true; + emit GoalReached(beneficiary, amountRaised); + } + crowdsaleClosed = true; + } + + + /** + * 完成融资目标时,融资款发送到收款方 + * 未完成融资目标时,执行退款 + * + */ + function safeWithdrawal() afterDeadline public{ + if (!fundingGoalReached) { + uint amount = balanceOf[msg.sender]; + balanceOf[msg.sender] = 0; + if (amount > 0) { + if (msg.sender.send(amount)) { + emit FundTransfer(msg.sender, amount, false); + } else { + balanceOf[msg.sender] = amount; + } + } + } + + if (fundingGoalReached && beneficiary == msg.sender) { + if (address(beneficiary).send(amountRaised)) { + emit FundTransfer(beneficiary, amountRaised, false); + } else { + //If we fail to send the funds to beneficiary, unlock funders balance + fundingGoalReached = false; + } + } + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario006.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario006.sol new file mode 100644 index 00000000000..397c62096e0 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractScenario006.sol @@ -0,0 +1,1963 @@ +//pragma solidity ^0.4.24; + +interface PlayerBookInterface { + function getPlayerID(address _addr) external returns (uint256); + function getPlayerName(uint256 _pID) external view returns (bytes32); + function getPlayerLAff(uint256 _pID) external view returns (uint256); + function getPlayerAddr(uint256 _pID) external view returns (address); + function getNameFee() external view returns (uint256); + function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); + function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); + function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); + function isDev(address _who) external view returns(bool); +} + + +/** +* @title -Name Filter- v0.1.9 +* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ +* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ +* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ +* _____ _____ +* (, / /) /) /) (, / /) /) +* ┌─┐ / _ (/_ // // / _ // _ __ _(/ +* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ +* ┴ ┴ / / .-/ _____ (__ / +* (__ / (_/ (, / /)™ +* / __ __ __ __ _ __ __ _ _/_ _ _(/ +* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ +* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 +* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ +* _ __ _ ____ ____ _ _ _____ ____ ___ +*=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* +*=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* +* +* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ +* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ +* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ +*/ + +library NameFilter { + /** + * @dev filters name strings + * -converts uppercase to lower case. + * -makes sure it does not start/end with a space + * -makes sure it does not contain multiple spaces in a row + * -cannot be only numbers + * -cannot start with 0x + * -restricts characters to A-Z, a-z, 0-9, and space. + * @return reprocessed string in bytes32 format + */ + function nameFilter(string memory _input) + internal + pure + returns(bytes32) + { + bytes memory _temp = bytes(_input); + uint256 _length = _temp.length; + + //sorry limited to 32 characters + require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); + // make sure it doesnt start with or end with space + require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); + // make sure first two characters are not 0x + if (_temp[0] == 0x30) + { + require(_temp[1] != 0x78, "string cannot start with 0x"); + require(_temp[1] != 0x58, "string cannot start with 0X"); + } + + // create a bool to track if we have a non number character + bool _hasNonNumber; + + // convert & check + for (uint256 i = 0; i < _length; i++) + { + // if its uppercase A-Z + if (_temp[i] > 0x40 && _temp[i] < 0x5b) + { + // convert to lower case a-z + _temp[i] = byte(uint8(_temp[i]) + 32); + + // we have a non number + if (_hasNonNumber == false) + _hasNonNumber = true; + } else { + require + ( + // require character is a space + _temp[i] == 0x20 || + // OR lowercase a-z + (_temp[i] > 0x60 && _temp[i] < 0x7b) || + // or 0-9 + (_temp[i] > 0x2f && _temp[i] < 0x3a), + "string contains invalid characters" + ); + // make sure theres not 2x spaces in a row + if (_temp[i] == 0x20) + require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); + + // see if we have a character other than a number + if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) + _hasNonNumber = true; + } + } + + require(_hasNonNumber == true, "string cannot be only numbers"); + + bytes32 _ret; + assembly { + _ret := mload(add(_temp, 32)) + } + return (_ret); + } +} + + +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) + internal + pure + returns (uint256 c) + { + if (a == 0) { + return 0; + } + c = a * b; + require(c / a == b, "SafeMath mul failed"); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) + internal + pure + returns (uint256) + { + require(b <= a, "SafeMath sub failed"); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) + internal + pure + returns (uint256 c) + { + c = a + b; + require(c >= a, "SafeMath add failed"); + return c; + } + + /** + * @dev gives square root of given x. + */ + function sqrt(uint256 x) + internal + pure + returns (uint256 y) + { + uint256 z = ((add(x,1)) / 2); + y = x; + while (z < y) + { + y = z; + z = ((add((x / z),z)) / 2); + } + } + + /** + * @dev gives square. multiplies x by x + */ + function sq(uint256 x) + internal + pure + returns (uint256) + { + return (mul(x,x)); + } + + /** + * @dev x to the power of y + */ + function pwr(uint256 x, uint256 y) + internal + pure + returns (uint256) + { + if (x==0) + return (0); + else if (y==0) + return (1); + else + { + uint256 z = x; + for (uint256 i=1; i < y; i++) + z = mul(z,x); + return (z); + } + } +} + +//============================================================================== +// | _ _ _ | _ . +// |<(/_\/ (_(_||(_ . +//=======/====================================================================== +library F3DKeysCalcLong { + using SafeMath for *; + /** + * @dev calculates number of keys received given X eth + * @param _curEth current amount of eth in contract + * @param _newEth eth being spent + * @return amount of ticket purchased + */ + function keysRec(uint256 _curEth, uint256 _newEth) + internal + pure + returns (uint256) + { + return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); + } + + /** + * @dev calculates amount of eth received if you sold X keys + * @param _curKeys current amount of keys that exist + * @param _sellKeys amount of keys you wish to sell + * @return amount of eth received + */ + function ethRec(uint256 _curKeys, uint256 _sellKeys) + internal + pure + returns (uint256) + { + return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); + } + + /** + * @dev calculates how many keys would exist with given an amount of eth + * @param _eth eth "in contract" + * @return number of keys that would exist + */ + function keys(uint256 _eth) + internal + pure + returns(uint256) + { + return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); + } + + /** + * @dev calculates how much eth would be in contract given a number of keys + * @param _keys number of keys "in contract" + * @return eth that would exists + */ + function eth(uint256 _keys) + internal + pure + returns(uint256) + { + return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); + } +} + +library F3Ddatasets { + //compressedData key + // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] + // 0 - new player (bool) + // 1 - joined round (bool) + // 2 - new leader (bool) + // 3-5 - air drop tracker (uint 0-999) + // 6-16 - round end time + // 17 - winnerTeam + // 18 - 28 timestamp + // 29 - team + // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) + // 31 - airdrop happened bool + // 32 - airdrop tier + // 33 - airdrop amount won + //compressedIDs key + // [77-52][51-26][25-0] + // 0-25 - pID + // 26-51 - winPID + // 52-77 - rID + struct EventReturns { + uint256 compressedData; + uint256 compressedIDs; + address winnerAddr; // winner address + bytes32 winnerName; // winner name + uint256 amountWon; // amount won + uint256 newPot; // amount in new pot + uint256 P3DAmount; // amount distributed to p3d + uint256 genAmount; // amount distributed to gen + uint256 potAmount; // amount added to pot + } + struct Player { + address payable addr; // player address + bytes32 name; // player name + uint256 win; // winnings vault + uint256 gen; // general vault + uint256 aff; // affiliate vault + uint256 lrnd; // last round played + uint256 laff; // last affiliate id used + } + struct PlayerRounds { + uint256 eth; // eth player has added to round (used for eth limiter) + uint256 keys; // keys + uint256 mask; // player mask + uint256 ico; // ICO phase investment + } + struct Round { + uint256 plyr; // pID of player in lead + uint256 team; // tID of team in lead + uint256 end; // time ends/ended + bool ended; // has round end function been ran + uint256 strt; // time round started + uint256 keys; // keys + uint256 eth; // total eth in + uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) + uint256 mask; // global mask + uint256 ico; // total eth sent in during ICO phase + uint256 icoGen; // total eth for gen during ICO phase + uint256 icoAvg; // average key price for ICO phase + } + struct TeamFee { + uint256 gen; // % of buy in thats paid to key holders of current round + uint256 p3d; // % of buy in thats paid to p3d holders + } + struct PotSplit { + uint256 gen; // % of pot thats paid to key holders of current round + uint256 p3d; // % of pot thats paid to p3d holders + } +} + +contract F3Devents { + // fired whenever a player registers a name + event onNewName + ( + uint256 indexed playerID, + address indexed playerAddress, + bytes32 indexed playerName, + bool isNewPlayer, + uint256 affiliateID, + address affiliateAddress, + bytes32 affiliateName, + uint256 amountPaid, + uint256 timeStamp + ); + + // fired at end of buy or reload + event onEndTx + ( + uint256 compressedData, + uint256 compressedIDs, + bytes32 playerName, + address playerAddress, + uint256 ethIn, + uint256 keysBought, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 P3DAmount, + uint256 genAmount, + uint256 potAmount, + uint256 airDropPot + ); + + // fired whenever theres a withdraw + event onWithdraw + ( + uint256 indexed playerID, + address playerAddress, + bytes32 playerName, + uint256 ethOut, + uint256 timeStamp + ); + + // fired whenever a withdraw forces end round to be ran + event onWithdrawAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 ethOut, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 P3DAmount, + uint256 genAmount + ); + + // (fomo3d long only) fired whenever a player tries a buy after round timer + // hit zero, and causes end round to be ran. + event onBuyAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 ethIn, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 P3DAmount, + uint256 genAmount + ); + + // (fomo3d long only) fired whenever a player tries a reload after round timer + // hit zero, and causes end round to be ran. + event onReLoadAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 P3DAmount, + uint256 genAmount + ); + + // fired whenever an affiliate is paid + event onAffiliatePayout + ( + uint256 indexed affiliateID, + address affiliateAddress, + bytes32 affiliateName, + uint256 indexed roundID, + uint256 indexed buyerID, + uint256 amount, + uint256 timeStamp + ); + + // received pot swap deposit + event onPotSwapDeposit + ( + uint256 roundID, + uint256 amountAddedToPot + ); +} + + + +contract FoMo3Dlong is F3Devents { + using SafeMath for *; + using NameFilter for string; + using F3DKeysCalcLong for uint256; + + address public otherF3D_; + address public Divies; + address public Jekyll_Island_Inc; + PlayerBookInterface public playerBook;// =PlayerBookInterface(0x0dcd2f752394c41875e259e00bb44fd505297caf);//new PlayerBook();// + // TeamJustInterface constant private teamJust = TeamJustInterface(0x3a5f8140b9213a0f733a6a639857c9df43ee3f5a);// new TeamJust();// + + //============================================================================== + // _ _ _ |`. _ _ _ |_ | _ _ . + // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) + //=================_|=========================================================== + string constant public name = "FoMo3D Long Official"; + string constant public symbol = "F3D"; + uint256 private rndExtra_ = 30;//extSettings.getLongExtra(); // length of the very first ICO + uint256 private rndGap_ = 30; //extSettings.getLongGap(); // length of ICO phase, set to 1 year for EOS. + uint256 constant private rndInit_ = 1 hours; // round timer starts at this + uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer + uint256 constant private rndMax_ = 24 hours; // max length a round timer can be + //============================================================================== + // _| _ _|_ _ _ _ _|_ _ . + // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) + //=============================|================================================ + uint256 public airDropPot_; // person who gets the airdrop wins part of this pot + uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop + uint256 public rID_; // round id number / total rounds that have happened + //**************** + // PLAYER DATA + //**************** + mapping(address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address + mapping(bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name + mapping(uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data + mapping(uint256 => mapping(uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id + mapping(uint256 => mapping(bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) + //**************** + // ROUND DATA + //**************** + mapping(uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data + mapping(uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id + //**************** + // TEAM FEE DATA + //**************** + mapping(uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team + mapping(uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team + + function setPlayerBook(address _playerBook) external { + require(msg.sender == owner, 'only dev!'); + require(address(playerBook) == address(0), 'already set!'); + playerBook = PlayerBookInterface(_playerBook); + } + + address public owner; + + //============================================================================== + // _ _ _ __|_ _ __|_ _ _ . + // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) + //============================================================================== + constructor() + public + { + owner = msg.sender; + // Team allocation structures + // 0 = whales + // 1 = bears + // 2 = sneks + // 3 = bulls + + // Team allocation percentages + // (F3D, P3D) + (Pot , Referrals, Community) + // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. + fees_[0] = F3Ddatasets.TeamFee(30, 6); + //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot + fees_[1] = F3Ddatasets.TeamFee(43, 0); + //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot + fees_[2] = F3Ddatasets.TeamFee(56, 10); + //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot + fees_[3] = F3Ddatasets.TeamFee(43, 8); + //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot + + // how to split up the final pot based on which team was picked + // (F3D, P3D) + potSplit_[0] = F3Ddatasets.PotSplit(15, 10); + //48% to winner, 25% to next round, 2% to com + potSplit_[1] = F3Ddatasets.PotSplit(25, 0); + //48% to winner, 25% to next round, 2% to com + potSplit_[2] = F3Ddatasets.PotSplit(20, 20); + //48% to winner, 10% to next round, 2% to com + potSplit_[3] = F3Ddatasets.PotSplit(30, 10); + //48% to winner, 10% to next round, 2% to com + } + //============================================================================== + // _ _ _ _|. |`. _ _ _ . + // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) + //============================================================================== + /** + * @dev used to make sure no one can interact with contract until it has + * been activated. + */ + modifier isActivated() { + require(activated_ == true, "its not ready yet. check ?eta in discord"); + _; + } + + /** + * @dev prevents contracts from interacting with fomo3d + */ + modifier isHuman() { + address _addr = msg.sender; + uint256 _codeLength; + + assembly {_codeLength := extcodesize(_addr)} + require(_codeLength == 0, "sorry humans only"); + _; + } + + modifier onlyDevs() + { + require(playerBook.isDev(msg.sender) == true, "msg sender is not a dev"); + _; + } + + /** + * @dev sets boundaries for incoming tx + */ + modifier isWithinLimits(uint256 _eth) { + require(_eth >= 1000000000, "pocket lint: not a valid currency"); + require(_eth <= 100000000000000000000000, "no vitalik, no"); + _; + } + + //============================================================================== + // _ |_ |. _ |` _ __|_. _ _ _ . + // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) + //====|========================================================================= + /** + * @dev emergency buy uses last stored affiliate ID and team snek + */ + function() + isActivated() + isHuman() + isWithinLimits(msg.value) + external + payable + { + // set up our tx event data and determine if player is new or not + F3Ddatasets.EventReturns memory _eventData_ ; + _eventData_ = determinePID(_eventData_); + + // fetch player id + uint256 _pID = pIDxAddr_[msg.sender]; + + // buy core + buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); + } + + /** + * @dev converts all incoming ethereum to keys. + * -functionhash- 0x8f38f309 (using ID for affiliate) + * -functionhash- 0x98a0871d (using address for affiliate) + * -functionhash- 0xa65b37a1 (using name for affiliate) + * @param _affCode the ID/address/name of the player who gets the affiliate fee + * @param _team what team is the player playing for? + */ + function buyXid(uint256 _affCode, uint256 _team) + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + // set up our tx event data and determine if player is new or not + F3Ddatasets.EventReturns memory _eventData_; + _eventData_ = determinePID(_eventData_); + + // fetch player id + uint256 _pID = pIDxAddr_[msg.sender]; + + // manage affiliate residuals + // if no affiliate code was given or player tried to use their own, lolz + if (_affCode == 0 || _affCode == _pID) + { + // use last stored affiliate code + _affCode = plyr_[_pID].laff; + + // if affiliate code was given & its not the same as previously stored + } else if (_affCode != plyr_[_pID].laff) { + // update last affiliate + plyr_[_pID].laff = _affCode; + } + + // verify a valid team was selected + _team = verifyTeam(_team); + + // buy core + buyCore(_pID, _affCode, _team, _eventData_); + } + + function buyXaddr(address _affCode, uint256 _team) + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + // set up our tx event data and determine if player is new or not + F3Ddatasets.EventReturns memory _eventData_; + _eventData_ = determinePID(_eventData_); + + // fetch player id + uint256 _pID = pIDxAddr_[msg.sender]; + + // manage affiliate residuals + uint256 _affID; + // if no affiliate code was given or player tried to use their own, lolz + if (_affCode == address(0) || _affCode == msg.sender) + { + // use last stored affiliate code + _affID = plyr_[_pID].laff; + + // if affiliate code was given + } else { + // get affiliate ID from aff Code + _affID = pIDxAddr_[_affCode]; + + // if affID is not the same as previously stored + if (_affID != plyr_[_pID].laff) + { + // update last affiliate + plyr_[_pID].laff = _affID; + } + } + + // verify a valid team was selected + _team = verifyTeam(_team); + + // buy core + buyCore(_pID, _affID, _team, _eventData_); + } + + function buyXname(bytes32 _affCode, uint256 _team) + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + // set up our tx event data and determine if player is new or not + F3Ddatasets.EventReturns memory _eventData_ ; + _eventData_ = determinePID(_eventData_); + + // fetch player id + uint256 _pID = pIDxAddr_[msg.sender]; + + // manage affiliate residuals + uint256 _affID; + // if no affiliate code was given or player tried to use their own, lolz + if (_affCode == '' || _affCode == plyr_[_pID].name) + { + // use last stored affiliate code + _affID = plyr_[_pID].laff; + + // if affiliate code was given + } else { + // get affiliate ID from aff Code + _affID = pIDxName_[_affCode]; + + // if affID is not the same as previously stored + if (_affID != plyr_[_pID].laff) + { + // update last affiliate + plyr_[_pID].laff = _affID; + } + } + + // verify a valid team was selected + _team = verifyTeam(_team); + + // buy core + buyCore(_pID, _affID, _team, _eventData_); + } + + /** + * @dev essentially the same as buy, but instead of you sending ether + * from your wallet, it uses your unwithdrawn earnings. + * -functionhash- 0x349cdcac (using ID for affiliate) + * -functionhash- 0x82bfc739 (using address for affiliate) + * -functionhash- 0x079ce327 (using name for affiliate) + * @param _affCode the ID/address/name of the player who gets the affiliate fee + * @param _team what team is the player playing for? + * @param _eth amount of earnings to use (remainder returned to gen vault) + */ + function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) + isActivated() + isHuman() + isWithinLimits(_eth) + public + { + // set up our tx event data + F3Ddatasets.EventReturns memory _eventData_; + + // fetch player ID + uint256 _pID = pIDxAddr_[msg.sender]; + + // manage affiliate residuals + // if no affiliate code was given or player tried to use their own, lolz + if (_affCode == 0 || _affCode == _pID) + { + // use last stored affiliate code + _affCode = plyr_[_pID].laff; + + // if affiliate code was given & its not the same as previously stored + } else if (_affCode != plyr_[_pID].laff) { + // update last affiliate + plyr_[_pID].laff = _affCode; + } + + // verify a valid team was selected + _team = verifyTeam(_team); + + // reload core + reLoadCore(_pID, _affCode, _team, _eth, _eventData_); + } + + function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) + isActivated() + isHuman() + isWithinLimits(_eth) + public + { + // set up our tx event data + F3Ddatasets.EventReturns memory _eventData_; + + // fetch player ID + uint256 _pID = pIDxAddr_[msg.sender]; + + // manage affiliate residuals + uint256 _affID; + // if no affiliate code was given or player tried to use their own, lolz + if (_affCode == address(0) || _affCode == msg.sender) + { + // use last stored affiliate code + _affID = plyr_[_pID].laff; + + // if affiliate code was given + } else { + // get affiliate ID from aff Code + _affID = pIDxAddr_[_affCode]; + + // if affID is not the same as previously stored + if (_affID != plyr_[_pID].laff) + { + // update last affiliate + plyr_[_pID].laff = _affID; + } + } + + // verify a valid team was selected + _team = verifyTeam(_team); + + // reload core + reLoadCore(_pID, _affID, _team, _eth, _eventData_); + } + + function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) + isActivated() + isHuman() + isWithinLimits(_eth) + public + { + // set up our tx event data + F3Ddatasets.EventReturns memory _eventData_; + + // fetch player ID + uint256 _pID = pIDxAddr_[msg.sender]; + + // manage affiliate residuals + uint256 _affID; + // if no affiliate code was given or player tried to use their own, lolz + if (_affCode == '' || _affCode == plyr_[_pID].name) + { + // use last stored affiliate code + _affID = plyr_[_pID].laff; + + // if affiliate code was given + } else { + // get affiliate ID from aff Code + _affID = pIDxName_[_affCode]; + + // if affID is not the same as previously stored + if (_affID != plyr_[_pID].laff) + { + // update last affiliate + plyr_[_pID].laff = _affID; + } + } + + // verify a valid team was selected + _team = verifyTeam(_team); + + // reload core + reLoadCore(_pID, _affID, _team, _eth, _eventData_); + } + + /** + * @dev withdraws all of your earnings. + * -functionhash- 0x3ccfd60b + */ + function withdraw() + isActivated() + isHuman() + public + { + // setup local rID + uint256 _rID = rID_; + + // grab time + uint256 _now = now; + + // fetch player ID + uint256 _pID = pIDxAddr_[msg.sender]; + + // setup temp var for player eth + uint256 _eth; + + // check to see if round has ended and no one has run round end yet + if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) + { + // set up our tx event data + F3Ddatasets.EventReturns memory _eventData_; + + // end the round (distributes pot) + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + + // get their earnings + _eth = withdrawEarnings(_pID); + + // gib moni + if (_eth > 0) + plyr_[_pID].addr.transfer(_eth); + + // build event data + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + // fire withdraw and distribute event + emit F3Devents.onWithdrawAndDistribute + ( + msg.sender, + plyr_[_pID].name, + _eth, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.P3DAmount, + _eventData_.genAmount + ); + + // in any other situation + } else { + // get their earnings + _eth = withdrawEarnings(_pID); + + // gib moni + if (_eth > 0) + plyr_[_pID].addr.transfer(_eth); + + // fire withdraw event + emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); + } + } + + /** + * @dev use these to register names. they are just wrappers that will send the + * registration requests to the PlayerBook contract. So registering here is the + * same as registering there. UI will always display the last name you registered. + * but you will still own all previously registered names to use as affiliate + * links. + * - must pay a registration fee. + * - name must be unique + * - names will be converted to lowercase + * - name cannot start or end with a space + * - cannot have more than 1 space in a row + * - cannot be only numbers + * - cannot start with 0x + * - name must be at least 1 char + * - max length of 32 characters long + * - allowed characters: a-z, 0-9, and space + * -functionhash- 0x921dec21 (using ID for affiliate) + * -functionhash- 0x3ddd4698 (using address for affiliate) + * -functionhash- 0x685ffd83 (using name for affiliate) + * @param _nameString players desired name + * @param _affCode affiliate ID, address, or name of who referred you + * @param _all set to true if you want this to push your info to all games + * (this might cost a lot of gas) + */ + function registerNameXID(string memory _nameString, uint256 _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + // fire event + emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + + function registerNameXaddr(string memory _nameString, address _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + // fire event + emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + + function registerNameXname(string memory _nameString, bytes32 _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + // fire event + emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + //============================================================================== + // _ _ _|__|_ _ _ _ . + // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) + //=====_|======================================================================= + /** + * @dev return the price buyer will pay for next 1 individual key. + * -functionhash- 0x018a25e8 + * @return price for next key bought (in wei format) + */ + function getBuyPrice() + public + view + returns (uint256) + { + // setup local rID + uint256 _rID = rID_; + + // grab time + uint256 _now = now; + + // are we in a round? + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ((round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000)); + else // rounds over. need price for new round + return (75000000000000); + // init + } + + /** + * @dev returns time left. dont spam this, you'll ddos yourself from your node + * provider + * -functionhash- 0xc7e284b8 + * @return time left in seconds + */ + function getTimeLeft() + public + view + returns (uint256) + { + // setup local rID + uint256 _rID = rID_; + + // grab time + uint256 _now = now; + + if (_now < round_[_rID].end) + if (_now > round_[_rID].strt + rndGap_) + return ((round_[_rID].end).sub(_now)); + else + return ((round_[_rID].strt + rndGap_).sub(_now)); + else + return (0); + } + + /** + * @dev returns player earnings per vaults + * -functionhash- 0x63066434 + * @return winnings vault + * @return general vault + * @return affiliate vault + */ + function getPlayerVaults(uint256 _pID) + public + view + returns (uint256, uint256, uint256) + { + // setup local rID + uint256 _rID = rID_; + + // if round has ended. but round end has not been run (so contract has not distributed winnings) + if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) + { + // if player is winner + if (round_[_rID].plyr == _pID) + { + return + ( + (plyr_[_pID].win).add(((round_[_rID].pot).mul(48)) / 100), + (plyr_[_pID].gen).add(getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)), + plyr_[_pID].aff + ); + // if player is not the winner + } else { + return + ( + plyr_[_pID].win, + (plyr_[_pID].gen).add(getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)), + plyr_[_pID].aff + ); + } + + // if round is still going on, or round has ended and round end has been ran + } else { + return + ( + plyr_[_pID].win, + (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), + plyr_[_pID].aff + ); + } + } + + /** + * solidity hates stack limits. this lets us avoid that hate + */ + function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) + private + view + returns (uint256) + { + return (((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000)); + } + + /** + * @dev returns all current round info needed for front end + * -functionhash- 0x747dff42 + * @return eth invested during ICO phase + * @return round id + * @return total keys for round + * @return time round ends + * @return time round started + * @return current pot + * @return current team ID & player ID in lead + * @return current player in leads address + * @return current player in leads name + * @return whales eth in for round + * @return bears eth in for round + * @return sneks eth in for round + * @return bulls eth in for round + * @return airdrop tracker # & airdrop pot + */ + function getCurrentRoundInfo() + public + view + returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) + { + // setup local rID + uint256 _rID = rID_; + + return + ( + round_[_rID].ico, //0 + _rID, //1 + round_[_rID].keys, //2 + round_[_rID].end, //3 + round_[_rID].strt, //4 + round_[_rID].pot, //5 + (round_[_rID].team + (round_[_rID].plyr * 10)), //6 + plyr_[round_[_rID].plyr].addr, //7 + plyr_[round_[_rID].plyr].name, //8 + rndTmEth_[_rID][0], //9 + rndTmEth_[_rID][1], //10 + rndTmEth_[_rID][2], //11 + rndTmEth_[_rID][3], //12 + airDropTracker_ + (airDropPot_ * 1000) //13 + ); + } + + /** + * @dev returns player info based on address. if no address is given, it will + * use msg.sender + * -functionhash- 0xee0b5d8b + * @param _addr address of the player you want to lookup + * @return player ID + * @return player name + * @return keys owned (current round) + * @return winnings vault + * @return general vault + * @return affiliate vault + * @return player round eth + */ + function getPlayerInfoByAddress(address _addr) + public + view + returns (uint256, bytes32, uint256, uint256, uint256, uint256, uint256) + { + // setup local rID + uint256 _rID = rID_; + + if (_addr == address(0)) + { + _addr == msg.sender; + } + uint256 _pID = pIDxAddr_[_addr]; + + return + ( + _pID, //0 + plyr_[_pID].name, //1 + plyrRnds_[_pID][_rID].keys, //2 + plyr_[_pID].win, //3 + (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 + plyr_[_pID].aff, //5 + plyrRnds_[_pID][_rID].eth //6 + ); + } + + //============================================================================== + // _ _ _ _ | _ _ . _ . + // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) + //=====================_|======================================================= + /** + * @dev logic runs whenever a buy order is executed. determines how to handle + * incoming eth depending on if we are in an active round or not + */ + function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) + private + { + // setup local rID + uint256 _rID = rID_; + + // grab time + uint256 _now = now; + + // if round is active + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + { + // call core + core(_rID, _pID, msg.value, _affID, _team, _eventData_); + + // if round is not active + } else { + // check to see if end round needs to be ran + if (_now > round_[_rID].end && round_[_rID].ended == false) + { + // end the round (distributes pot) & start new round + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + + // build event data + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + // fire buy and distribute event + emit F3Devents.onBuyAndDistribute + ( + msg.sender, + plyr_[_pID].name, + msg.value, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.P3DAmount, + _eventData_.genAmount + ); + } + + // put eth in players vault + plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); + } + } + + /** + * @dev logic runs whenever a reload order is executed. determines how to handle + * incoming eth depending on if we are in an active round or not + */ + function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) + private + { + // setup local rID + uint256 _rID = rID_; + + // grab time + uint256 _now = now; + + // if round is active + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + { + // get earnings from all vaults and return unused to gen vault + // because we use a custom safemath library. this will throw if player + // tried to spend more eth than they have. + plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); + + // call core + core(_rID, _pID, _eth, _affID, _team, _eventData_); + + // if round is not active and end round needs to be ran + } else if (_now > round_[_rID].end && round_[_rID].ended == false) { + // end the round (distributes pot) & start new round + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + + // build event data + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + // fire buy and distribute event + emit F3Devents.onReLoadAndDistribute + ( + msg.sender, + plyr_[_pID].name, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.P3DAmount, + _eventData_.genAmount + ); + } + } + + /** + * @dev this is the core logic for any buy/reload that happens while a round + * is live. + */ + function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) + private + { + // if player is new to round + if (plyrRnds_[_pID][_rID].keys == 0) + _eventData_ = managePlayer(_pID, _eventData_); + + // early round eth limiter + if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) + { + uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); + uint256 _refund = _eth.sub(_availableLimit); + plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); + _eth = _availableLimit; + } + + // if eth left is greater than min eth allowed (sorry no pocket lint) + if (_eth > 1000000000) + { + + // mint the new keys + uint256 _keys = (round_[_rID].eth).keysRec(_eth); + + // if they bought at least 1 whole key + if (_keys >= 1000000000000000000) + { + updateTimer(_keys, _rID); + + // set new leaders + if (round_[_rID].plyr != _pID) + round_[_rID].plyr = _pID; + if (round_[_rID].team != _team) + round_[_rID].team = _team; + + // set the new leader bool to true + _eventData_.compressedData = _eventData_.compressedData + 100; + } + + // manage airdrops + if (_eth >= 100000000000000000) + { + airDropTracker_++; + if (airdrop() == true) + { + // gib muni + uint256 _prize; + if (_eth >= 10000000000000000000) + { + // calculate prize and give it to winner + _prize = ((airDropPot_).mul(75)) / 100; + plyr_[_pID].win = (plyr_[_pID].win).add(_prize); + + // adjust airDropPot + airDropPot_ = (airDropPot_).sub(_prize); + + // let event know a tier 3 prize was won + _eventData_.compressedData += 300000000000000000000000000000000; + } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { + // calculate prize and give it to winner + _prize = ((airDropPot_).mul(50)) / 100; + plyr_[_pID].win = (plyr_[_pID].win).add(_prize); + + // adjust airDropPot + airDropPot_ = (airDropPot_).sub(_prize); + + // let event know a tier 2 prize was won + _eventData_.compressedData += 200000000000000000000000000000000; + } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { + // calculate prize and give it to winner + _prize = ((airDropPot_).mul(25)) / 100; + plyr_[_pID].win = (plyr_[_pID].win).add(_prize); + + // adjust airDropPot + airDropPot_ = (airDropPot_).sub(_prize); + + // let event know a tier 3 prize was won + _eventData_.compressedData += 300000000000000000000000000000000; + } + // set airdrop happened bool to true + _eventData_.compressedData += 10000000000000000000000000000000; + // let event know how much was won + _eventData_.compressedData += _prize * 1000000000000000000000000000000000; + + // reset air drop tracker + airDropTracker_ = 0; + } + } + + // store the air drop tracker number (number of buys since last airdrop) + _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); + + // update player + plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); + plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); + + // update round + round_[_rID].keys = _keys.add(round_[_rID].keys); + round_[_rID].eth = _eth.add(round_[_rID].eth); + rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); + + // distribute eth + _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); + _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); + + // call end tx function to fire end tx event. + endTx(_pID, _team, _eth, _keys, _eventData_); + } + } + //============================================================================== + // _ _ | _ | _ _|_ _ _ _ . + // (_(_||(_|_||(_| | (_)| _\ . + //============================================================================== + /** + * @dev calculates unmasked earnings (just calculates, does not update mask) + * @return earnings in wei format + */ + function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) + private + view + returns (uint256) + { + return ((((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask)); + } + + /** + * @dev returns the amount of keys you would get given an amount of eth. + * -functionhash- 0xce89c80c + * @param _rID round ID you want price for + * @param _eth amount of eth sent in + * @return keys received + */ + function calcKeysReceived(uint256 _rID, uint256 _eth) + public + view + returns (uint256) + { + // grab time + uint256 _now = now; + + // are we in a round? + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ((round_[_rID].eth).keysRec(_eth)); + else // rounds over. need keys for new round + return ((_eth).keys()); + } + + /** + * @dev returns current eth price for X keys. + * -functionhash- 0xcf808000 + * @param _keys number of keys desired (in 18 decimal format) + * @return amount of eth needed to send + */ + function iWantXKeys(uint256 _keys) + public + view + returns (uint256) + { + // setup local rID + uint256 _rID = rID_; + + // grab time + uint256 _now = now; + + // are we in a round? + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ((round_[_rID].keys.add(_keys)).ethRec(_keys)); + else // rounds over. need price for new round + return ((_keys).eth()); + } + //============================================================================== + // _|_ _ _ | _ . + // | (_)(_)|_\ . + //============================================================================== + /** + * @dev receives name/player info from names contract + */ + function receivePlayerInfo(uint256 _pID, address payable _addr, bytes32 _name, uint256 _laff) + external + { + require(msg.sender == address(playerBook), "your not playerNames contract... hmmm.."); + if (pIDxAddr_[_addr] != _pID) + pIDxAddr_[_addr] = _pID; + if (pIDxName_[_name] != _pID) + pIDxName_[_name] = _pID; + if (plyr_[_pID].addr != _addr) + plyr_[_pID].addr = _addr; + if (plyr_[_pID].name != _name) + plyr_[_pID].name = _name; + if (plyr_[_pID].laff != _laff) + plyr_[_pID].laff = _laff; + if (plyrNames_[_pID][_name] == false) + plyrNames_[_pID][_name] = true; + } + + /** + * @dev receives entire player name list + */ + function receivePlayerNameList(uint256 _pID, bytes32 _name) + external + { + require(msg.sender == address(playerBook), "your not playerNames contract... hmmm.."); + if (plyrNames_[_pID][_name] == false) + plyrNames_[_pID][_name] = true; + } + + /** + * @dev gets existing or registers new pID. use this when a player may be new + * @return pID + */ + function determinePID(F3Ddatasets.EventReturns memory _eventData_) + private + returns (F3Ddatasets.EventReturns memory) + { + uint256 _pID = pIDxAddr_[msg.sender]; + // if player is new to this version of fomo3d + if (_pID == 0) + { + // grab their player ID, name and last aff ID, from player names contract + _pID = playerBook.getPlayerID(msg.sender); + bytes32 _name = playerBook.getPlayerName(_pID); + uint256 _laff = playerBook.getPlayerLAff(_pID); + + // set up player account + pIDxAddr_[msg.sender] = _pID; + plyr_[_pID].addr = msg.sender; + + if (_name != "") + { + pIDxName_[_name] = _pID; + plyr_[_pID].name = _name; + plyrNames_[_pID][_name] = true; + } + + if (_laff != 0 && _laff != _pID) + plyr_[_pID].laff = _laff; + + // set the new player bool to true + _eventData_.compressedData = _eventData_.compressedData + 1; + } + return (_eventData_); + } + + /** + * @dev checks to make sure user picked a valid team. if not sets team + * to default (sneks) + */ + function verifyTeam(uint256 _team) + private + pure + returns (uint256) + { + if (_team < 0 || _team > 3) + return (2); + else + return (_team); + } + + /** + * @dev decides if round end needs to be run & new round started. and if + * player unmasked earnings from previously played rounds need to be moved. + */ + function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) + private + returns (F3Ddatasets.EventReturns memory) + { + // if player has played a previous round, move their unmasked earnings + // from that round to gen vault. + if (plyr_[_pID].lrnd != 0) + updateGenVault(_pID, plyr_[_pID].lrnd); + + // update player's last round played + plyr_[_pID].lrnd = rID_; + + // set the joined round bool to true + _eventData_.compressedData = _eventData_.compressedData + 10; + + return (_eventData_); + } + + /** + * @dev ends the round. manages paying out winner/splitting up pot + */ + function endRound(F3Ddatasets.EventReturns memory _eventData_) + private + returns (F3Ddatasets.EventReturns memory) + { + // setup local rID + uint256 _rID = rID_; + + // grab our winning player and team id's + uint256 _winPID = round_[_rID].plyr; + uint256 _winTID = round_[_rID].team; + + // grab our pot amount + uint256 _pot = round_[_rID].pot; + + // calculate our winner share, community rewards, gen share, + // p3d share, and amount reserved for next pot + uint256 _win = (_pot.mul(48)) / 100; + uint256 _com = (_pot / 50); + uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; + uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; + uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); + + // calculate ppt for round mask + uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); + uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); + if (_dust > 0) + { + _gen = _gen.sub(_dust); + _res = _res.add(_dust); + } + + // pay our winner + plyr_[_winPID].win = _win.add(plyr_[_winPID].win); + + // community rewards + address payable add = address(uint160(Jekyll_Island_Inc)); + if (!add.send(_com)) + { + // This ensures Team Just cannot influence the outcome of FoMo3D with + // bank migrations by breaking outgoing transactions. + // Something we would never do. But that's not the point. + // We spent 2000$ in eth re-deploying just to patch this, we hold the + // highest belief that everything we create should be trustless. + // Team JUST, The name you shouldn't have to trust. + _p3d = _p3d.add(_com); + _com = 0; + } + + // distribute gen portion to key holders + round_[_rID].mask = _ppt.add(round_[_rID].mask); + + // send share for p3d to divies + if (_p3d > 0){ + address payable addr = address(uint160(Divies)); + addr.transfer(_p3d); + } + // prepare event data + _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); + _eventData_.winnerAddr = plyr_[_winPID].addr; + _eventData_.winnerName = plyr_[_winPID].name; + _eventData_.amountWon = _win; + _eventData_.genAmount = _gen; + _eventData_.P3DAmount = _p3d; + _eventData_.newPot = _res; + + // start next round + rID_++; + _rID++; + round_[_rID].strt = now; + round_[_rID].end = now.add(rndInit_).add(rndGap_); + round_[_rID].pot = _res; + + return (_eventData_); + } + + /** + * @dev moves any unmasked earnings to gen vault. updates earnings mask + */ + function updateGenVault(uint256 _pID, uint256 _rIDlast) + private + { + uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); + if (_earnings > 0) + { + // put in gen vault + plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); + // zero out their earnings by updating mask + plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); + } + } + + /** + * @dev updates round timer based on number of whole keys bought. + */ + function updateTimer(uint256 _keys, uint256 _rID) + private + { + // grab time + uint256 _now = now; + + // calculate time based on number of keys bought + uint256 _newTime; + if (_now > round_[_rID].end && round_[_rID].plyr == 0) + _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); + else + _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); + + // compare to max and set new end time + if (_newTime < (rndMax_).add(_now)) + round_[_rID].end = _newTime; + else + round_[_rID].end = rndMax_.add(_now); + } + + /** + * @dev generates a random number between 0-99 and checks to see if thats + * resulted in an airdrop win + * @return do we have a winner? + */ + function airdrop() + private + view + returns (bool) + { + uint256 seed = uint256(keccak256(abi.encodePacked( + + (block.timestamp).add + (block.difficulty).add + ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add + (block.gaslimit).add + ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add + (block.number) + + ))); + if ((seed - ((seed / 1000) * 1000)) < airDropTracker_) + return (true); + else + return (false); + } + + /** + * @dev distributes eth based on fees to com, aff, and p3d + */ + function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) + private + returns (F3Ddatasets.EventReturns memory) + { + // pay 2% out to community rewards + uint256 _com = _eth / 50; + uint256 _p3d; + address payable addr = address(uint160(Jekyll_Island_Inc)); + if (!addr.send(_com)) + { + // This ensures Team Just cannot influence the outcome of FoMo3D with + // bank migrations by breaking outgoing transactions. + // Something we would never do. But that's not the point. + // We spent 2000$ in eth re-deploying just to patch this, we hold the + // highest belief that everything we create should be trustless. + // Team JUST, The name you shouldn't have to trust. + _p3d = _com; + _com = 0; + } + + // pay 1% out to FoMo3D short + _com = _eth / 100; + address payable add = address(uint160(otherF3D_)); + add.transfer(_com); + + // distribute share to affiliate + _com = _eth / 10; + + // decide what to do with affiliate share of fees + // affiliate must not be self, and must have a name registered + if (_affID != _pID && plyr_[_affID].name != '') { + plyr_[_affID].aff = _com.add(plyr_[_affID].aff); + emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _com, now); + } else { + _p3d = _com; + } + + // pay out p3d + _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); + if (_p3d > 0) + { + // deposit to divies contract + address payable add = address(uint160(Divies)); + add.transfer(_p3d); + + // set up event data + _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); + } + + return (_eventData_); + } + + function potSwap() + external + payable + { + // setup local rID + uint256 _rID = rID_ + 1; + + round_[_rID].pot = round_[_rID].pot.add(msg.value); + emit F3Devents.onPotSwapDeposit(_rID, msg.value); + } + + /** + * @dev distributes eth based on fees to gen and pot + */ + function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) + private + returns (F3Ddatasets.EventReturns memory) + { + // calculate gen share + uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; + + // toss 1% into airdrop pot + uint256 _air = (_eth / 100); + airDropPot_ = airDropPot_.add(_air); + + // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) + _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); + + // calculate pot + uint256 _pot = _eth.sub(_gen); + + // distribute gen share (thats what updateMasks() does) and adjust + // balances for dust. + uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); + if (_dust > 0) + _gen = _gen.sub(_dust); + + // add eth to pot + round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); + + // set up event data + _eventData_.genAmount = _gen.add(_eventData_.genAmount); + _eventData_.potAmount = _pot; + + return (_eventData_); + } + + /** + * @dev updates masks for round and player when keys are bought + * @return dust left over + */ + function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) + private + returns (uint256) + { + /* MASKING NOTES + earnings masks are a tricky thing for people to wrap their minds around. + the basic thing to understand here. is were going to have a global + tracker based on profit per share for each round, that increases in + relevant proportion to the increase in share supply. + + the player will have an additional mask that basically says "based + on the rounds mask, my shares, and how much i've already withdrawn, + how much is still owed to me?" + */ + + // calc profit per key & round mask based on this buy: (dust goes to pot) + uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); + round_[_rID].mask = _ppt.add(round_[_rID].mask); + + // calculate player earning from their own buy (only based on the keys + // they just bought). & update player earnings mask + uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); + plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); + + // calculate & return dust + return (_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); + } + + /** + * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 + * @return earnings in wei format + */ + function withdrawEarnings(uint256 _pID) + private + returns (uint256) + { + // update gen vault + updateGenVault(_pID, plyr_[_pID].lrnd); + + // from vaults + uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); + if (_earnings > 0) + { + plyr_[_pID].win = 0; + plyr_[_pID].gen = 0; + plyr_[_pID].aff = 0; + } + + return (_earnings); + } + + /** + * @dev prepares compression data and fires event for buy or reload tx's + */ + function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) + private + { + _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); + + emit F3Devents.onEndTx + ( + _eventData_.compressedData, + _eventData_.compressedIDs, + plyr_[_pID].name, + msg.sender, + _eth, + _keys, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.P3DAmount, + _eventData_.genAmount, + _eventData_.potAmount, + airDropPot_ + ); + } + //============================================================================== + // (~ _ _ _._|_ . + // _)(/_(_|_|| | | \/ . + //====================/========================================================= + /** upon contract deploy, it will be deactivated. this is a one time + * use function that will activate the contract. we do this so devs + * have time to set things up on the web end **/ + bool public activated_ = false; + + function activate() + public + onlyDevs + { + + // can only be ran once + require(activated_ == false, "fomo3d already activated"); + + // activate the contract + activated_ = true; + + otherF3D_ = msg.sender; + Divies = msg.sender; + Jekyll_Island_Inc = msg.sender; + + // lets start first round + rID_ = 1; + round_[1].strt = now + rndExtra_ - rndGap_; + round_[1].end = now + rndInit_ + rndExtra_; + } + + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario007.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario007.sol new file mode 100644 index 00000000000..1e6ff5d7250 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractScenario007.sol @@ -0,0 +1,1433 @@ +//pragma solidity 0.4.24; + +/** + * @title ERC165 + * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md + */ +interface ERC165 { + + /** + * @notice Query if a contract implements an interface + * @param _interfaceId The interface identifier, as specified in ERC-165 + * @dev Interface identification is specified in ERC-165. This function + * uses less than 30,000 gas. + */ + function supportsInterface(bytes4 _interfaceId) external view returns (bool); + +} + +contract ERC721Basic is ERC165 { + + event Transfer( + address indexed _from, + address indexed _to, + uint256 indexed _tokenId + ); + event Approval( + address indexed _owner, + address indexed _approved, + uint256 indexed _tokenId + ); + event ApprovalForAll( + address indexed _owner, + address indexed _operator, + bool _approved + ); + + function balanceOf(address _owner) public view returns (uint256 _balance); + function ownerOf(uint256 _tokenId) public view returns (address _owner); + function exists(uint256 _tokenId) public view returns (bool _exists); + + function approve(address _to, uint256 _tokenId) public; + function getApproved(uint256 _tokenId) + public view returns (address _operator); + + function setApprovalForAll(address _operator, bool _approved) public; + function isApprovedForAll(address _owner, address _operator) + public view returns (bool); + + function transferFrom(address _from, address _to, uint256 _tokenId) public; + function safeTransferFrom(address _from, address _to, uint256 _tokenId) + public; + + function safeTransferFrom( + address _from, + address _to, + uint256 _tokenId, + bytes memory _data + ) + public; +} + + +/** + * @title SupportsInterfaceWithLookup + * @author Matt Condon (@shrugs) + * @dev Implements ERC165 using a lookup table. + */ +contract SupportsInterfaceWithLookup is ERC165 { + bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; + /** + * 0x01ffc9a7 === + * bytes4(keccak256('supportsInterface(bytes4)')) + */ + + /** + * @dev a mapping of interface id to whether or not it's supported + */ + mapping(bytes4 => bool) internal supportedInterfaces; + + /** + * @dev A contract implementing SupportsInterfaceWithLookup + * implement ERC165 itself + */ + constructor() public { + _registerInterface(InterfaceId_ERC165); + } + + /** + * @dev implement supportsInterface(bytes4) using a lookup table + */ + function supportsInterface(bytes4 _interfaceId) external view returns (bool) { + return supportedInterfaces[_interfaceId]; + } + + /** + * @dev private method for registering an interface + */ + function _registerInterface(bytes4 _interfaceId) internal { + require(_interfaceId != 0xffffffff); + supportedInterfaces[_interfaceId] = true; + } +} + +contract Governable { + + event Pause(); + event Unpause(); + + address public governor; + bool public paused = false; + + constructor() public { + governor = msg.sender; + } + + function setGovernor(address _gov) public onlyGovernor { + governor = _gov; + } + + modifier onlyGovernor { + require(msg.sender == governor); + _; + } + + /** + * @dev Modifier to make a function callable only when the contract is not paused. + */ + modifier whenNotPaused() { + require(!paused); + _; + } + + /** + * @dev Modifier to make a function callable only when the contract is paused. + */ + modifier whenPaused() { + require(paused); + _; + } + + /** + * @dev called by the owner to pause, triggers stopped state + */ + function pause() onlyGovernor whenNotPaused public { + paused = true; + emit Pause(); + } + + /** + * @dev called by the owner to unpause, returns to normal state + */ + function unpause() onlyGovernor whenPaused public { + paused = false; + emit Unpause(); + } + +} + +contract CardBase is Governable { + + struct Card { + uint16 proto; + uint16 purity; + } + + function getCard(uint id) public view returns (uint16 proto, uint16 purity) { + Card memory card = cards[id]; + return (card.proto, card.purity); + } + + function getShine(uint16 purity) public pure returns (uint8) { + return uint8(purity / 1000); + } + + Card[] public cards; + +} + +contract CardProto is CardBase { + + event NewProtoCard( + uint16 id, uint8 season, uint8 god, + Rarity rarity, uint8 mana, uint8 attack, + uint8 health, uint8 cardType, uint8 tribe, bool packable + ); + + struct Limit { + uint64 limit; + bool exists; + } + + // limits for mythic cards + mapping(uint16 => Limit) public limits; + + // can only set limits once + function setLimit(uint16 id, uint64 limit) public onlyGovernor { + Limit memory l = limits[id]; + require(!l.exists); + limits[id] = Limit({ + limit: limit, + exists: true + }); + } + + function getLimit(uint16 id) public view returns (uint64 limit, bool set) { + Limit memory l = limits[id]; + return (l.limit, l.exists); + } + + // could make these arrays to save gas + // not really necessary - will be update a very limited no of times + mapping(uint8 => bool) public seasonTradable; + mapping(uint8 => bool) public seasonTradabilityLocked; + uint8 public currentSeason; + + function makeTradable(uint8 season) public onlyGovernor { + seasonTradable[season] = true; + } + + function makeUntradable(uint8 season) public onlyGovernor { + require(!seasonTradabilityLocked[season]); + seasonTradable[season] = false; + } + + function makePermanantlyTradable(uint8 season) public onlyGovernor { + require(seasonTradable[season]); + seasonTradabilityLocked[season] = true; + } + + function isTradable(uint16 proto) public view returns (bool) { + return seasonTradable[protos[proto].season]; + } + + function nextSeason() public onlyGovernor { + //Seasons shouldn't go to 0 if there is more than the uint8 should hold, the governor should know this ¯\_(ツ)_/¯ -M + require(currentSeason <= 255); + + currentSeason++; + mythic.length = 0; + legendary.length = 0; + epic.length = 0; + rare.length = 0; + common.length = 0; + } + + enum Rarity { + Common, + Rare, + Epic, + Legendary, + Mythic + } + + uint8 constant SPELL = 1; + uint8 constant MINION = 2; + uint8 constant WEAPON = 3; + uint8 constant HERO = 4; + + struct ProtoCard { + bool exists; + uint8 god; + uint8 season; + uint8 cardType; + Rarity rarity; + uint8 mana; + uint8 attack; + uint8 health; + uint8 tribe; + } + + // there is a particular design decision driving this: + // need to be able to iterate over mythics only for card generation + // don't store 5 different arrays: have to use 2 ids + // better to bear this cost (2 bytes per proto card) + // rather than 1 byte per instance + + uint16 public protoCount; + + mapping(uint16 => ProtoCard) protos; + + uint16[] public mythic; + uint16[] public legendary; + uint16[] public epic; + uint16[] public rare; + uint16[] public common; + + function addProtos( + uint16[] memory externalIDs, uint8[] memory gods, Rarity[] memory rarities, uint8[] memory manas, uint8[] memory attacks, + uint8[] memory healths, uint8[] memory cardTypes, uint8[] memory tribes, bool[] memory packable + ) public onlyGovernor returns(uint16) { + + for (uint i = 0; i < externalIDs.length; i++) { + + ProtoCard memory card = ProtoCard({ + exists: true, + god: gods[i], + season: currentSeason, + cardType: cardTypes[i], + rarity: rarities[i], + mana: manas[i], + attack: attacks[i], + health: healths[i], + tribe: tribes[i] + }); + + _addProto(externalIDs[i], card, packable[i]); + } + + } + + function addProto( + uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable + ) public onlyGovernor returns(uint16) { + ProtoCard memory card = ProtoCard({ + exists: true, + god: god, + season: currentSeason, + cardType: cardType, + rarity: rarity, + mana: mana, + attack: attack, + health: health, + tribe: tribe + }); + + _addProto(externalID, card, packable); + } + + function addWeapon( + uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 durability, bool packable + ) public onlyGovernor returns(uint16) { + + ProtoCard memory card = ProtoCard({ + exists: true, + god: god, + season: currentSeason, + cardType: WEAPON, + rarity: rarity, + mana: mana, + attack: attack, + health: durability, + tribe: 0 + }); + + _addProto(externalID, card, packable); + } + + function addSpell(uint16 externalID, uint8 god, Rarity rarity, uint8 mana, bool packable) public onlyGovernor returns(uint16) { + + ProtoCard memory card = ProtoCard({ + exists: true, + god: god, + season: currentSeason, + cardType: SPELL, + rarity: rarity, + mana: mana, + attack: 0, + health: 0, + tribe: 0 + }); + + _addProto(externalID, card, packable); + } + + function addMinion( + uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe, bool packable + ) public onlyGovernor returns(uint16) { + + ProtoCard memory card = ProtoCard({ + exists: true, + god: god, + season: currentSeason, + cardType: MINION, + rarity: rarity, + mana: mana, + attack: attack, + health: health, + tribe: tribe + }); + + _addProto(externalID, card, packable); + } + + function _addProto(uint16 externalID, ProtoCard memory card, bool packable) internal { + + require(!protos[externalID].exists); + + card.exists = true; + + protos[externalID] = card; + + protoCount++; + + emit NewProtoCard( + externalID, currentSeason, card.god, + card.rarity, card.mana, card.attack, + card.health, card.cardType, card.tribe, packable + ); + + if (packable) { + Rarity rarity = card.rarity; + if (rarity == Rarity.Common) { + common.push(externalID); + } else if (rarity == Rarity.Rare) { + rare.push(externalID); + } else if (rarity == Rarity.Epic) { + epic.push(externalID); + } else if (rarity == Rarity.Legendary) { + legendary.push(externalID); + } else if (rarity == Rarity.Mythic) { + mythic.push(externalID); + } else { + require(false); + } + } + } + + function getProto(uint16 id) public view returns( + bool exists, uint8 god, uint8 season, uint8 cardType, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe + ) { + ProtoCard memory proto = protos[id]; + return ( + proto.exists, + proto.god, + proto.season, + proto.cardType, + proto.rarity, + proto.mana, + proto.attack, + proto.health, + proto.tribe + ); + } + + function getRandomCard(Rarity rarity, uint16 random) public view returns (uint16) { + // modulo bias is fine - creates rarity tiers etc + // will obviously revert is there are no cards of that type: this is expected - should never happen + if (rarity == Rarity.Common) { + return common[random % common.length]; + } else if (rarity == Rarity.Rare) { + return rare[random % rare.length]; + } else if (rarity == Rarity.Epic) { + return epic[random % epic.length]; + } else if (rarity == Rarity.Legendary) { + return legendary[random % legendary.length]; + } else if (rarity == Rarity.Mythic) { + // make sure a mythic is available + uint16 id; + uint64 limit; + bool set; + for (uint i = 0; i < mythic.length; i++) { + id = mythic[(random + i) % mythic.length]; + (limit, set) = getLimit(id); + if (set && limit > 0){ + return id; + } + } + // if not, they get a legendary :( + return legendary[random % legendary.length]; + } + require(false); + return 0; + } + + // can never adjust tradable cards + // each season gets a 'balancing beta' + // totally immutable: season, rarity + function replaceProto( + uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe + ) public onlyGovernor { + ProtoCard memory pc = protos[index]; + require(!seasonTradable[pc.season]); + protos[index] = ProtoCard({ + exists: true, + god: god, + season: pc.season, + cardType: cardType, + rarity: pc.rarity, + mana: mana, + attack: attack, + health: health, + tribe: tribe + }); + } + +} + +contract ERC721Receiver { + /** + * @dev Magic value to be returned upon successful reception of an NFT + * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, + * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` + */ + bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; + + /** + * @notice Handle the receipt of an NFT + * @dev The ERC721 smart contract calls this function on the recipient + * after a `safetransfer`. This function MAY throw to revert and reject the + * transfer. Return of other than the magic value MUST result in the + * transaction being reverted. + * Note: the contract address is always the message sender. + * @param _operator The address which called `safeTransferFrom` function + * @param _from The address which previously owned the token + * @param _tokenId The NFT identifier which is being transfered + * @param _data Additional data with no specified format + * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` + */ + function onERC721Received( + address _operator, + address _from, + uint256 _tokenId, + bytes memory _data + ) + public + returns(bytes4); +} + +library AddressUtils { + + /** + * Returns whether the target address is a contract + * @dev This function will return false if invoked during the constructor of a contract, + * as the code is not actually created until after the constructor finishes. + * @param addr address to check + * @return whether the target address is a contract + */ + function isContract1(address addr) internal view returns (bool) { + uint256 size; + // XXX Currently there is no better way to check if there is a contract in an address + // than to check the size of the code at that address. + // See https://ethereum.stackexchange.com/a/14016/36603 + // for more details about how this works. + // TODO Check this again before the Serenity release, because all addresses will be + // contracts then. + // solium-disable-next-line security/no-inline-assembly + assembly { size := extcodesize(addr) } + return size > 0; + } + +} + +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting 'a' not being zero, but the + // benefit is lost if 'b' is also tested. + // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + // uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract ERC721BasicToken is CardProto, SupportsInterfaceWithLookup, ERC721Basic { + + bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd; + /* + * 0x80ac58cd === + * bytes4(keccak256('balanceOf(address)')) ^ + * bytes4(keccak256('ownerOf(uint256)')) ^ + * bytes4(keccak256('approve(address,uint256)')) ^ + * bytes4(keccak256('getApproved(uint256)')) ^ + * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ + * bytes4(keccak256('isApprovedForAll(address,address)')) ^ + * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ + * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ + * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) + */ + + bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79; + /* + * 0x4f558e79 === + * bytes4(keccak256('exists(uint256)')) + */ + + using SafeMath for uint256; + using AddressUtils for address; + + // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` + // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` + bytes4 private constant ERC721_RECEIVED = 0x150b7a02; + + // Mapping from token ID to owner + mapping (uint256 => address) internal tokenOwner; + + // Mapping from token ID to approved address + mapping (uint256 => address) internal tokenApprovals; + + // Mapping from owner to number of owned token + // mapping (address => uint256) internal ownedTokensCount; + + // Mapping from owner to operator approvals + mapping (address => mapping (address => bool)) internal operatorApprovals; + + /** + * @dev Guarantees msg.sender is owner of the given token + * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender + */ + modifier onlyOwnerOf(uint256 _tokenId) { + require(ownerOf(_tokenId) == msg.sender); + _; + } + + /** + * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator + * @param _tokenId uint256 ID of the token to validate + */ + modifier canTransfer(uint256 _tokenId) { + require(isApprovedOrOwner(msg.sender, _tokenId)); + _; + } + + constructor() + public + { + // register the supported interfaces to conform to ERC721 via ERC165 + _registerInterface(InterfaceId_ERC721); + _registerInterface(InterfaceId_ERC721Exists); + } + + /** + * @dev Gets the balance of the specified address + * @param _owner address to query the balance of + * @return uint256 representing the amount owned by the passed address + */ + function balanceOf(address _owner) public view returns (uint256); + + /** + * @dev Gets the owner of the specified token ID + * @param _tokenId uint256 ID of the token to query the owner of + * @return owner address currently marked as the owner of the given token ID + */ + function ownerOf(uint256 _tokenId) public view returns (address) { + address owner = tokenOwner[_tokenId]; + require(owner != address(0)); + return owner; + } + + /** + * @dev Returns whether the specified token exists + * @param _tokenId uint256 ID of the token to query the existence of + * @return whether the token exists + */ + function exists(uint256 _tokenId) public view returns (bool) { + address owner = tokenOwner[_tokenId]; + return owner != address(0); + } + + /** + * @dev Approves another address to transfer the given token ID + * The zero address indicates there is no approved address. + * There can only be one approved address per token at a given time. + * Can only be called by the token owner or an approved operator. + * @param _to address to be approved for the given token ID + * @param _tokenId uint256 ID of the token to be approved + */ + function approve(address _to, uint256 _tokenId) public { + address owner = ownerOf(_tokenId); + require(_to != owner); + require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); + + tokenApprovals[_tokenId] = _to; + emit Approval(owner, _to, _tokenId); + } + + /** + * @dev Gets the approved address for a token ID, or zero if no address set + * @param _tokenId uint256 ID of the token to query the approval of + * @return address currently approved for the given token ID + */ + function getApproved(uint256 _tokenId) public view returns (address) { + return tokenApprovals[_tokenId]; + } + + /** + * @dev Sets or unsets the approval of a given operator + * An operator is allowed to transfer all tokens of the sender on their behalf + * @param _to operator address to set the approval + * @param _approved representing the status of the approval to be set + */ + function setApprovalForAll(address _to, bool _approved) public { + require(_to != msg.sender); + operatorApprovals[msg.sender][_to] = _approved; + emit ApprovalForAll(msg.sender, _to, _approved); + } + + /** + * @dev Tells whether an operator is approved by a given owner + * @param _owner owner address which you want to query the approval of + * @param _operator operator address which you want to query the approval of + * @return bool whether the given operator is approved by the given owner + */ + function isApprovedForAll( + address _owner, + address _operator + ) + public + view + returns (bool) + { + return operatorApprovals[_owner][_operator]; + } + + /** + * @dev Transfers the ownership of a given token ID to another address + * Usage of this method is discouraged, use `safeTransferFrom` whenever possible + * Requires the msg sender to be the owner, approved, or operator + * @param _from current owner of the token + * @param _to address to receive the ownership of the given token ID + * @param _tokenId uint256 ID of the token to be transferred + */ + function transferFrom( + address _from, + address _to, + uint256 _tokenId + ) + public + canTransfer(_tokenId) + { + require(_from != address(0)); + require(_to != address(0)); + + clearApproval(_from, _tokenId); + removeTokenFrom(_from, _tokenId); + addTokenTo(_to, _tokenId); + + emit Transfer(_from, _to, _tokenId); + } + + /** + * @dev Safely transfers the ownership of a given token ID to another address + * If the target address is a contract, it must implement `onERC721Received`, + * which is called upon a safe transfer, and return the magic value + * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, + * the transfer is reverted. + * + * Requires the msg sender to be the owner, approved, or operator + * @param _from current owner of the token + * @param _to address to receive the ownership of the given token ID + * @param _tokenId uint256 ID of the token to be transferred + */ + function safeTransferFrom( + address _from, + address _to, + uint256 _tokenId + ) + public + canTransfer(_tokenId) + { + // solium-disable-next-line arg-overflow + safeTransferFrom(_from, _to, _tokenId, ""); + } + + /** + * @dev Safely transfers the ownership of a given token ID to another address + * If the target address is a contract, it must implement `onERC721Received`, + * which is called upon a safe transfer, and return the magic value + * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, + * the transfer is reverted. + * Requires the msg sender to be the owner, approved, or operator + * @param _from current owner of the token + * @param _to address to receive the ownership of the given token ID + * @param _tokenId uint256 ID of the token to be transferred + * @param _data bytes data to send along with a safe transfer check + */ + function safeTransferFrom( + address _from, + address _to, + uint256 _tokenId, + bytes memory _data + ) + public + canTransfer(_tokenId) + { + transferFrom(_from, _to, _tokenId); + // solium-disable-next-line arg-overflow + require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); + } + + /** + * @dev Returns whether the given spender can transfer a given token ID + * @param _spender address of the spender to query + * @param _tokenId uint256 ID of the token to be transferred + * @return bool whether the msg.sender is approved for the given token ID, + * is an operator of the owner, or is the owner of the token + */ + function isApprovedOrOwner( + address _spender, + uint256 _tokenId + ) + internal + view + returns (bool) + { + address owner = ownerOf(_tokenId); + // Disable solium check because of + // https://github.com/duaraghav8/Solium/issues/175 + // solium-disable-next-line operator-whitespace + return ( + _spender == owner || + getApproved(_tokenId) == _spender || + isApprovedForAll(owner, _spender) + ); + } + + /** + * @dev Internal function to clear current approval of a given token ID + * Reverts if the given address is not indeed the owner of the token + * @param _owner owner of the token + * @param _tokenId uint256 ID of the token to be transferred + */ + function clearApproval(address _owner, uint256 _tokenId) internal { + require(ownerOf(_tokenId) == _owner); + if (tokenApprovals[_tokenId] != address(0)) { + tokenApprovals[_tokenId] = address(0); + } + } + + /** + * @dev Internal function to mint a new token + * Reverts if the given token ID already exists + * @param _to The address that will own the minted token + * @param _tokenId uint256 ID of the token to be minted by the msg.sender + */ + function _mint(address _to, uint256 _tokenId) internal { + require(_to != address(0)); + addNewTokenTo(_to, _tokenId); + emit Transfer(address(0), _to, _tokenId); + } + + + /** + * @dev Internal function to burn a specific token + * Reverts if the token does not exist + * @param _tokenId uint256 ID of the token being burned by the msg.sender + */ + function _burn(address _owner, uint256 _tokenId) internal { + clearApproval(_owner, _tokenId); + removeTokenFrom(_owner, _tokenId); + emit Transfer(_owner, address(0), _tokenId); + } + + function addNewTokenTo(address _to, uint256 _tokenId) internal { + require(tokenOwner[_tokenId] == address(0)); + tokenOwner[_tokenId] = _to; + } + + /** + * @dev Internal function to add a token ID to the list of a given address + * @param _to address representing the new owner of the given token ID + * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address + */ + function addTokenTo(address _to, uint256 _tokenId) internal { + require(tokenOwner[_tokenId] == address(0)); + tokenOwner[_tokenId] = _to; + // ownedTokensCount[_to] = ownedTokensCount[_to].add(1); + } + + /** + * @dev Internal function to remove a token ID from the list of a given address + * @param _from address representing the previous owner of the given token ID + * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address + */ + function removeTokenFrom(address _from, uint256 _tokenId) internal { + require(ownerOf(_tokenId) == _from); + // ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); + tokenOwner[_tokenId] = address(0); + } + + /** + * @dev Internal function to invoke `onERC721Received` on a target address + * The call is not executed if the target address is not a contract + * @param _from address representing the previous owner of the given token ID + * @param _to target address that will receive the tokens + * @param _tokenId uint256 ID of the token to be transferred + * @param _data bytes optional data to send along with the call + * @return whether the call correctly returned the expected magic value + */ + function checkAndCallSafeTransfer( + address _from, + address _to, + uint256 _tokenId, + bytes memory _data + ) + internal + returns (bool) + { + if (!_to.isContract1()) { + return true; + } + bytes4 retval = ERC721Receiver(_to).onERC721Received( + msg.sender, _from, _tokenId, _data); + return (retval == ERC721_RECEIVED); + } + +} + + + +contract ERC721Enumerable is ERC721Basic { + function totalSupply() public view returns (uint256); + function tokenOfOwnerByIndex( + address _owner, + uint256 _index + ) + public + view + returns (uint256 _tokenId); + + function tokenByIndex(uint256 _index) public view returns (uint256); +} + +contract ERC721Metadata is ERC721Basic { + function name() external view returns (string memory _name); + function symbol() external view returns (string memory _symbol); + function tokenURI(uint256 _tokenId) public view returns (string memory); +} + +contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { + +} + + + + +library Strings { + + // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol + function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory ) { + bytes memory _ba = bytes(_a); + bytes memory _bb = bytes(_b); + bytes memory _bc = bytes(_c); + bytes memory _bd = bytes(_d); + bytes memory _be = bytes(_e); + string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); + bytes memory babcde = bytes(abcde); + uint k = 0; + for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; + for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; + for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; + for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; + for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; + return string(babcde); + } + + function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory ) { + return strConcat(_a, _b, _c, _d, ""); + } + + function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory ) { + return strConcat(_a, _b, _c, "", ""); + } + + function strConcat(string memory _a, string memory _b) internal pure returns (string memory ) { + return strConcat(_a, _b, "", "", ""); + } + + function uint2str(uint i) internal pure returns (string memory ) { + if (i == 0) return "0"; + uint j = i; + uint len; + while (j != 0){ + len++; + j /= 10; + } + bytes memory bstr = new bytes(len); + uint k = len - 1; + while (i != 0){ + bstr[k--] = byte(uint8(48 + i % 10)); + i /= 10; + } + return string(bstr); + } +} + +contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 { + + using Strings for string; + + bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63; + /** + * 0x780e9d63 === + * bytes4(keccak256('totalSupply()')) ^ + * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ + * bytes4(keccak256('tokenByIndex(uint256)')) + */ + + bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; + /** + * 0x5b5e139f === + * bytes4(keccak256('name()')) ^ + * bytes4(keccak256('symbol()')) ^ + * bytes4(keccak256('tokenURI(uint256)')) + */ + + /*** Constants ***/ + // Configure these for your own deployment + string public constant NAME = "Gods Unchained"; + string public constant SYMBOL = "GODS"; + string public tokenMetadataBaseURI = "https://api.godsunchained.com/card/"; + + // Mapping from owner to list of owned token IDs + // EDITED: limit to 2^40 (around 1T) + mapping(address => uint40[]) internal ownedTokens; + + uint32[] ownedTokensIndex; + + /** + * @dev Constructor function + */ + constructor() public { + + // register the supported interfaces to conform to ERC721 via ERC165 + _registerInterface(InterfaceId_ERC721Enumerable); + _registerInterface(InterfaceId_ERC721Metadata); + } + + /** + * @dev Gets the token name + * @return string representing the token name + */ + function name() external view returns (string memory) { + return NAME; + } + + /** + * @dev Gets the token symbol + * @return string representing the token symbol + */ + function symbol() external view returns (string memory) { + return SYMBOL; + } + + /** + * @dev Returns an URI for a given token ID + * Throws if the token ID does not exist. May return an empty string. + * @param _tokenId uint256 ID of the token to query + */ + function tokenURI(uint256 _tokenId) public view returns (string memory) { + return Strings.strConcat( + tokenMetadataBaseURI, + Strings.uint2str(_tokenId) + ); + } + + /** + * @dev Gets the token ID at a given index of the tokens list of the requested owner + * @param _owner address owning the tokens list to be accessed + * @param _index uint256 representing the index to be accessed of the requested tokens list + * @return uint256 token ID at the given index of the tokens list owned by the requested address + */ + function tokenOfOwnerByIndex( + address _owner, + uint256 _index + ) + public + view + returns (uint256) + { + require(_index < balanceOf(_owner)); + return ownedTokens[_owner][_index]; + } + + /** + * @dev Gets the total amount of tokens stored by the contract + * @return uint256 representing the total amount of tokens + */ + function totalSupply() public view returns (uint256) { + return cards.length; + } + + /** + * @dev Gets the token ID at a given index of all the tokens in this contract + * Reverts if the index is greater or equal to the total number of tokens + * @param _index uint256 representing the index to be accessed of the tokens list + * @return uint256 token ID at the given index of the tokens list + */ + function tokenByIndex(uint256 _index) public view returns (uint256) { + require(_index < totalSupply()); + return _index; + } + + /** + * @dev Internal function to add a token ID to the list of a given address + * @param _to address representing the new owner of the given token ID + * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address + */ + function addTokenTo(address _to, uint256 _tokenId) internal { + super.addTokenTo(_to, _tokenId); + uint256 length = ownedTokens[_to].length; + // EDITED: prevent overflow + require(length == uint32(length)); + ownedTokens[_to].push(uint40(_tokenId)); + + ownedTokensIndex[_tokenId] = uint32(length); + } + + // EDITED + // have to have in order to use array rather than mapping + function addNewTokenTo(address _to, uint256 _tokenId) internal { + super.addNewTokenTo(_to, _tokenId); + uint256 length = ownedTokens[_to].length; + // EDITED: prevent overflow + require(length == uint32(length)); + ownedTokens[_to].push(uint40(_tokenId)); + ownedTokensIndex.push(uint32(length)); + } + + /** + * @dev Internal function to remove a token ID from the list of a given address + * @param _from address representing the previous owner of the given token ID + * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address + */ + function removeTokenFrom(address _from, uint256 _tokenId) internal { + super.removeTokenFrom(_from, _tokenId); + + uint32 tokenIndex = ownedTokensIndex[_tokenId]; + uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); + uint40 lastToken = ownedTokens[_from][lastTokenIndex]; + + ownedTokens[_from][tokenIndex] = lastToken; + ownedTokens[_from][lastTokenIndex] = 0; + // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to + // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping + // the lastToken to the first position, and then dropping the element placed in the last position of the list + + ownedTokens[_from].length--; + ownedTokensIndex[_tokenId] = 0; + ownedTokensIndex[lastToken] = tokenIndex; + } + + /** + * @dev Gets the balance of the specified address - overrriden from previous to save gas + * @param _owner address to query the balance of + * @return uint256 representing the amount owned by the passed address + */ + function balanceOf(address _owner) public view returns (uint256) { + return ownedTokens[_owner].length; + } + +} + +contract CardOwnershipTwo is ERC721Token { + + uint public burnCount; + + function getActiveCards() public view returns (uint) { + return totalSupply() - burnCount; + } + + /** + * @param to : the address to which the card will be transferred + * @param id : the id of the card to be transferred + */ + function transfer(address to, uint id) public payable onlyOwnerOf(id) { + require(isTradable(cards[id].proto)); + require(to != address(0)); + + _transfer(msg.sender, to, id); + } + + function _transfer(address from, address to, uint id) internal { + + clearApproval(from, id); + + removeTokenFrom(from, id); + + addTokenTo(to, id); + + emit Transfer(from, to, id); + } + + /** + * @param to : the address to which the cards will be transferred + * @param ids : the ids of the cards to be transferred + */ + function transferAll(address to, uint[] memory ids) public payable { + for (uint i = 0; i < ids.length; i++) { + transfer(to, ids[i]); + } + } + + /** + * @param proposed : the claimed owner of the cards + * @param ids : the ids of the cards to check + * @return whether proposed owns all of the cards + */ + function ownsAll(address proposed, uint[] memory ids) public view returns (bool) { + require(ids.length > 0); + for (uint i = 0; i < ids.length; i++) { + if (!owns(proposed, ids[i])) { + return false; + } + } + return true; + } + + /** + * @param proposed : the claimed owner of the card + * @param id : the id of the card to check + * @return whether proposed owns the card + */ + function owns(address proposed, uint id) public view returns (bool) { + return ownerOf(id) == proposed; + } + + function burn(uint id) public onlyOwnerOf(id) { + burnCount++; + _burn(msg.sender, id); + } + + /** + * @param ids : the indices of the tokens to burn + */ + function burnAll(uint[] memory ids) public { + for (uint i = 0; i < ids.length; i++){ + burn(ids[i]); + } + } + + /** + * @param to : the address to approve for transfer + * @param id : the index of the card to be approved + */ + function approve(address to, uint id) public { + require(isTradable(cards[id].proto)); + super.approve(to, id); + } + + /** + * @param to : the address to approve for transfer + * @param ids : the indices of the cards to be approved + */ + function approveAll(address to, uint[] memory ids) public { + for (uint i = 0; i < ids.length; i++) { + approve(to, ids[i]); + } + } + + /** + * @param to : the address to which the token should be transferred + * @param id : the index of the token to transfer + */ + function transferFrom(address from, address to, uint id) public { + require(isTradable(cards[id].proto)); + super.transferFrom(from, to, id); + } + + /** + * @param to : the address to which the tokens should be transferred + * @param ids : the indices of the tokens to transfer + */ + function transferAllFrom(address from, address to, uint[] memory ids) public { + for (uint i = 0; i < ids.length; i++) { + transferFrom(from, to, ids[i]); + } + } + + /** + * @return the number of cards which have been burned + */ + function getBurnCount() public view returns (uint) { + return burnCount; + } + +} + +contract CardIntegrationTwo is CardOwnershipTwo { + + address[] public packs; + + event CardCreated(uint indexed id, uint16 proto, uint16 purity, address owner); + + function addPack(address approved) public onlyGovernor { + packs.push(approved); + } + + modifier onlyApprovedPacks { + require(_isApprovedPack()); + _; + } + + function _isApprovedPack() private view returns (bool) { + for (uint i = 0; i < packs.length; i++) { + if (msg.sender == address(packs[i])) { + return true; + } + } + return false; + } + + function createCard(address owner, uint16 proto, uint16 purity) public whenNotPaused onlyApprovedPacks returns (uint) { + ProtoCard memory card = protos[proto]; + require(card.season == currentSeason); + if (card.rarity == Rarity.Mythic) { + uint64 limit; + bool exists; + (limit, exists) = getLimit(proto); + require(!exists || limit > 0); + limits[proto].limit--; + } + return _createCard(owner, proto, purity); + } + + function _createCard(address owner, uint16 proto, uint16 purity) internal returns (uint) { + Card memory card = Card({ + proto: proto, + purity: purity + }); + + uint id = cards.push(card) - 1; + + _mint(owner, id); + + emit CardCreated(id, proto, purity, owner); + + return id; + } + + /*function combineCards(uint[] ids) public whenNotPaused { + require(ids.length == 5); + require(ownsAll(msg.sender, ids)); + Card memory first = cards[ids[0]]; + uint16 proto = first.proto; + uint8 shine = _getShine(first.purity); + require(shine < shineLimit); + uint16 puritySum = first.purity - (shine * 1000); + burn(ids[0]); + for (uint i = 1; i < ids.length; i++) { + Card memory next = cards[ids[i]]; + require(next.proto == proto); + require(_getShine(next.purity) == shine); + puritySum += (next.purity - (shine * 1000)); + burn(ids[i]); + } + uint16 newPurity = uint16(((shine + 1) * 1000) + (puritySum / ids.length)); + _createCard(msg.sender, proto, newPurity); + }*/ + + + // PURITY NOTES + // currently, we only + // however, to protect rarity, you'll never be abl + // this is enforced by the restriction in the create-card function + // no cards above this point can be found in packs + + + +} + +contract PreviousInterface { + + function ownerOf(uint id) public view returns (address); + + function getCard(uint id) public view returns (uint16, uint16); + + function totalSupply() public view returns (uint); + + function burnCount() public view returns (uint); + +} + +contract CardMigration is CardIntegrationTwo { + + constructor(PreviousInterface previous) public { + old = previous; + } + + // use interface to lower deployment cost + PreviousInterface old; + + mapping(uint => bool) public migrated; + + function migrate(uint id) public { + + require(!migrated[id]); + + migrated[id] = true; + + address owner = old.ownerOf(id); + + uint16 proto; + uint16 purity; + + (proto, purity) = old.getCard(id); + + _createCard(owner, proto, purity); + } + + function migrateAll(uint[] memory ids) public { + + for (uint i = 0; i < ids.length; i++){ + migrate(ids[i]); + } + + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario008.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario008.sol new file mode 100644 index 00000000000..251b41bc6a2 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractScenario008.sol @@ -0,0 +1,2050 @@ +//pragma solidity ^0.4.11; + + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + if (newOwner != address(0)) { + owner = newOwner; + } + } + +} + + + + +/// @title A facet of KittyCore that manages special access privileges. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. +contract KittyAccessControl { + // This facet controls access control for CryptoKitties. There are four roles managed here: + // + // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart + // contracts. It is also the only role that can unpause the smart contract. It is initially + // set to the address that created the smart contract in the KittyCore constructor. + // + // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. + // + // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. + // + // It should be noted that these roles are distinct without overlap in their access abilities, the + // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any + // address to any role, the CEO address itself doesn't have the ability to act in those roles. This + // restriction is intentional so that we aren't tempted to use the CEO address frequently out of + // convenience. The less we use an address, the less likely it is that we somehow compromise the + // account. + + /// @dev Emited when contract is upgraded - See README.md for updgrade plan + event ContractUpgrade(address newContract); + + // The addresses of the accounts (or contracts) that can execute actions within each roles. + address public ceoAddress; + address payable public cfoAddress; + address public cooAddress; + + // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked + bool public paused = false; + + /// @dev Access modifier for CEO-only functionality + modifier onlyCEO() { + require(msg.sender == ceoAddress); + _; + } + + /// @dev Access modifier for CFO-only functionality + modifier onlyCFO() { + require(msg.sender == cfoAddress); + _; + } + + /// @dev Access modifier for COO-only functionality + modifier onlyCOO() { + require(msg.sender == cooAddress); + _; + } + + modifier onlyCLevel() { + require( + msg.sender == cooAddress || + msg.sender == ceoAddress || + msg.sender == cfoAddress + ); + _; + } + + /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. + /// @param _newCEO The address of the new CEO + function setCEO(address _newCEO) external onlyCEO { + require(_newCEO != address(0)); + + ceoAddress = _newCEO; + } + + /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. + /// @param _newCFO The address of the new CFO + function setCFO(address payable _newCFO) external onlyCEO { + require(_newCFO != address(0)); + + cfoAddress = _newCFO; + } + + /// @dev Assigns a new address to act as the COO. Only available to the current CEO. + /// @param _newCOO The address of the new COO + function setCOO(address _newCOO) external onlyCEO { + require(_newCOO != address(0)); + + cooAddress = _newCOO; + } + + /*** Pausable functionality adapted from OpenZeppelin ***/ + + /// @dev Modifier to allow actions only when the contract IS NOT paused + modifier whenNotPaused() { + require(!paused); + _; + } + + /// @dev Modifier to allow actions only when the contract IS paused + modifier whenPaused { + require(paused); + _; + } + + /// @dev Called by any "C-level" role to pause the contract. Used only when + /// a bug or exploit is detected and we need to limit damage. + function pause() external onlyCLevel whenNotPaused { + paused = true; + } + + /// @dev Unpauses the smart contract. Can only be called by the CEO, since + /// one reason we may pause the contract is when CFO or COO accounts are + /// compromised. + /// @notice This is public rather than external so it can be called by + /// derived contracts. + function unpause() public onlyCEO whenPaused { + // can't unpause if contract was upgraded + paused = false; + } +} + + + + +/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. +contract KittyBase is KittyAccessControl { + /*** EVENTS ***/ + + /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously + /// includes any time a cat is created through the giveBirth method, but it is also called + /// when a new gen0 cat is created. + event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); + + /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten + /// ownership is assigned, including births. + event Transfer(address from, address to, uint256 tokenId); + + /*** DATA TYPES ***/ + + /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy + /// of this structure, so great care was taken to ensure that it fits neatly into + /// exactly two 256-bit words. Note that the order of the members in this structure + /// is important because of the byte-packing rules used by Ethereum. + /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html + struct Kitty { + // The Kitty's genetic code is packed into these 256-bits, the format is + // sooper-sekret! A cat's genes never change. + uint256 genes; + + // The timestamp from the block when this cat came into existence. + uint64 birthTime; + + // The minimum timestamp after which this cat can engage in breeding + // activities again. This same timestamp is used for the pregnancy + // timer (for matrons) as well as the siring cooldown. + uint64 cooldownEndBlock; + + // The ID of the parents of this kitty, set to 0 for gen0 cats. + // Note that using 32-bit unsigned integers limits us to a "mere" + // 4 billion cats. This number might seem small until you realize + // that Ethereum currently has a limit of about 500 million + // transactions per year! So, this definitely won't be a problem + // for several years (even as Ethereum learns to scale). + uint32 matronId; + uint32 sireId; + + // Set to the ID of the sire cat for matrons that are pregnant, + // zero otherwise. A non-zero value here is how we know a cat + // is pregnant. Used to retrieve the genetic material for the new + // kitten when the birth transpires. + uint32 siringWithId; + + // Set to the index in the cooldown array (see below) that represents + // the current cooldown duration for this Kitty. This starts at zero + // for gen0 cats, and is initialized to floor(generation/2) for others. + // Incremented by one for each successful breeding action, regardless + // of whether this cat is acting as matron or sire. + uint16 cooldownIndex; + + // The "generation number" of this cat. Cats minted by the CK contract + // for sale are called "gen0" and have a generation number of 0. The + // generation number of all other cats is the larger of the two generation + // numbers of their parents, plus one. + // (i.e. max(matron.generation, sire.generation) + 1) + uint16 generation; + } + + /*** CONSTANTS ***/ + + /// @dev A lookup table indicating the cooldown duration after any successful + /// breeding action, called "pregnancy time" for matrons and "siring cooldown" + /// for sires. Designed such that the cooldown roughly doubles each time a cat + /// is bred, encouraging owners not to just keep breeding the same cat over + /// and over again. Caps out at one week (a cat can breed an unbounded number + /// of times, and the maximum cooldown is always seven days). + uint32[14] public cooldowns = [ + uint32(1 minutes), + uint32(2 minutes), + uint32(5 minutes), + uint32(10 minutes), + uint32(30 minutes), + uint32(1 hours), + uint32(2 hours), + uint32(4 hours), + uint32(8 hours), + uint32(16 hours), + uint32(1 days), + uint32(2 days), + uint32(4 days), + uint32(7 days) + ]; + + // An approximation of currently how many seconds are in between blocks. + uint256 public secondsPerBlock = 15; + + /*** STORAGE ***/ + + /// @dev An array containing the Kitty struct for all Kitties in existence. The ID + /// of each cat is actually an index into this array. Note that ID 0 is a negacat, + /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre + /// creature that is both matron and sire... to itself! Has an invalid genetic code. + /// In other words, cat ID 0 is invalid... ;-) + Kitty[] kitties; + + /// @dev A mapping from cat IDs to the address that owns them. All cats have + /// some valid owner address, even gen0 cats are created with a non-zero owner. + mapping (uint256 => address) public kittyIndexToOwner; + + // @dev A mapping from owner address to count of tokens that address owns. + // Used internally inside balanceOf() to resolve ownership count. + mapping (address => uint256) ownershipTokenCount; + + /// @dev A mapping from KittyIDs to an address that has been approved to call + /// transferFrom(). Each Kitty can only have one approved address for transfer + /// at any time. A zero value means no approval is outstanding. + mapping (uint256 => address) public kittyIndexToApproved; + + /// @dev A mapping from KittyIDs to an address that has been approved to use + /// this Kitty for siring via breedWith(). Each Kitty can only have one approved + /// address for siring at any time. A zero value means no approval is outstanding. + mapping (uint256 => address) public sireAllowedToAddress; + + /// @dev The address of the ClockAuction contract that handles sales of Kitties. This + /// same contract handles both peer-to-peer sales as well as the gen0 sales which are + /// initiated every 15 minutes. + SaleClockAuction public saleAuction; + + /// @dev The address of a custom ClockAuction subclassed contract that handles siring + /// auctions. Needs to be separate from saleAuction because the actions taken on success + /// after a sales and siring auction are quite different. + SiringClockAuction public siringAuction; + + /// @dev Assigns ownership of a specific Kitty to an address. + function _transfer(address _from, address _to, uint256 _tokenId) internal { + // Since the number of kittens is capped to 2^32 we can't overflow this + ownershipTokenCount[_to]++; + // transfer ownership + kittyIndexToOwner[_tokenId] = _to; + // When creating new kittens _from is 0x0, but we can't account that address. + if (_from != address(0)) { + ownershipTokenCount[_from]--; + // once the kitten is transferred also clear sire allowances + delete sireAllowedToAddress[_tokenId]; + // clear any previously approved ownership exchange + delete kittyIndexToApproved[_tokenId]; + } + // Emit the transfer event. + emit Transfer(_from, _to, _tokenId); + } + + /// @dev An internal method that creates a new kitty and stores it. This + /// method doesn't do any checking and should only be called when the + /// input data is known to be valid. Will generate both a Birth event + /// and a Transfer event. + /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) + /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) + /// @param _generation The generation number of this cat, must be computed by caller. + /// @param _genes The kitty's genetic code. + /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) + function _createKitty( + uint256 _matronId, + uint256 _sireId, + uint256 _generation, + uint256 _genes, + address _owner + ) + internal + returns (uint) + { + // These requires are not strictly necessary, our calling code should make + // sure that these conditions are never broken. However! _createKitty() is already + // an expensive call (for storage), and it doesn't hurt to be especially careful + // to ensure our data structures are always valid. + require(_matronId == uint256(uint32(_matronId))); + require(_sireId == uint256(uint32(_sireId))); + require(_generation == uint256(uint16(_generation))); + + // New kitty starts with the same cooldown as parent gen/2 + uint16 cooldownIndex = uint16(_generation / 2); + if (cooldownIndex > 13) { + cooldownIndex = 13; + } + + Kitty memory _kitty = Kitty({ + genes: _genes, + birthTime: uint64(now), + cooldownEndBlock: 0, + matronId: uint32(_matronId), + sireId: uint32(_sireId), + siringWithId: 0, + cooldownIndex: cooldownIndex, + generation: uint16(_generation) + }); + uint256 newKittenId = kitties.push(_kitty) - 1; + + // It's probably never going to happen, 4 billion cats is A LOT, but + // let's just be 100% sure we never let this happen. + require(newKittenId == uint256(uint32(newKittenId))); + + // emit the birth event + emit Birth( + _owner, + newKittenId, + uint256(_kitty.matronId), + uint256(_kitty.sireId), + _kitty.genes + ); + + // This will assign ownership, and also emit the Transfer event as + // per ERC721 draft + _transfer(address(0), _owner, newKittenId); + + return newKittenId; + } + + // Any C-level can fix how many seconds per blocks are currently observed. + function setSecondsPerBlock(uint256 secs) external onlyCLevel { + require(secs < cooldowns[0]); + secondsPerBlock = secs; + } +} + + +/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens +/// @author Dieter Shirley (https://github.com/dete) +contract ERC721 { + // Required methods + function totalSupply() public view returns (uint256 total); + function balanceOf(address _owner) public view returns (uint256 balance); + function ownerOf(uint256 _tokenId) external view returns (address owner); + function approve(address _to, uint256 _tokenId) external; + function transfer(address _to, uint256 _tokenId) external; + function transferFrom(address _from, address _to, uint256 _tokenId) external; + + // Events + event Transfer(address from, address to, uint256 tokenId); + event Approval(address owner, address approved, uint256 tokenId); + + // Optional + // function name() public view returns (string name); + // function symbol() public view returns (string symbol); + // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); + // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); + + // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) + function supportsInterface(bytes4 _interfaceID) external view returns (bool); +} + + +/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 +/// See the KittyCore contract documentation to understand how the various contract facets are arranged. +contract KittyOwnership is ERC721, KittyBase { + + /// @notice Name and symbol of the non fungible token, as defined in ERC721. + string public constant name = "CryptoKitties"; + string public constant symbol = "CK"; + + // The contract that will return kitty metadata + ERC721Metadata public erc721Metadata; + + bytes4 constant InterfaceSignature_ERC165 = + bytes4(keccak256('supportsInterface(bytes4)')); + + bytes4 constant InterfaceSignature_ERC721 = + bytes4(keccak256('name()')) ^ + bytes4(keccak256('symbol()')) ^ + bytes4(keccak256('totalSupply()')) ^ + bytes4(keccak256('balanceOf(address)')) ^ + bytes4(keccak256('ownerOf(uint256)')) ^ + bytes4(keccak256('approve(address,uint256)')) ^ + bytes4(keccak256('transfer(address,uint256)')) ^ + bytes4(keccak256('transferFrom(address,address,uint256)')) ^ + bytes4(keccak256('tokensOfOwner(address)')) ^ + bytes4(keccak256('tokenMetadata(uint256,string)')); + + /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). + /// Returns true for any standardized interfaces implemented by this contract. We implement + /// ERC-165 (obviously!) and ERC-721. + function supportsInterface(bytes4 _interfaceID) external view returns (bool) + { + // DEBUG ONLY + //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); + + return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); + } + + /// @dev Set the address of the sibling contract that tracks metadata. + /// CEO only. + function setMetadataAddress(address _contractAddress) public onlyCEO { + erc721Metadata = ERC721Metadata(_contractAddress); + } + + // Internal utility functions: These functions all assume that their input arguments + // are valid. We leave it to public methods to sanitize their inputs and follow + // the required logic. + + /// @dev Checks if a given address is the current owner of a particular Kitty. + /// @param _claimant the address we are validating against. + /// @param _tokenId kitten id, only valid when > 0 + function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { + return kittyIndexToOwner[_tokenId] == _claimant; + } + + /// @dev Checks if a given address currently has transferApproval for a particular Kitty. + /// @param _claimant the address we are confirming kitten is approved for. + /// @param _tokenId kitten id, only valid when > 0 + function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { + return kittyIndexToApproved[_tokenId] == _claimant; + } + + /// @dev Marks an address as being approved for transferFrom(), overwriting any previous + /// approval. Setting _approved to address(0) clears all transfer approval. + /// NOTE: _approve() does NOT send the Approval event. This is intentional because + /// _approve() and transferFrom() are used together for putting Kitties on auction, and + /// there is no value in spamming the log with Approval events in that case. + function _approve(uint256 _tokenId, address _approved) internal { + kittyIndexToApproved[_tokenId] = _approved; + } + + /// @notice Returns the number of Kitties owned by a specific address. + /// @param _owner The owner address to check. + /// @dev Required for ERC-721 compliance + function balanceOf(address _owner) public view returns (uint256 count) { + return ownershipTokenCount[_owner]; + } + + /// @notice Transfers a Kitty to another address. If transferring to a smart + /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or + /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. + /// @param _to The address of the recipient, can be a user or contract. + /// @param _tokenId The ID of the Kitty to transfer. + /// @dev Required for ERC-721 compliance. + function transfer( + address _to, + uint256 _tokenId + ) + external + whenNotPaused + { + // Safety check to prevent against an unexpected 0x0 default. + require(_to != address(0)); + // Disallow transfers to this contract to prevent accidental misuse. + // The contract should never own any kitties (except very briefly + // after a gen0 cat is created and before it goes on auction). + require(_to != address(this)); + // Disallow transfers to the auction contracts to prevent accidental + // misuse. Auction contracts should only take ownership of kitties + // through the allow + transferFrom flow. + require(_to != address(saleAuction)); + require(_to != address(siringAuction)); + + // You can only send your own cat. + require(_owns(msg.sender, _tokenId)); + + // Reassign ownership, clear pending approvals, emit Transfer event. + _transfer(msg.sender, _to, _tokenId); + } + + /// @notice Grant another address the right to transfer a specific Kitty via + /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. + /// @param _to The address to be granted transfer approval. Pass address(0) to + /// clear all approvals. + /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. + /// @dev Required for ERC-721 compliance. + function approve( + address _to, + uint256 _tokenId + ) + external + whenNotPaused + { + // Only an owner can grant transfer approval. + require(_owns(msg.sender, _tokenId)); + + // Register the approval (replacing any previous approval). + _approve(_tokenId, _to); + + // Emit approval event. + emit Approval(msg.sender, _to, _tokenId); + } + + /// @notice Transfer a Kitty owned by another address, for which the calling address + /// has previously been granted transfer approval by the owner. + /// @param _from The address that owns the Kitty to be transfered. + /// @param _to The address that should take ownership of the Kitty. Can be any address, + /// including the caller. + /// @param _tokenId The ID of the Kitty to be transferred. + /// @dev Required for ERC-721 compliance. + function transferFrom( + address _from, + address _to, + uint256 _tokenId + ) + external + whenNotPaused + { + // Safety check to prevent against an unexpected 0x0 default. + require(_to != address(0)); + // Disallow transfers to this contract to prevent accidental misuse. + // The contract should never own any kitties (except very briefly + // after a gen0 cat is created and before it goes on auction). + require(_to != address(this)); + // Check for approval and valid ownership + require(_approvedFor(msg.sender, _tokenId)); + require(_owns(_from, _tokenId)); + + // Reassign ownership (also clears pending approvals and emits Transfer event). + _transfer(_from, _to, _tokenId); + } + + /// @notice Returns the total number of Kitties currently in existence. + /// @dev Required for ERC-721 compliance. + function totalSupply() public view returns (uint) { + return kitties.length - 1; + } + + /// @notice Returns the address currently assigned ownership of a given Kitty. + /// @dev Required for ERC-721 compliance. + function ownerOf(uint256 _tokenId) + external + view + returns (address owner) + { + owner = kittyIndexToOwner[_tokenId]; + + require(owner != address(0)); + } + + /// @notice Returns a list of all Kitty IDs assigned to an address. + /// @param _owner The owner whose Kitties we are interested in. + /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly + /// expensive (it walks the entire Kitty array looking for cats belonging to owner), + /// but it also returns a dynamic array, which is only supported for web3 calls, and + /// not contract-to-contract calls. + function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { + uint256 tokenCount = balanceOf(_owner); + + if (tokenCount == 0) { + // Return an empty array + return new uint256[](0); + } else { + uint256[] memory result = new uint256[](tokenCount); + uint256 totalCats = totalSupply(); + uint256 resultIndex = 0; + + // We count on the fact that all cats have IDs starting at 1 and increasing + // sequentially up to the totalCat count. + uint256 catId; + + for (catId = 1; catId <= totalCats; catId++) { + if (kittyIndexToOwner[catId] == _owner) { + result[resultIndex] = catId; + resultIndex++; + } + } + + return result; + } + } + + /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) + /// This method is licenced under the Apache License. + /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol + function _memcpy(uint _dest, uint _src, uint _len) private view { + // Copy word-length chunks while possible + for(; _len >= 32; _len -= 32) { + assembly { + mstore(_dest, mload(_src)) + } + _dest += 32; + _src += 32; + } + + // Copy remaining bytes + uint256 mask = 256 ** (32 - _len) - 1; + assembly { + let srcpart := and(mload(_src), not(mask)) + let destpart := and(mload(_dest), mask) + mstore(_dest, or(destpart, srcpart)) + } + } + + /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) + /// This method is licenced under the Apache License. + /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol + function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { + string memory outputString = new string(_stringLength); + uint256 outputPtr; + uint256 bytesPtr; + + assembly { + outputPtr := add(outputString, 32) + bytesPtr := _rawBytes + } + + _memcpy(outputPtr, bytesPtr, _stringLength); + + return outputString; + } + + /// @notice Returns a URI pointing to a metadata package for this token conforming to + /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) + /// @param _tokenId The ID number of the Kitty whose metadata should be returned. + function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { + require( address(erc721Metadata) != address(0)); + bytes32[4] memory buffer; + uint256 count; + (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); + + return _toString(buffer, count); + } +} + + + + +/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. +contract KittyBreeding is KittyOwnership { + + /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy + /// timer begins for the matron. + event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); + + /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards + /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by + /// the COO role as the gas price changes. + uint256 public autoBirthFee = 2 sun; + + // Keeps track of number of pregnant kitties. + uint256 public pregnantKitties; + + /// @dev The address of the sibling contract that is used to implement the sooper-sekret + /// genetic combination algorithm. + GeneScienceInterface public geneScience; + + /// @dev Update the address of the genetic contract, can only be called by the CEO. + /// @param _address An address of a GeneScience contract instance to be used from this point forward. + function setGeneScienceAddress(address _address) external onlyCEO { + GeneScienceInterface candidateContract = GeneScienceInterface(_address); + + // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 + require(candidateContract.isGeneScience()); + + // Set the new contract address + geneScience = candidateContract; + } + + /// @dev Checks that a given kitten is able to breed. Requires that the + /// current cooldown is finished (for sires) and also checks that there is + /// no pending pregnancy. + function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { + // In addition to checking the cooldownEndBlock, we also need to check to see if + // the cat has a pending birth; there can be some period of time between the end + // of the pregnacy timer and the birth event. + return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); + } + + /// @dev Check if a sire has authorized breeding with this matron. True if both sire + /// and matron have the same owner, or if the sire has given siring permission to + /// the matron's owner (via approveSiring()). + function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { + address matronOwner = kittyIndexToOwner[_matronId]; + address sireOwner = kittyIndexToOwner[_sireId]; + + // Siring is okay if they have same owner, or if the matron's owner was given + // permission to breed with this sire. + return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); + } + + /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. + /// Also increments the cooldownIndex (unless it has hit the cap). + /// @param _kitten A reference to the Kitty in storage which needs its timer started. + function _triggerCooldown(Kitty storage _kitten) internal { + // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). + _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); + + // Increment the breeding count, clamping it at 13, which is the length of the + // cooldowns array. We could check the array size dynamically, but hard-coding + // this as a constant saves gas. Yay, Solidity! + if (_kitten.cooldownIndex < 13) { + _kitten.cooldownIndex += 1; + } + } + + /// @notice Grants approval to another user to sire with one of your Kitties. + /// @param _addr The address that will be able to sire with your Kitty. Set to + /// address(0) to clear all siring approvals for this Kitty. + /// @param _sireId A Kitty that you own that _addr will now be able to sire with. + function approveSiring(address _addr, uint256 _sireId) + external + whenNotPaused + { + require(_owns(msg.sender, _sireId)); + sireAllowedToAddress[_sireId] = _addr; + } + + /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only + /// be called by the COO address. (This fee is used to offset the gas cost incurred + /// by the autobirth daemon). + function setAutoBirthFee(uint256 val) external onlyCOO { + autoBirthFee = val; + } + + /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation + /// period has passed. + function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { + return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); + } + + /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or + /// in the middle of a siring cooldown). + /// @param _kittyId reference the id of the kitten, any user can inquire about it + function isReadyToBreed(uint256 _kittyId) + public + view + returns (bool) + { + require(_kittyId > 0); + Kitty storage kit = kitties[_kittyId]; + return _isReadyToBreed(kit); + } + + /// @dev Checks whether a kitty is currently pregnant. + /// @param _kittyId reference the id of the kitten, any user can inquire about it + function isPregnant(uint256 _kittyId) + public + view + returns (bool) + { + require(_kittyId > 0); + // A kitty is pregnant if and only if this field is set + return kitties[_kittyId].siringWithId != 0; + } + + /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT + /// check ownership permissions (that is up to the caller). + /// @param _matron A reference to the Kitty struct of the potential matron. + /// @param _matronId The matron's ID. + /// @param _sire A reference to the Kitty struct of the potential sire. + /// @param _sireId The sire's ID + function _isValidMatingPair( + Kitty storage _matron, + uint256 _matronId, + Kitty storage _sire, + uint256 _sireId + ) + private + view + returns(bool) + { + // A Kitty can't breed with itself! + if (_matronId == _sireId) { + return false; + } + + // Kitties can't breed with their parents. + if (_matron.matronId == _sireId || _matron.sireId == _sireId) { + return false; + } + if (_sire.matronId == _matronId || _sire.sireId == _matronId) { + return false; + } + + // We can short circuit the sibling check (below) if either cat is + // gen zero (has a matron ID of zero). + if (_sire.matronId == 0 || _matron.matronId == 0) { + return true; + } + + // Kitties can't breed with full or half siblings. + if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { + return false; + } + if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { + return false; + } + + // Everything seems cool! Let's get DTF. + return true; + } + + /// @dev Internal check to see if a given sire and matron are a valid mating pair for + /// breeding via auction (i.e. skips ownership and siring approval checks). + function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) + internal + view + returns (bool) + { + Kitty storage matron = kitties[_matronId]; + Kitty storage sire = kitties[_sireId]; + return _isValidMatingPair(matron, _matronId, sire, _sireId); + } + + /// @notice Checks to see if two cats can breed together, including checks for + /// ownership and siring approvals. Does NOT check that both cats are ready for + /// breeding (i.e. breedWith could still fail until the cooldowns are finished). + /// TODO: Shouldn't this check pregnancy and cooldowns?!? + /// @param _matronId The ID of the proposed matron. + /// @param _sireId The ID of the proposed sire. + function canBreedWith(uint256 _matronId, uint256 _sireId) + external + view + returns(bool) + { + require(_matronId > 0); + require(_sireId > 0); + Kitty storage matron = kitties[_matronId]; + Kitty storage sire = kitties[_sireId]; + return _isValidMatingPair(matron, _matronId, sire, _sireId) && + _isSiringPermitted(_sireId, _matronId); + } + + /// @dev Internal utility function to initiate breeding, assumes that all breeding + /// requirements have been checked. + function _breedWith(uint256 _matronId, uint256 _sireId) internal { + // Grab a reference to the Kitties from storage. + Kitty storage sire = kitties[_sireId]; + Kitty storage matron = kitties[_matronId]; + + // Mark the matron as pregnant, keeping track of who the sire is. + matron.siringWithId = uint32(_sireId); + + // Trigger the cooldown for both parents. + _triggerCooldown(sire); + _triggerCooldown(matron); + + // Clear siring permission for both parents. This may not be strictly necessary + // but it's likely to avoid confusion! + delete sireAllowedToAddress[_matronId]; + delete sireAllowedToAddress[_sireId]; + + // Every time a kitty gets pregnant, counter is incremented. + pregnantKitties++; + + // Emit the pregnancy event. + emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); + } + + /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you + /// have previously been given Siring approval. Will either make your cat pregnant, or will + /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() + /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) + /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) + function breedWithAuto(uint256 _matronId, uint256 _sireId) + external + payable + whenNotPaused + { + // Checks for payment. + require(msg.value >= autoBirthFee); + + // Caller must own the matron. + require(_owns(msg.sender, _matronId)); + + // Neither sire nor matron are allowed to be on auction during a normal + // breeding operation, but we don't need to check that explicitly. + // For matron: The caller of this function can't be the owner of the matron + // because the owner of a Kitty on auction is the auction house, and the + // auction house will never call breedWith(). + // For sire: Similarly, a sire on auction will be owned by the auction house + // and the act of transferring ownership will have cleared any oustanding + // siring approval. + // Thus we don't need to spend gas explicitly checking to see if either cat + // is on auction. + + // Check that matron and sire are both owned by caller, or that the sire + // has given siring permission to caller (i.e. matron's owner). + // Will fail for _sireId = 0 + require(_isSiringPermitted(_sireId, _matronId)); + + // Grab a reference to the potential matron + Kitty storage matron = kitties[_matronId]; + + // Make sure matron isn't pregnant, or in the middle of a siring cooldown + require(_isReadyToBreed(matron)); + + // Grab a reference to the potential sire + Kitty storage sire = kitties[_sireId]; + + // Make sure sire isn't pregnant, or in the middle of a siring cooldown + require(_isReadyToBreed(sire)); + + // Test that these cats are a valid mating pair. + require(_isValidMatingPair( + matron, + _matronId, + sire, + _sireId + )); + + // All checks passed, kitty gets pregnant! + _breedWith(_matronId, _sireId); + } + + /// @notice Have a pregnant Kitty give birth! + /// @param _matronId A Kitty ready to give birth. + /// @return The Kitty ID of the new kitten. + /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, + /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned + /// to the current owner of the matron. Upon successful completion, both the matron and the + /// new kitten will be ready to breed again. Note that anyone can call this function (if they + /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. + function giveBirth(uint256 _matronId) + external + whenNotPaused + returns(uint256) + { + // Grab a reference to the matron in storage. + Kitty storage matron = kitties[_matronId]; + + // Check that the matron is a valid cat. + require(matron.birthTime != 0); + + // Check that the matron is pregnant, and that its time has come! + require(_isReadyToGiveBirth(matron)); + + // Grab a reference to the sire in storage. + uint256 sireId = matron.siringWithId; + Kitty storage sire = kitties[sireId]; + + // Determine the higher generation number of the two parents + uint16 parentGen = matron.generation; + if (sire.generation > matron.generation) { + parentGen = sire.generation; + } + + // Call the sooper-sekret gene mixing operation. + uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); + + // Make the new kitten! + address owner = kittyIndexToOwner[_matronId]; + uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); + + // Clear the reference to sire from the matron (REQUIRED! Having siringWithId + // set is what marks a matron as being pregnant.) + delete matron.siringWithId; + + // Every time a kitty gives birth counter is decremented. + pregnantKitties--; + + // Send the balance fee to the person who made birth happen. + msg.sender.transfer(autoBirthFee); + + // return the new kitten's ID + return kittenId; + } +} + + + +/// @title Handles creating auctions for sale and siring of kitties. +/// This wrapper of ReverseAuction exists only so that users can create +/// auctions with only one transaction. +contract KittyAuction is KittyBreeding { + + // @notice The auction contract variables are defined in KittyBase to allow + // us to refer to them in KittyOwnership to prevent accidental transfers. + // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. + // `siringAuction` refers to the auction for siring rights of kitties. + + /// @dev Sets the reference to the sale auction. + /// @param _address - Address of sale contract. + function setSaleAuctionAddress(address _address) external onlyCEO { + SaleClockAuction candidateContract = SaleClockAuction(_address); + + // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 + require(candidateContract.isSaleClockAuction()); + + // Set the new contract address + saleAuction = candidateContract; + } + + /// @dev Sets the reference to the siring auction. + /// @param _address - Address of siring contract. + function setSiringAuctionAddress(address _address) external onlyCEO { + SiringClockAuction candidateContract = SiringClockAuction(_address); + + // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 + require(candidateContract.isSiringClockAuction()); + + // Set the new contract address + siringAuction = candidateContract; + } + + /// @dev Put a kitty up for auction. + /// Does some ownership trickery to create auctions in one tx. + function createSaleAuction( + uint256 _kittyId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration + ) + external + whenNotPaused + { + // Auction contract checks input sizes + // If kitty is already on any auction, this will throw + // because it will be owned by the auction contract. + require(_owns(msg.sender, _kittyId)); + // Ensure the kitty is not pregnant to prevent the auction + // contract accidentally receiving ownership of the child. + // NOTE: the kitty IS allowed to be in a cooldown. + require(!isPregnant(_kittyId)); + _approve(_kittyId, address(saleAuction)); + // Sale auction throws if inputs are invalid and clears + // transfer and sire approval after escrowing the kitty. + saleAuction.createAuction( + _kittyId, + _startingPrice, + _endingPrice, + _duration, + msg.sender + ); + } + + /// @dev Put a kitty up for auction to be sire. + /// Performs checks to ensure the kitty can be sired, then + /// delegates to reverse auction. + function createSiringAuction( + uint256 _kittyId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration + ) + external + whenNotPaused + { + // Auction contract checks input sizes + // If kitty is already on any auction, this will throw + // because it will be owned by the auction contract. + require(_owns(msg.sender, _kittyId)); + require(isReadyToBreed(_kittyId)); + _approve(_kittyId, address(siringAuction)); + // Siring auction throws if inputs are invalid and clears + // transfer and sire approval after escrowing the kitty. + siringAuction.createAuction( + _kittyId, + _startingPrice, + _endingPrice, + _duration, + msg.sender + ); + } + + /// @dev Completes a siring auction by bidding. + /// Immediately breeds the winning matron with the sire on auction. + /// @param _sireId - ID of the sire on auction. + /// @param _matronId - ID of the matron owned by the bidder. + function bidOnSiringAuction( + uint256 _sireId, + uint256 _matronId + ) + external + payable + whenNotPaused + { + // Auction contract checks input sizes + require(_owns(msg.sender, _matronId)); + require(isReadyToBreed(_matronId)); + require(_canBreedWithViaAuction(_matronId, _sireId)); + + // Define the current price of the auction. + uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); + require(msg.value >= currentPrice + autoBirthFee); + + // Siring auction will throw if the bid fails. + siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); + _breedWith(uint32(_matronId), uint32(_sireId)); + } + + /// @dev Transfers the balance of the sale auction contract + /// to the KittyCore contract. We use two-step withdrawal to + /// prevent two transfer calls in the auction bid function. + function withdrawAuctionBalances() external onlyCLevel { + saleAuction.withdrawBalance(); + siringAuction.withdrawBalance(); + } +} + + +/// @title all functions related to creating kittens +contract KittyMinting is KittyAuction { + + // Limits the number of cats the contract owner can ever create. + uint256 public constant PROMO_CREATION_LIMIT = 5000; + uint256 public constant GEN0_CREATION_LIMIT = 45000; + + // Constants for gen0 auctions. + uint256 public constant GEN0_STARTING_PRICE = 10 sun; + uint256 public constant GEN0_AUCTION_DURATION = 1 days; + + // Counts the number of cats the contract owner has created. + uint256 public promoCreatedCount; + uint256 public gen0CreatedCount; + + /// @dev we can create promo kittens, up to a limit. Only callable by COO + /// @param _genes the encoded genes of the kitten to be created, any value is accepted + /// @param _owner the future owner of the created kittens. Default to contract COO + function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { + address kittyOwner = _owner; + if (kittyOwner == address(0)) { + kittyOwner = cooAddress; + } + require(promoCreatedCount < PROMO_CREATION_LIMIT); + + promoCreatedCount++; + _createKitty(0, 0, 0, _genes, kittyOwner); + } + + /// @dev Creates a new gen0 kitty with the given genes and + /// creates an auction for it. + function createGen0Auction(uint256 _genes) external onlyCOO { + require(gen0CreatedCount < GEN0_CREATION_LIMIT); + + uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); + _approve(kittyId, address(saleAuction)); + + saleAuction.createAuction( + kittyId, + _computeNextGen0Price(), + 0, + GEN0_AUCTION_DURATION, + address(uint160(address(this))) + ); + + gen0CreatedCount++; + } + + /// @dev Computes the next gen0 auction starting price, given + /// the average of the past 5 prices + 50%. + function _computeNextGen0Price() internal view returns (uint256) { + uint256 avePrice = saleAuction.averageGen0SalePrice(); + + // Sanity check to ensure we don't overflow arithmetic + require(avePrice == uint256(uint128(avePrice))); + + uint256 nextPrice = avePrice + (avePrice / 2); + + // We never auction for less than starting price + if (nextPrice < GEN0_STARTING_PRICE) { + nextPrice = GEN0_STARTING_PRICE; + } + + return nextPrice; + } +} + + + +/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. +contract KittyCore is KittyMinting { + + // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, + // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts + // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are + // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping + // them in their own contracts, we can upgrade them without disrupting the main contract that tracks + // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of + // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. + // Don't worry, I'm sure someone will reverse engineer it soon enough! + // + // Secondly, we break the core contract into multiple files using inheritence, one for each major + // facet of functionality of CK. This allows us to keep related code bundled together while still + // avoiding a single giant file with everything in it. The breakdown is as follows: + // + // - KittyBase: This is where we define the most fundamental code shared throughout the core + // functionality. This includes our main data storage, constants and data types, plus + // internal functions for managing these items. + // + // - KittyAccessControl: This contract manages the various addresses and constraints for operations + // that can be executed only by specific roles. Namely CEO, CFO and COO. + // + // - KittyOwnership: This provides the methods required for basic non-fungible token + // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). + // + // - KittyBreeding: This file contains the methods necessary to breed cats together, including + // keeping track of siring offers, and relies on an external genetic combination contract. + // + // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring + // services. The actual auction functionality is handled in two sibling contracts (one + // for sales and one for siring), while auction creation and bidding is mostly mediated + // through this facet of the core contract. + // + // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. + // We can make up to 5000 "promo" cats that can be given away (especially important when + // the community is new), and all others can only be created and then immediately put up + // for auction via an algorithmically determined starting price. Regardless of how they + // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the + // community to breed, breed, breed! + + // Set in case the core contract is broken and an upgrade is required + address public newContractAddress; + + /// @notice Creates the main CryptoKitties smart contract instance. + constructor() public { + // Starts paused. + paused = true; + + // the creator of the contract is the initial CEO + ceoAddress = msg.sender; + + // the creator of the contract is also the initial COO + cooAddress = msg.sender; + + // start with the mythical kitten 0 - so we don't have generation-0 parent issues + _createKitty(0, 0, 0, uint256(-1), address(0)); + } + + /// @dev Used to mark the smart contract as upgraded, in case there is a serious + /// breaking bug. This method does nothing but keep track of the new contract and + /// emit a message indicating that the new address is set. It's up to clients of this + /// contract to update to the new contract address in that case. (This contract will + /// be paused indefinitely if such an upgrade takes place.) + /// @param _v2Address new address + function setNewAddress(address _v2Address) external onlyCEO whenPaused { + // See README.md for updgrade plan + newContractAddress = _v2Address; + emit ContractUpgrade(_v2Address); + } + + /// @notice No tipping! + /// @dev Reject all Ether from being sent here, unless it's from one of the + /// two auction contracts. (Hopefully, we can prevent user accidents.) + function() external payable { + require( + msg.sender == address(saleAuction) || + msg.sender == address(siringAuction) + ); + } + + /// @notice Returns all the relevant information about a specific kitty. + /// @param _id The ID of the kitty of interest. + function getKitty(uint256 _id) + external + view + returns ( + bool isGestating, + bool isReady, + uint256 cooldownIndex, + uint256 nextActionAt, + uint256 siringWithId, + uint256 birthTime, + uint256 matronId, + uint256 sireId, + uint256 generation, + uint256 genes + ) { + Kitty storage kit = kitties[_id]; + + // if this variable is 0 then it's not gestating + isGestating = (kit.siringWithId != 0); + isReady = (kit.cooldownEndBlock <= block.number); + cooldownIndex = uint256(kit.cooldownIndex); + nextActionAt = uint256(kit.cooldownEndBlock); + siringWithId = uint256(kit.siringWithId); + birthTime = uint256(kit.birthTime); + matronId = uint256(kit.matronId); + sireId = uint256(kit.sireId); + generation = uint256(kit.generation); + genes = kit.genes; + } + + /// @dev Override unpause so it requires all external contract addresses + /// to be set before contract can be unpaused. Also, we can't have + /// newContractAddress set either, because then the contract was upgraded. + /// @notice This is public rather than external so we can call super.unpause + /// without using an expensive CALL. + + function unpause() public onlyCEO whenPaused { + require(address(saleAuction) != address(0)); + require(address(siringAuction) != address(0)); + require(address(geneScience) != address(0)); + require(newContractAddress == address(0)); + + // Actually unpause the contract. + super.unpause(); + } + + // @dev Allows the CFO to capture the balance available to the contract. + function withdrawBalance() external onlyCFO { + uint256 balance = address(this).balance; + // Subtract all the currently pregnant kittens we have, plus 1 of margin. + uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; + + if (balance > subtractFees) { + cfoAddress.transfer(balance - subtractFees); + } + } +} + + + + + + + + + + + + + +// // Auction wrapper functions + + +// Auction wrapper functions + + + + + + + +/// @title SEKRETOOOO +contract GeneScienceInterface { + + function isGeneScience() public pure returns (bool){ + return true; + } + + /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor + /// @param genes1 genes of mom + /// @param genes2 genes of sire + /// @return the genes that are supposed to be passed down the child + function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ + + return (genes1+genes2+targetBlock)/2; + + +} +} + + + + + + + + + + + + + + + + +/// @title The external contract that is responsible for generating metadata for the kitties, +/// it has one function that will return the data as bytes. +contract ERC721Metadata { + /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. + function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { + if (_tokenId == 1) { + buffer[0] = "Hello World! :D"; + count = 15; + } else if (_tokenId == 2) { + buffer[0] = "I would definitely choose a medi"; + buffer[1] = "um length string."; + count = 49; + } else if (_tokenId == 3) { + buffer[0] = "Lorem ipsum dolor sit amet, mi e"; + buffer[1] = "st accumsan dapibus augue lorem,"; + buffer[2] = " tristique vestibulum id, libero"; + buffer[3] = " suscipit varius sapien aliquam."; + count = 128; + } + } +} + + + + + + + + + + + + + + + +/// @title Auction Core +/// @dev Contains models, variables, and internal methods for the auction. +/// @notice We omit a fallback function to prevent accidental sends to this contract. +contract ClockAuctionBase { + + // Represents an auction on an NFT + struct Auction { + // Current owner of NFT + address payable seller; + // Price (in wei) at beginning of auction + uint128 startingPrice; + // Price (in wei) at end of auction + uint128 endingPrice; + // Duration (in seconds) of auction + uint64 duration; + // Time when auction started + // NOTE: 0 if this auction has been concluded + uint64 startedAt; + } + + // Reference to contract tracking NFT ownership + ERC721 public nonFungibleContract; + + // Cut owner takes on each auction, measured in basis points (1/100 of a percent). + // Values 0-10,000 map to 0%-100% + uint256 public ownerCut; + + // Map from token ID to their corresponding auction. + mapping (uint256 => Auction) tokenIdToAuction; + + event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); + event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); + event AuctionCancelled(uint256 tokenId); + + /// @dev Returns true if the claimant owns the token. + /// @param _claimant - Address claiming to own the token. + /// @param _tokenId - ID of token whose ownership to verify. + function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { + return (nonFungibleContract.ownerOf(_tokenId) == _claimant); + } + + /// @dev Escrows the NFT, assigning ownership to this contract. + /// Throws if the escrow fails. + /// @param _owner - Current owner address of token to escrow. + /// @param _tokenId - ID of token whose approval to verify. + function _escrow(address _owner, uint256 _tokenId) internal { + // it will throw if transfer fails + nonFungibleContract.transferFrom(_owner, address(this), _tokenId); + } + + /// @dev Transfers an NFT owned by this contract to another address. + /// Returns true if the transfer succeeds. + /// @param _receiver - Address to transfer NFT to. + /// @param _tokenId - ID of token to transfer. + function _transfer(address _receiver, uint256 _tokenId) internal { + // it will throw if transfer fails + nonFungibleContract.transfer(_receiver, _tokenId); + } + + /// @dev Adds an auction to the list of open auctions. Also fires the + /// AuctionCreated event. + /// @param _tokenId The ID of the token to be put on auction. + /// @param _auction Auction to add. + function _addAuction(uint256 _tokenId, Auction memory _auction) internal { + // Require that all auctions have a duration of + // at least one minute. (Keeps our math from getting hairy!) + require(_auction.duration >= 1 minutes); + + tokenIdToAuction[_tokenId] = _auction; + + emit AuctionCreated( + uint256(_tokenId), + uint256(_auction.startingPrice), + uint256(_auction.endingPrice), + uint256(_auction.duration) + ); + } + + /// @dev Cancels an auction unconditionally. + function _cancelAuction(uint256 _tokenId, address _seller) internal { + _removeAuction(_tokenId); + _transfer(_seller, _tokenId); + emit AuctionCancelled(_tokenId); + } + + /// @dev Computes the price and transfers winnings. + /// Does NOT transfer ownership of token. + function _bid(uint256 _tokenId, uint256 _bidAmount) + internal + returns (uint256) + { + // Get a reference to the auction struct + Auction storage auction = tokenIdToAuction[_tokenId]; + + // Explicitly check that this auction is currently live. + // (Because of how Ethereum mappings work, we can't just count + // on the lookup above failing. An invalid _tokenId will just + // return an auction object that is all zeros.) + require(_isOnAuction(auction)); + + // Check that the bid is greater than or equal to the current price + uint256 price = _currentPrice(auction); + require(_bidAmount >= price); + + // Grab a reference to the seller before the auction struct + // gets deleted. + address payable seller = auction.seller; + + // The bid is good! Remove the auction before sending the fees + // to the sender so we can't have a reentrancy attack. + _removeAuction(_tokenId); + + // Transfer proceeds to seller (if there are any!) + if (price > 0) { + // Calculate the auctioneer's cut. + // (NOTE: _computeCut() is guaranteed to return a + // value <= price, so this subtraction can't go negative.) + uint256 auctioneerCut = _computeCut(price); + uint256 sellerProceeds = price - auctioneerCut; + + // NOTE: Doing a transfer() in the middle of a complex + // method like this is generally discouraged because of + // reentrancy attacks and DoS attacks if the seller is + // a contract with an invalid fallback function. We explicitly + // guard against reentrancy attacks by removing the auction + // before calling transfer(), and the only thing the seller + // can DoS is the sale of their own asset! (And if it's an + // accident, they can call cancelAuction(). ) + seller.transfer(sellerProceeds); + } + + // Calculate any excess funds included with the bid. If the excess + // is anything worth worrying about, transfer it back to bidder. + // NOTE: We checked above that the bid amount is greater than or + // equal to the price so this cannot underflow. + uint256 bidExcess = _bidAmount - price; + + // Return the funds. Similar to the previous transfer, this is + // not susceptible to a re-entry attack because the auction is + // removed before any transfers occur. + msg.sender.transfer(bidExcess); + + // Tell the world! + emit AuctionSuccessful(_tokenId, price, msg.sender); + + return price; + } + + /// @dev Removes an auction from the list of open auctions. + /// @param _tokenId - ID of NFT on auction. + function _removeAuction(uint256 _tokenId) internal { + delete tokenIdToAuction[_tokenId]; + } + + /// @dev Returns true if the NFT is on auction. + /// @param _auction - Auction to check. + function _isOnAuction(Auction storage _auction) internal view returns (bool) { + return (_auction.startedAt > 0); + } + + /// @dev Returns current price of an NFT on auction. Broken into two + /// functions (this one, that computes the duration from the auction + /// structure, and the other that does the price computation) so we + /// can easily test that the price computation works correctly. + function _currentPrice(Auction storage _auction) + internal + view + returns (uint256) + { + uint256 secondsPassed = 0; + + // A bit of insurance against negative values (or wraparound). + // Probably not necessary (since Ethereum guarnatees that the + // now variable doesn't ever go backwards). + if (now > _auction.startedAt) { + secondsPassed = now - _auction.startedAt; + } + + return _computeCurrentPrice( + _auction.startingPrice, + _auction.endingPrice, + _auction.duration, + secondsPassed + ); + } + + /// @dev Computes the current price of an auction. Factored out + /// from _currentPrice so we can run extensive unit tests. + /// When testing, make this function public and turn on + /// `Current price computation` test suite. + function _computeCurrentPrice( + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration, + uint256 _secondsPassed + ) + internal + pure + returns (uint256) + { + // NOTE: We don't use SafeMath (or similar) in this function because + // all of our public functions carefully cap the maximum values for + // time (at 64-bits) and currency (at 128-bits). _duration is + // also known to be non-zero (see the require() statement in + // _addAuction()) + if (_secondsPassed >= _duration) { + // We've reached the end of the dynamic pricing portion + // of the auction, just return the end price. + return _endingPrice; + } else { + // Starting price can be higher than ending price (and often is!), so + // this delta can be negative. + int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); + + // This multiplication can't overflow, _secondsPassed will easily fit within + // 64-bits, and totalPriceChange will easily fit within 128-bits, their product + // will always fit within 256-bits. + int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); + + // currentPriceChange can be negative, but if so, will have a magnitude + // less that _startingPrice. Thus, this result will always end up positive. + int256 currentPrice = int256(_startingPrice) + currentPriceChange; + + return uint256(currentPrice); + } + } + + /// @dev Computes owner's cut of a sale. + /// @param _price - Sale price of NFT. + function _computeCut(uint256 _price) internal view returns (uint256) { + // NOTE: We don't use SafeMath (or similar) in this function because + // all of our entry functions carefully cap the maximum values for + // currency (at 128-bits), and ownerCut <= 10000 (see the require() + // statement in the ClockAuction constructor). The result of this + // function is always guaranteed to be <= _price. + return _price * ownerCut / 10000; + } + +} + + + + + + + +/** + * @title Pausable + * @dev Base contract which allows children to implement an emergency stop mechanism. + */ +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + /** + * @dev modifier to allow actions only when the contract IS paused + */ + modifier whenNotPaused() { + require(!paused); + _; + } + + /** + * @dev modifier to allow actions only when the contract IS NOT paused + */ + modifier whenPaused { + require(paused); + _; + } + + /** + * @dev called by the owner to pause, triggers stopped state + */ + function pause() onlyOwner whenNotPaused public returns (bool) { + paused = true; + emit Pause(); + return true; + } + + /** + * @dev called by the owner to unpause, returns to normal state + */ + function unpause() onlyOwner whenPaused public returns (bool) { + paused = false; + emit Unpause(); + return true; + } +} + + +/// @title Clock auction for non-fungible tokens. +/// @notice We omit a fallback function to prevent accidental sends to this contract. +contract ClockAuction is Pausable, ClockAuctionBase { + + /// @dev The ERC-165 interface signature for ERC-721. + /// Ref: https://github.com/ethereum/EIPs/issues/165 + /// Ref: https://github.com/ethereum/EIPs/issues/721 + bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); + + /// @dev Constructor creates a reference to the NFT ownership contract + /// and verifies the owner cut is in the valid range. + /// @param _nftAddress - address of a deployed contract implementing + /// the Nonfungible Interface. + /// @param _cut - percent cut the owner takes on each auction, must be + /// between 0-10,000. + constructor(address _nftAddress, uint256 _cut) public { + require(_cut <= 10000); + ownerCut = _cut; + + ERC721 candidateContract = ERC721(_nftAddress); + require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); + nonFungibleContract = candidateContract; + } + + /// @dev Remove all Ether from the contract, which is the owner's cuts + /// as well as any Ether sent directly to the contract address. + /// Always transfers to the NFT contract, but can be called either by + /// the owner or the NFT contract. + function withdrawBalance() external { + address payable nftAddress = address(uint160(address(nonFungibleContract))); + + require( + msg.sender == owner || + msg.sender == nftAddress + ); + // We are using this boolean method to make sure that even if one fails it will still work + bool res = nftAddress.send(address(this).balance); + } + + /// @dev Creates and begins a new auction. + /// @param _tokenId - ID of token to auction, sender must be owner. + /// @param _startingPrice - Price of item (in wei) at beginning of auction. + /// @param _endingPrice - Price of item (in wei) at end of auction. + /// @param _duration - Length of time to move between starting + /// price and ending price (in seconds). + /// @param _seller - Seller, if not the message sender + function createAuction( + uint256 _tokenId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration, + address payable _seller + ) + external + whenNotPaused + { + // Sanity check that no inputs overflow how many bits we've allocated + // to store them in the auction struct. + require(_startingPrice == uint256(uint128(_startingPrice))); + require(_endingPrice == uint256(uint128(_endingPrice))); + require(_duration == uint256(uint64(_duration))); + + require(_owns(msg.sender, _tokenId)); + _escrow(msg.sender, _tokenId); + Auction memory auction = Auction( + _seller, + uint128(_startingPrice), + uint128(_endingPrice), + uint64(_duration), + uint64(now) + ); + _addAuction(_tokenId, auction); + } + + /// @dev Bids on an open auction, completing the auction and transferring + /// ownership of the NFT if enough Ether is supplied. + /// @param _tokenId - ID of token to bid on. + function bid(uint256 _tokenId) + external + payable + whenNotPaused + { + // _bid will throw if the bid or funds transfer fails + _bid(_tokenId, msg.value); + _transfer(msg.sender, _tokenId); + } + + /// @dev Cancels an auction that hasn't been won yet. + /// Returns the NFT to original owner. + /// @notice This is a state-modifying function that can + /// be called while the contract is paused. + /// @param _tokenId - ID of token on auction + function cancelAuction(uint256 _tokenId) + external + { + Auction storage auction = tokenIdToAuction[_tokenId]; + require(_isOnAuction(auction)); + address seller = auction.seller; + require(msg.sender == seller); + _cancelAuction(_tokenId, seller); + } + + /// @dev Cancels an auction when the contract is paused. + /// Only the owner may do this, and NFTs are returned to + /// the seller. This should only be used in emergencies. + /// @param _tokenId - ID of the NFT on auction to cancel. + function cancelAuctionWhenPaused(uint256 _tokenId) + whenPaused + onlyOwner + external + { + Auction storage auction = tokenIdToAuction[_tokenId]; + require(_isOnAuction(auction)); + _cancelAuction(_tokenId, auction.seller); + } + + /// @dev Returns auction info for an NFT on auction. + /// @param _tokenId - ID of NFT on auction. + function getAuction(uint256 _tokenId) + external + view + returns + ( + address seller, + uint256 startingPrice, + uint256 endingPrice, + uint256 duration, + uint256 startedAt + ) { + Auction storage auction = tokenIdToAuction[_tokenId]; + require(_isOnAuction(auction)); + return ( + auction.seller, + auction.startingPrice, + auction.endingPrice, + auction.duration, + auction.startedAt + ); + } + + /// @dev Returns the current price of an auction. + /// @param _tokenId - ID of the token price we are checking. + function getCurrentPrice(uint256 _tokenId) + external + view + returns (uint256) + { + Auction storage auction = tokenIdToAuction[_tokenId]; + require(_isOnAuction(auction)); + return _currentPrice(auction); + } + +} + + +/// @title Reverse auction modified for siring +/// @notice We omit a fallback function to prevent accidental sends to this contract. +contract SiringClockAuction is ClockAuction { + + // @dev Sanity check that allows us to ensure that we are pointing to the + // right auction in our setSiringAuctionAddress() call. + bool public isSiringClockAuction = true; + + // Delegate constructor + constructor(address _nftAddr, uint256 _cut) public + ClockAuction(_nftAddr, _cut) {} + + /// @dev Creates and begins a new auction. Since this function is wrapped, + /// require sender to be KittyCore contract. + /// @param _tokenId - ID of token to auction, sender must be owner. + /// @param _startingPrice - Price of item (in wei) at beginning of auction. + /// @param _endingPrice - Price of item (in wei) at end of auction. + /// @param _duration - Length of auction (in seconds). + /// @param _seller - Seller, if not the message sender + function createAuction( + uint256 _tokenId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration, + address payable _seller + ) + external + { + // Sanity check that no inputs overflow how many bits we've allocated + // to store them in the auction struct. + require(_startingPrice == uint256(uint128(_startingPrice))); + require(_endingPrice == uint256(uint128(_endingPrice))); + require(_duration == uint256(uint64(_duration))); + + require(msg.sender == address(nonFungibleContract)); + _escrow(_seller, _tokenId); + Auction memory auction = Auction( + _seller, + uint128(_startingPrice), + uint128(_endingPrice), + uint64(_duration), + uint64(now) + ); + _addAuction(_tokenId, auction); + } + + /// @dev Places a bid for siring. Requires the sender + /// is the KittyCore contract because all bid methods + /// should be wrapped. Also returns the kitty to the + /// seller rather than the winner. + function bid(uint256 _tokenId) + external + payable + { + require(msg.sender == address(nonFungibleContract)); + address seller = tokenIdToAuction[_tokenId].seller; + // _bid checks that token ID is valid and will throw if bid fails + _bid(_tokenId, msg.value); + // We transfer the kitty back to the seller, the winner will get + // the offspring + _transfer(seller, _tokenId); + } + +} + + + + + +/// @title Clock auction modified for sale of kitties +/// @notice We omit a fallback function to prevent accidental sends to this contract. +contract SaleClockAuction is ClockAuction { + + // @dev Sanity check that allows us to ensure that we are pointing to the + // right auction in our setSaleAuctionAddress() call. + bool public isSaleClockAuction = true; + + // Tracks last 5 sale price of gen0 kitty sales + uint256 public gen0SaleCount; + uint256[5] public lastGen0SalePrices; + + // Delegate constructor + constructor(address _nftAddr, uint256 _cut) public + ClockAuction(_nftAddr, _cut) {} + + /// @dev Creates and begins a new auction. + /// @param _tokenId - ID of token to auction, sender must be owner. + /// @param _startingPrice - Price of item (in wei) at beginning of auction. + /// @param _endingPrice - Price of item (in wei) at end of auction. + /// @param _duration - Length of auction (in seconds). + /// @param _seller - Seller, if not the message sender + function createAuction( + uint256 _tokenId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration, + address payable _seller + ) + external + { + // Sanity check that no inputs overflow how many bits we've allocated + // to store them in the auction struct. + require(_startingPrice == uint256(uint128(_startingPrice))); + require(_endingPrice == uint256(uint128(_endingPrice))); + require(_duration == uint256(uint64(_duration))); + + require(msg.sender == address(nonFungibleContract)); + _escrow(_seller, _tokenId); + Auction memory auction = Auction( + _seller, + uint128(_startingPrice), + uint128(_endingPrice), + uint64(_duration), + uint64(now) + ); + _addAuction(_tokenId, auction); + } + + /// @dev Updates lastSalePrice if seller is the nft contract + /// Otherwise, works the same as default bid method. + function bid(uint256 _tokenId) + external + payable + { + // _bid verifies token ID size + address seller = tokenIdToAuction[_tokenId].seller; + uint256 price = _bid(_tokenId, msg.value); + _transfer(msg.sender, _tokenId); + + // If not a gen0 auction, exit + if (seller == address(nonFungibleContract)) { + // Track gen0 sale prices + lastGen0SalePrices[gen0SaleCount % 5] = price; + gen0SaleCount++; + } + } + + function averageGen0SalePrice() external view returns (uint256) { + uint256 sum = 0; + for (uint256 i = 0; i < 5; i++) { + sum += lastGen0SalePrices[i]; + } + return sum / 5; + } + +} + + + + + + + diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario009.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario009.sol new file mode 100644 index 00000000000..fb0b76db240 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractScenario009.sol @@ -0,0 +1,51 @@ +//pragma solidity ^0.4.0; + +library Set { + // We define a new struct datatype that will be used to + // hold its data in the calling contract. + struct Data { mapping(uint => bool) flags; } + + // Note that the first parameter is of type "storage + // reference" and thus only its storage address and not + // its contents is passed as part of the call. This is a + // special feature of library functions. It is idiomatic + // to call the first parameter 'self', if the function can + // be seen as a method of that object. + function insert (Data storage self, uint value) public + returns (bool) + { + if (self.flags[value]) + return false; // already there + self.flags[value] = true; + return true; + } + + function remove(Data storage self, uint value) public + returns (bool) + { + if (!self.flags[value]) + return false; // not there + self.flags[value] = false; + return true; + } + + function contains(Data storage self, uint value) public + returns (bool) + { + return self.flags[value]; + } +} + + +contract C { + Set.Data knownValues; + + function register(uint value) public { + // The library functions can be called without a + // specific instance of the library, since the + // "instance" will be the current contract. + if (!Set.insert(knownValues, value)) + revert(); + } + // In this contract, we can also directly access knownValues.flags, if we want. +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario010.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario010.sol new file mode 100644 index 00000000000..f665ea9686e --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractScenario010.sol @@ -0,0 +1,107 @@ +//pragma solidity ^0.4.11; + +contract TRON_ERC721 { + //name + function name() view public returns (string memory name){ + return "Tron ERC721 Token"; + } + //symbol + function symbol() view public returns (string memory symbol){ + return "T721T"; + } + + //totalSupply + + function totalSupply() view public returns (uint256 supply){ + uint256 totalSupply = 1000000000000; + return totalSupply; + } + + mapping(address => uint) private balances; + function balanceOf(address _owner) view public returns (uint balance) + { + return balances[_owner]; + } + + + mapping(uint256 => address) private tokenOwners; + mapping(uint256 => bool) private tokenExists; + function ownerOf(uint256 _tokenId) view public returns (address owner) { + require(tokenExists[_tokenId]); + return tokenOwners[_tokenId]; + } + + + mapping(address => mapping (address => uint256)) allowed; + function approve(address _to, uint256 _tokenId) public{ + require(msg.sender == ownerOf(_tokenId)); + require(msg.sender != _to); + allowed[msg.sender][_to] = _tokenId; + emit Approval(msg.sender, _to, _tokenId); + } + + + function takeOwnership(uint256 _tokenId) public { + require(tokenExists[_tokenId]); + address oldOwner = ownerOf(_tokenId); + address newOwner = msg.sender; + require(newOwner != oldOwner); + require(allowed[oldOwner][newOwner] == _tokenId); + balances[oldOwner] -= 1; + tokenOwners[_tokenId] = newOwner; + balances[newOwner] += 1; + emit Transfer(oldOwner, newOwner, _tokenId); + } + + + mapping(address => mapping(uint256 => uint256)) private ownerTokens; + function removeFromTokenList(address owner, uint256 _tokenId) private { + for(uint256 i = 0;ownerTokens[owner][i] != _tokenId;i++){ + ownerTokens[owner][i] = 0; + } + } + + function transfer(address _to, uint256 _tokenId) public{ + address currentOwner = msg.sender; + address newOwner = _to; + require(tokenExists[_tokenId]); + require(currentOwner == ownerOf(_tokenId)); + require(currentOwner != newOwner); + require(newOwner != address(0)); + address oldOwner =currentOwner; + removeFromTokenList(oldOwner,_tokenId); + balances[oldOwner] -= 1; + tokenOwners[_tokenId] = newOwner; + balances[newOwner] += 1; + emit Transfer(oldOwner, newOwner, _tokenId); + } + + function transferFrom(address _from,address _to, uint256 _tokenId) public{ + address currentOwner = _from; + address newOwner = _to; + require(tokenExists[_tokenId]); + require(currentOwner == ownerOf(_tokenId)); + require(currentOwner != newOwner); + require(newOwner != address(0)); + address oldOwner =currentOwner; + removeFromTokenList(oldOwner,_tokenId); + balances[oldOwner] -= 1; + tokenOwners[_tokenId] = newOwner; + balances[newOwner] += 1; + emit Transfer(oldOwner, newOwner, _tokenId); + } + + + function tokenOfOwnerByIndex(address _owner, uint256 _index) view public returns (uint tokenId){ + return ownerTokens[_owner][_index]; + } + + + mapping(uint256 => string) tokenLinks; + function tokenMetadata(uint256 _tokenId) view public returns (string memory infoUrl) { + return tokenLinks[_tokenId]; + } + // Events + event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); + event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario011.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario011.sol new file mode 100644 index 00000000000..74fe819be31 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractScenario011.sol @@ -0,0 +1,2050 @@ +//pragma solidity ^0.4.11; + + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + if (newOwner != address(0)) { + owner = newOwner; + } + } + +} + + + + +/// @title A facet of KittyCore that manages special access privileges. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. +contract KittyAccessControl { + // This facet controls access control for CryptoKitties. There are four roles managed here: + // + // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart + // contracts. It is also the only role that can unpause the smart contract. It is initially + // set to the address that created the smart contract in the KittyCore constructor. + // + // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. + // + // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. + // + // It should be noted that these roles are distinct without overlap in their access abilities, the + // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any + // address to any role, the CEO address itself doesn't have the ability to act in those roles. This + // restriction is intentional so that we aren't tempted to use the CEO address frequently out of + // convenience. The less we use an address, the less likely it is that we somehow compromise the + // account. + + /// @dev Emited when contract is upgraded - See README.md for updgrade plan + event ContractUpgrade(address newContract); + + // The addresses of the accounts (or contracts) that can execute actions within each roles. + address public ceoAddress; + address payable public cfoAddress; + address public cooAddress; + + // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked + bool public paused = false; + + /// @dev Access modifier for CEO-only functionality + modifier onlyCEO() { + require(msg.sender == ceoAddress); + _; + } + + /// @dev Access modifier for CFO-only functionality + modifier onlyCFO() { + require(msg.sender == cfoAddress); + _; + } + + /// @dev Access modifier for COO-only functionality + modifier onlyCOO() { + require(msg.sender == cooAddress); + _; + } + + modifier onlyCLevel() { + require( + msg.sender == cooAddress || + msg.sender == ceoAddress || + msg.sender == cfoAddress + ); + _; + } + + /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. + /// @param _newCEO The address of the new CEO + function setCEO(address _newCEO) external onlyCEO { + require(_newCEO != address(0)); + + ceoAddress = _newCEO; + } + + /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. + /// @param _newCFO The address of the new CFO + function setCFO(address payable _newCFO) external onlyCEO { + require(_newCFO != address(0)); + + cfoAddress = _newCFO; + } + + /// @dev Assigns a new address to act as the COO. Only available to the current CEO. + /// @param _newCOO The address of the new COO + function setCOO(address _newCOO) external onlyCEO { + require(_newCOO != address(0)); + + cooAddress = _newCOO; + } + + /*** Pausable functionality adapted from OpenZeppelin ***/ + + /// @dev Modifier to allow actions only when the contract IS NOT paused + modifier whenNotPaused() { + require(!paused); + _; + } + + /// @dev Modifier to allow actions only when the contract IS paused + modifier whenPaused { + require(paused); + _; + } + + /// @dev Called by any "C-level" role to pause the contract. Used only when + /// a bug or exploit is detected and we need to limit damage. + function pause() external onlyCLevel whenNotPaused { + paused = true; + } + + /// @dev Unpauses the smart contract. Can only be called by the CEO, since + /// one reason we may pause the contract is when CFO or COO accounts are + /// compromised. + /// @notice This is public rather than external so it can be called by + /// derived contracts. + function unpause() public onlyCEO whenPaused { + // can't unpause if contract was upgraded + paused = false; + } +} + + + + +/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. +contract KittyBase is KittyAccessControl { + /*** EVENTS ***/ + + /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously + /// includes any time a cat is created through the giveBirth method, but it is also called + /// when a new gen0 cat is created. + event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); + + /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten + /// ownership is assigned, including births. + event Transfer(address from, address to, uint256 tokenId); + + /*** DATA TYPES ***/ + + /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy + /// of this structure, so great care was taken to ensure that it fits neatly into + /// exactly two 256-bit words. Note that the order of the members in this structure + /// is important because of the byte-packing rules used by Ethereum. + /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html + struct Kitty { + // The Kitty's genetic code is packed into these 256-bits, the format is + // sooper-sekret! A cat's genes never change. + uint256 genes; + + // The timestamp from the block when this cat came into existence. + uint64 birthTime; + + // The minimum timestamp after which this cat can engage in breeding + // activities again. This same timestamp is used for the pregnancy + // timer (for matrons) as well as the siring cooldown. + uint64 cooldownEndBlock; + + // The ID of the parents of this kitty, set to 0 for gen0 cats. + // Note that using 32-bit unsigned integers limits us to a "mere" + // 4 billion cats. This number might seem small until you realize + // that Ethereum currently has a limit of about 500 million + // transactions per year! So, this definitely won't be a problem + // for several years (even as Ethereum learns to scale). + uint32 matronId; + uint32 sireId; + + // Set to the ID of the sire cat for matrons that are pregnant, + // zero otherwise. A non-zero value here is how we know a cat + // is pregnant. Used to retrieve the genetic material for the new + // kitten when the birth transpires. + uint32 siringWithId; + + // Set to the index in the cooldown array (see below) that represents + // the current cooldown duration for this Kitty. This starts at zero + // for gen0 cats, and is initialized to floor(generation/2) for others. + // Incremented by one for each successful breeding action, regardless + // of whether this cat is acting as matron or sire. + uint16 cooldownIndex; + + // The "generation number" of this cat. Cats minted by the CK contract + // for sale are called "gen0" and have a generation number of 0. The + // generation number of all other cats is the larger of the two generation + // numbers of their parents, plus one. + // (i.e. max(matron.generation, sire.generation) + 1) + uint16 generation; + } + + /*** CONSTANTS ***/ + + /// @dev A lookup table indicating the cooldown duration after any successful + /// breeding action, called "pregnancy time" for matrons and "siring cooldown" + /// for sires. Designed such that the cooldown roughly doubles each time a cat + /// is bred, encouraging owners not to just keep breeding the same cat over + /// and over again. Caps out at one week (a cat can breed an unbounded number + /// of times, and the maximum cooldown is always seven days). + uint32[14] public cooldowns = [ + uint32(1 minutes), + uint32(2 minutes), + uint32(5 minutes), + uint32(10 minutes), + uint32(30 minutes), + uint32(1 hours), + uint32(2 hours), + uint32(4 hours), + uint32(8 hours), + uint32(16 hours), + uint32(1 days), + uint32(2 days), + uint32(4 days), + uint32(7 days) + ]; + + // An approximation of currently how many seconds are in between blocks. + uint256 public secondsPerBlock = 15; + + /*** STORAGE ***/ + + /// @dev An array containing the Kitty struct for all Kitties in existence. The ID + /// of each cat is actually an index into this array. Note that ID 0 is a negacat, + /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre + /// creature that is both matron and sire... to itself! Has an invalid genetic code. + /// In other words, cat ID 0 is invalid... ;-) + Kitty[] kitties; + + /// @dev A mapping from cat IDs to the address that owns them. All cats have + /// some valid owner address, even gen0 cats are created with a non-zero owner. + mapping (uint256 => address) public kittyIndexToOwner; + + // @dev A mapping from owner address to count of tokens that address owns. + // Used internally inside balanceOf() to resolve ownership count. + mapping (address => uint256) ownershipTokenCount; + + /// @dev A mapping from KittyIDs to an address that has been approved to call + /// transferFrom(). Each Kitty can only have one approved address for transfer + /// at any time. A zero value means no approval is outstanding. + mapping (uint256 => address) public kittyIndexToApproved; + + /// @dev A mapping from KittyIDs to an address that has been approved to use + /// this Kitty for siring via breedWith(). Each Kitty can only have one approved + /// address for siring at any time. A zero value means no approval is outstanding. + mapping (uint256 => address) public sireAllowedToAddress; + + /// @dev The address of the ClockAuction contract that handles sales of Kitties. This + /// same contract handles both peer-to-peer sales as well as the gen0 sales which are + /// initiated every 15 minutes. + SaleClockAuction public saleAuction; + + /// @dev The address of a custom ClockAuction subclassed contract that handles siring + /// auctions. Needs to be separate from saleAuction because the actions taken on success + /// after a sales and siring auction are quite different. + SiringClockAuction public siringAuction; + + /// @dev Assigns ownership of a specific Kitty to an address. + function _transfer(address _from, address _to, uint256 _tokenId) internal { + // Since the number of kittens is capped to 2^32 we can't overflow this + ownershipTokenCount[_to]++; + // transfer ownership + kittyIndexToOwner[_tokenId] = _to; + // When creating new kittens _from is 0x0, but we can't account that address. + if (_from != address(0)) { + ownershipTokenCount[_from]--; + // once the kitten is transferred also clear sire allowances + delete sireAllowedToAddress[_tokenId]; + // clear any previously approved ownership exchange + delete kittyIndexToApproved[_tokenId]; + } + // Emit the transfer event. + emit Transfer(_from, _to, _tokenId); + } + + /// @dev An internal method that creates a new kitty and stores it. This + /// method doesn't do any checking and should only be called when the + /// input data is known to be valid. Will generate both a Birth event + /// and a Transfer event. + /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) + /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) + /// @param _generation The generation number of this cat, must be computed by caller. + /// @param _genes The kitty's genetic code. + /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) + function _createKitty( + uint256 _matronId, + uint256 _sireId, + uint256 _generation, + uint256 _genes, + address _owner + ) + internal + returns (uint) + { + // These requires are not strictly necessary, our calling code should make + // sure that these conditions are never broken. However! _createKitty() is already + // an expensive call (for storage), and it doesn't hurt to be especially careful + // to ensure our data structures are always valid. + require(_matronId == uint256(uint32(_matronId))); + require(_sireId == uint256(uint32(_sireId))); + require(_generation == uint256(uint16(_generation))); + + // New kitty starts with the same cooldown as parent gen/2 + uint16 cooldownIndex = uint16(_generation / 2); + if (cooldownIndex > 13) { + cooldownIndex = 13; + } + + Kitty memory _kitty = Kitty({ + genes: _genes, + birthTime: uint64(now), + cooldownEndBlock: 0, + matronId: uint32(_matronId), + sireId: uint32(_sireId), + siringWithId: 0, + cooldownIndex: cooldownIndex, + generation: uint16(_generation) + }); + uint256 newKittenId = kitties.push(_kitty) - 1; + + // It's probably never going to happen, 4 billion cats is A LOT, but + // let's just be 100% sure we never let this happen. + require(newKittenId == uint256(uint32(newKittenId))); + + // emit the birth event + emit Birth( + _owner, + newKittenId, + uint256(_kitty.matronId), + uint256(_kitty.sireId), + _kitty.genes + ); + + // This will assign ownership, and also emit the Transfer event as + // per ERC721 draft + _transfer(address(0), _owner, newKittenId); + + return newKittenId; + } + + // Any C-level can fix how many seconds per blocks are currently observed. + function setSecondsPerBlock(uint256 secs) external onlyCLevel { + require(secs < cooldowns[0]); + secondsPerBlock = secs; + } +} + + +/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens +/// @author Dieter Shirley (https://github.com/dete) +contract ERC721 { + // Required methods + function totalSupply() public view returns (uint256 total); + function balanceOf(address _owner) public view returns (uint256 balance); + function ownerOf(uint256 _tokenId) external view returns (address owner); + function approve(address _to, uint256 _tokenId) external; + function transfer(address _to, uint256 _tokenId) external; + function transferFrom(address _from, address _to, uint256 _tokenId) external; + + // Events + event Transfer(address from, address to, uint256 tokenId); + event Approval(address owner, address approved, uint256 tokenId); + + // Optional + // function name() public view returns (string name); + // function symbol() public view returns (string symbol); + // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); + // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); + + // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) + function supportsInterface(bytes4 _interfaceID) external view returns (bool); +} + + +/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 +/// See the KittyCore contract documentation to understand how the various contract facets are arranged. +contract KittyOwnership is ERC721, KittyBase { + + /// @notice Name and symbol of the non fungible token, as defined in ERC721. + string public constant name = "CryptoKitties"; + string public constant symbol = "CK"; + + // The contract that will return kitty metadata + ERC721Metadata public erc721Metadata; + + bytes4 constant InterfaceSignature_ERC165 = + bytes4(keccak256('supportsInterface(bytes4)')); + + bytes4 constant InterfaceSignature_ERC721 = + bytes4(keccak256('name()')) ^ + bytes4(keccak256('symbol()')) ^ + bytes4(keccak256('totalSupply()')) ^ + bytes4(keccak256('balanceOf(address)')) ^ + bytes4(keccak256('ownerOf(uint256)')) ^ + bytes4(keccak256('approve(address,uint256)')) ^ + bytes4(keccak256('transfer(address,uint256)')) ^ + bytes4(keccak256('transferFrom(address,address,uint256)')) ^ + bytes4(keccak256('tokensOfOwner(address)')) ^ + bytes4(keccak256('tokenMetadata(uint256,string)')); + + /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). + /// Returns true for any standardized interfaces implemented by this contract. We implement + /// ERC-165 (obviously!) and ERC-721. + function supportsInterface(bytes4 _interfaceID) external view returns (bool) + { + // DEBUG ONLY + //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); + + return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); + } + + /// @dev Set the address of the sibling contract that tracks metadata. + /// CEO only. + function setMetadataAddress(address _contractAddress) public onlyCEO { + erc721Metadata = ERC721Metadata(_contractAddress); + } + + // Internal utility functions: These functions all assume that their input arguments + // are valid. We leave it to public methods to sanitize their inputs and follow + // the required logic. + + /// @dev Checks if a given address is the current owner of a particular Kitty. + /// @param _claimant the address we are validating against. + /// @param _tokenId kitten id, only valid when > 0 + function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { + return kittyIndexToOwner[_tokenId] == _claimant; + } + + /// @dev Checks if a given address currently has transferApproval for a particular Kitty. + /// @param _claimant the address we are confirming kitten is approved for. + /// @param _tokenId kitten id, only valid when > 0 + function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { + return kittyIndexToApproved[_tokenId] == _claimant; + } + + /// @dev Marks an address as being approved for transferFrom(), overwriting any previous + /// approval. Setting _approved to address(0) clears all transfer approval. + /// NOTE: _approve() does NOT send the Approval event. This is intentional because + /// _approve() and transferFrom() are used together for putting Kitties on auction, and + /// there is no value in spamming the log with Approval events in that case. + function _approve(uint256 _tokenId, address _approved) internal { + kittyIndexToApproved[_tokenId] = _approved; + } + + /// @notice Returns the number of Kitties owned by a specific address. + /// @param _owner The owner address to check. + /// @dev Required for ERC-721 compliance + function balanceOf(address _owner) public view returns (uint256 count) { + return ownershipTokenCount[_owner]; + } + + /// @notice Transfers a Kitty to another address. If transferring to a smart + /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or + /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. + /// @param _to The address of the recipient, can be a user or contract. + /// @param _tokenId The ID of the Kitty to transfer. + /// @dev Required for ERC-721 compliance. + function transfer( + address _to, + uint256 _tokenId + ) + external + whenNotPaused + { + // Safety check to prevent against an unexpected 0x0 default. + require(_to != address(0)); + // Disallow transfers to this contract to prevent accidental misuse. + // The contract should never own any kitties (except very briefly + // after a gen0 cat is created and before it goes on auction). + require(_to != address(this)); + // Disallow transfers to the auction contracts to prevent accidental + // misuse. Auction contracts should only take ownership of kitties + // through the allow + transferFrom flow. + require(_to != address(saleAuction)); + require(_to != address(siringAuction)); + + // You can only send your own cat. + require(_owns(msg.sender, _tokenId)); + + // Reassign ownership, clear pending approvals, emit Transfer event. + _transfer(msg.sender, _to, _tokenId); + } + + /// @notice Grant another address the right to transfer a specific Kitty via + /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. + /// @param _to The address to be granted transfer approval. Pass address(0) to + /// clear all approvals. + /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. + /// @dev Required for ERC-721 compliance. + function approve( + address _to, + uint256 _tokenId + ) + external + whenNotPaused + { + // Only an owner can grant transfer approval. + require(_owns(msg.sender, _tokenId)); + + // Register the approval (replacing any previous approval). + _approve(_tokenId, _to); + + // Emit approval event. + emit Approval(msg.sender, _to, _tokenId); + } + + /// @notice Transfer a Kitty owned by another address, for which the calling address + /// has previously been granted transfer approval by the owner. + /// @param _from The address that owns the Kitty to be transfered. + /// @param _to The address that should take ownership of the Kitty. Can be any address, + /// including the caller. + /// @param _tokenId The ID of the Kitty to be transferred. + /// @dev Required for ERC-721 compliance. + function transferFrom( + address _from, + address _to, + uint256 _tokenId + ) + external + whenNotPaused + { + // Safety check to prevent against an unexpected 0x0 default. + require(_to != address(0)); + // Disallow transfers to this contract to prevent accidental misuse. + // The contract should never own any kitties (except very briefly + // after a gen0 cat is created and before it goes on auction). + require(_to != address(this)); + // Check for approval and valid ownership + require(_approvedFor(msg.sender, _tokenId)); + require(_owns(_from, _tokenId)); + + // Reassign ownership (also clears pending approvals and emits Transfer event). + _transfer(_from, _to, _tokenId); + } + + /// @notice Returns the total number of Kitties currently in existence. + /// @dev Required for ERC-721 compliance. + function totalSupply() public view returns (uint) { + return kitties.length - 1; + } + + /// @notice Returns the address currently assigned ownership of a given Kitty. + /// @dev Required for ERC-721 compliance. + function ownerOf(uint256 _tokenId) + external + view + returns (address owner) + { + owner = kittyIndexToOwner[_tokenId]; + + require(owner != address(0)); + } + + /// @notice Returns a list of all Kitty IDs assigned to an address. + /// @param _owner The owner whose Kitties we are interested in. + /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly + /// expensive (it walks the entire Kitty array looking for cats belonging to owner), + /// but it also returns a dynamic array, which is only supported for web3 calls, and + /// not contract-to-contract calls. + function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { + uint256 tokenCount = balanceOf(_owner); + + if (tokenCount == 0) { + // Return an empty array + return new uint256[](0); + } else { + uint256[] memory result = new uint256[](tokenCount); + uint256 totalCats = totalSupply(); + uint256 resultIndex = 0; + + // We count on the fact that all cats have IDs starting at 1 and increasing + // sequentially up to the totalCat count. + uint256 catId; + + for (catId = 1; catId <= totalCats; catId++) { + if (kittyIndexToOwner[catId] == _owner) { + result[resultIndex] = catId; + resultIndex++; + } + } + + return result; + } + } + + /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) + /// This method is licenced under the Apache License. + /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol + function _memcpy(uint _dest, uint _src, uint _len) private view { + // Copy word-length chunks while possible + for(; _len >= 32; _len -= 32) { + assembly { + mstore(_dest, mload(_src)) + } + _dest += 32; + _src += 32; + } + + // Copy remaining bytes + uint256 mask = 256 ** (32 - _len) - 1; + assembly { + let srcpart := and(mload(_src), not(mask)) + let destpart := and(mload(_dest), mask) + mstore(_dest, or(destpart, srcpart)) + } + } + + /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) + /// This method is licenced under the Apache License. + /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol + function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { + string memory outputString = new string(_stringLength); + uint256 outputPtr; + uint256 bytesPtr; + + assembly { + outputPtr := add(outputString, 32) + bytesPtr := _rawBytes + } + + _memcpy(outputPtr, bytesPtr, _stringLength); + + return outputString; + } + + /// @notice Returns a URI pointing to a metadata package for this token conforming to + /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) + /// @param _tokenId The ID number of the Kitty whose metadata should be returned. + function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { + require( address(erc721Metadata) != address(0)); + bytes32[4] memory buffer; + uint256 count; + (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); + + return _toString(buffer, count); + } +} + + + + +/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. +contract KittyBreeding is KittyOwnership { + + /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy + /// timer begins for the matron. + event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); + + /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards + /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by + /// the COO role as the gas price changes. + uint256 public autoBirthFee = 2 sun; + + // Keeps track of number of pregnant kitties. + uint256 public pregnantKitties; + + /// @dev The address of the sibling contract that is used to implement the sooper-sekret + /// genetic combination algorithm. + GeneScienceInterface public geneScience; + + /// @dev Update the address of the genetic contract, can only be called by the CEO. + /// @param _address An address of a GeneScience contract instance to be used from this point forward. + function setGeneScienceAddress(address _address) external onlyCEO { + GeneScienceInterface candidateContract = GeneScienceInterface(_address); + + // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 + require(candidateContract.isGeneScience()); + + // Set the new contract address + geneScience = candidateContract; + } + + /// @dev Checks that a given kitten is able to breed. Requires that the + /// current cooldown is finished (for sires) and also checks that there is + /// no pending pregnancy. + function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { + // In addition to checking the cooldownEndBlock, we also need to check to see if + // the cat has a pending birth; there can be some period of time between the end + // of the pregnacy timer and the birth event. + return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); + } + + /// @dev Check if a sire has authorized breeding with this matron. True if both sire + /// and matron have the same owner, or if the sire has given siring permission to + /// the matron's owner (via approveSiring()). + function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { + address matronOwner = kittyIndexToOwner[_matronId]; + address sireOwner = kittyIndexToOwner[_sireId]; + + // Siring is okay if they have same owner, or if the matron's owner was given + // permission to breed with this sire. + return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); + } + + /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. + /// Also increments the cooldownIndex (unless it has hit the cap). + /// @param _kitten A reference to the Kitty in storage which needs its timer started. + function _triggerCooldown(Kitty storage _kitten) internal { + // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). + _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); + + // Increment the breeding count, clamping it at 13, which is the length of the + // cooldowns array. We could check the array size dynamically, but hard-coding + // this as a constant saves gas. Yay, Solidity! + if (_kitten.cooldownIndex < 13) { + _kitten.cooldownIndex += 1; + } + } + + /// @notice Grants approval to another user to sire with one of your Kitties. + /// @param _addr The address that will be able to sire with your Kitty. Set to + /// address(0) to clear all siring approvals for this Kitty. + /// @param _sireId A Kitty that you own that _addr will now be able to sire with. + function approveSiring(address _addr, uint256 _sireId) + external + whenNotPaused + { + require(_owns(msg.sender, _sireId)); + sireAllowedToAddress[_sireId] = _addr; + } + + /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only + /// be called by the COO address. (This fee is used to offset the gas cost incurred + /// by the autobirth daemon). + function setAutoBirthFee(uint256 val) external onlyCOO { + autoBirthFee = val; + } + + /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation + /// period has passed. + function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { + return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); + } + + /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or + /// in the middle of a siring cooldown). + /// @param _kittyId reference the id of the kitten, any user can inquire about it + function isReadyToBreed(uint256 _kittyId) + public + view + returns (bool) + { + require(_kittyId > 0); + Kitty storage kit = kitties[_kittyId]; + return _isReadyToBreed(kit); + } + + /// @dev Checks whether a kitty is currently pregnant. + /// @param _kittyId reference the id of the kitten, any user can inquire about it + function isPregnant(uint256 _kittyId) + public + view + returns (bool) + { + require(_kittyId > 0); + // A kitty is pregnant if and only if this field is set + return kitties[_kittyId].siringWithId != 0; + } + + /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT + /// check ownership permissions (that is up to the caller). + /// @param _matron A reference to the Kitty struct of the potential matron. + /// @param _matronId The matron's ID. + /// @param _sire A reference to the Kitty struct of the potential sire. + /// @param _sireId The sire's ID + function _isValidMatingPair( + Kitty storage _matron, + uint256 _matronId, + Kitty storage _sire, + uint256 _sireId + ) + private + view + returns(bool) + { + // A Kitty can't breed with itself! + if (_matronId == _sireId) { + return false; + } + + // Kitties can't breed with their parents. + if (_matron.matronId == _sireId || _matron.sireId == _sireId) { + return false; + } + if (_sire.matronId == _matronId || _sire.sireId == _matronId) { + return false; + } + + // We can short circuit the sibling check (below) if either cat is + // gen zero (has a matron ID of zero). + if (_sire.matronId == 0 || _matron.matronId == 0) { + return true; + } + + // Kitties can't breed with full or half siblings. + if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { + return false; + } + if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { + return false; + } + + // Everything seems cool! Let's get DTF. + return true; + } + + /// @dev Internal check to see if a given sire and matron are a valid mating pair for + /// breeding via auction (i.e. skips ownership and siring approval checks). + function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) + internal + view + returns (bool) + { + Kitty storage matron = kitties[_matronId]; + Kitty storage sire = kitties[_sireId]; + return _isValidMatingPair(matron, _matronId, sire, _sireId); + } + + /// @notice Checks to see if two cats can breed together, including checks for + /// ownership and siring approvals. Does NOT check that both cats are ready for + /// breeding (i.e. breedWith could still fail until the cooldowns are finished). + /// TODO: Shouldn't this check pregnancy and cooldowns?!? + /// @param _matronId The ID of the proposed matron. + /// @param _sireId The ID of the proposed sire. + function canBreedWith(uint256 _matronId, uint256 _sireId) + external + view + returns(bool) + { + require(_matronId > 0); + require(_sireId > 0); + Kitty storage matron = kitties[_matronId]; + Kitty storage sire = kitties[_sireId]; + return _isValidMatingPair(matron, _matronId, sire, _sireId) && + _isSiringPermitted(_sireId, _matronId); + } + + /// @dev Internal utility function to initiate breeding, assumes that all breeding + /// requirements have been checked. + function _breedWith(uint256 _matronId, uint256 _sireId) internal { + // Grab a reference to the Kitties from storage. + Kitty storage sire = kitties[_sireId]; + Kitty storage matron = kitties[_matronId]; + + // Mark the matron as pregnant, keeping track of who the sire is. + matron.siringWithId = uint32(_sireId); + + // Trigger the cooldown for both parents. + _triggerCooldown(sire); + _triggerCooldown(matron); + + // Clear siring permission for both parents. This may not be strictly necessary + // but it's likely to avoid confusion! + delete sireAllowedToAddress[_matronId]; + delete sireAllowedToAddress[_sireId]; + + // Every time a kitty gets pregnant, counter is incremented. + pregnantKitties++; + + // Emit the pregnancy event. + emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); + } + + /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you + /// have previously been given Siring approval. Will either make your cat pregnant, or will + /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() + /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) + /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) + function breedWithAuto(uint256 _matronId, uint256 _sireId) + external + payable + whenNotPaused + { + // Checks for payment. + require(msg.value >= autoBirthFee); + + // Caller must own the matron. + require(_owns(msg.sender, _matronId)); + + // Neither sire nor matron are allowed to be on auction during a normal + // breeding operation, but we don't need to check that explicitly. + // For matron: The caller of this function can't be the owner of the matron + // because the owner of a Kitty on auction is the auction house, and the + // auction house will never call breedWith(). + // For sire: Similarly, a sire on auction will be owned by the auction house + // and the act of transferring ownership will have cleared any oustanding + // siring approval. + // Thus we don't need to spend gas explicitly checking to see if either cat + // is on auction. + + // Check that matron and sire are both owned by caller, or that the sire + // has given siring permission to caller (i.e. matron's owner). + // Will fail for _sireId = 0 + require(_isSiringPermitted(_sireId, _matronId)); + + // Grab a reference to the potential matron + Kitty storage matron = kitties[_matronId]; + + // Make sure matron isn't pregnant, or in the middle of a siring cooldown + require(_isReadyToBreed(matron)); + + // Grab a reference to the potential sire + Kitty storage sire = kitties[_sireId]; + + // Make sure sire isn't pregnant, or in the middle of a siring cooldown + require(_isReadyToBreed(sire)); + + // Test that these cats are a valid mating pair. + require(_isValidMatingPair( + matron, + _matronId, + sire, + _sireId + )); + + // All checks passed, kitty gets pregnant! + _breedWith(_matronId, _sireId); + } + + /// @notice Have a pregnant Kitty give birth! + /// @param _matronId A Kitty ready to give birth. + /// @return The Kitty ID of the new kitten. + /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, + /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned + /// to the current owner of the matron. Upon successful completion, both the matron and the + /// new kitten will be ready to breed again. Note that anyone can call this function (if they + /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. + function giveBirth(uint256 _matronId) + external + whenNotPaused + returns(uint256) + { + // Grab a reference to the matron in storage. + Kitty storage matron = kitties[_matronId]; + + // Check that the matron is a valid cat. + require(matron.birthTime != 0); + + // Check that the matron is pregnant, and that its time has come! + require(_isReadyToGiveBirth(matron)); + + // Grab a reference to the sire in storage. + uint256 sireId = matron.siringWithId; + Kitty storage sire = kitties[sireId]; + + // Determine the higher generation number of the two parents + uint16 parentGen = matron.generation; + if (sire.generation > matron.generation) { + parentGen = sire.generation; + } + + // Call the sooper-sekret gene mixing operation. + uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); + + // Make the new kitten! + address owner = kittyIndexToOwner[_matronId]; + uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); + + // Clear the reference to sire from the matron (REQUIRED! Having siringWithId + // set is what marks a matron as being pregnant.) + delete matron.siringWithId; + + // Every time a kitty gives birth counter is decremented. + pregnantKitties--; + + // Send the balance fee to the person who made birth happen. + msg.sender.transfer(autoBirthFee); + + // return the new kitten's ID + return kittenId; + } +} + + + +/// @title Handles creating auctions for sale and siring of kitties. +/// This wrapper of ReverseAuction exists only so that users can create +/// auctions with only one transaction. +contract KittyAuction is KittyBreeding { + + // @notice The auction contract variables are defined in KittyBase to allow + // us to refer to them in KittyOwnership to prevent accidental transfers. + // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. + // `siringAuction` refers to the auction for siring rights of kitties. + + /// @dev Sets the reference to the sale auction. + /// @param _address - Address of sale contract. + function setSaleAuctionAddress(address _address) external onlyCEO { + SaleClockAuction candidateContract = SaleClockAuction(_address); + + // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 + require(candidateContract.isSaleClockAuction()); + + // Set the new contract address + saleAuction = candidateContract; + } + + /// @dev Sets the reference to the siring auction. + /// @param _address - Address of siring contract. + function setSiringAuctionAddress(address _address) external onlyCEO { + SiringClockAuction candidateContract = SiringClockAuction(_address); + + // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 + require(candidateContract.isSiringClockAuction()); + + // Set the new contract address + siringAuction = candidateContract; + } + + /// @dev Put a kitty up for auction. + /// Does some ownership trickery to create auctions in one tx. + function createSaleAuction( + uint256 _kittyId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration + ) + external + whenNotPaused + { + // Auction contract checks input sizes + // If kitty is already on any auction, this will throw + // because it will be owned by the auction contract. + require(_owns(msg.sender, _kittyId)); + // Ensure the kitty is not pregnant to prevent the auction + // contract accidentally receiving ownership of the child. + // NOTE: the kitty IS allowed to be in a cooldown. + require(!isPregnant(_kittyId)); + _approve(_kittyId, address(saleAuction)); + // Sale auction throws if inputs are invalid and clears + // transfer and sire approval after escrowing the kitty. + saleAuction.createAuction( + _kittyId, + _startingPrice, + _endingPrice, + _duration, + msg.sender + ); + } + + /// @dev Put a kitty up for auction to be sire. + /// Performs checks to ensure the kitty can be sired, then + /// delegates to reverse auction. + function createSiringAuction( + uint256 _kittyId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration + ) + external + whenNotPaused + { + // Auction contract checks input sizes + // If kitty is already on any auction, this will throw + // because it will be owned by the auction contract. + require(_owns(msg.sender, _kittyId)); + require(isReadyToBreed(_kittyId)); + _approve(_kittyId, address(siringAuction)); + // Siring auction throws if inputs are invalid and clears + // transfer and sire approval after escrowing the kitty. + siringAuction.createAuction( + _kittyId, + _startingPrice, + _endingPrice, + _duration, + msg.sender + ); + } + + /// @dev Completes a siring auction by bidding. + /// Immediately breeds the winning matron with the sire on auction. + /// @param _sireId - ID of the sire on auction. + /// @param _matronId - ID of the matron owned by the bidder. + function bidOnSiringAuction( + uint256 _sireId, + uint256 _matronId + ) + external + payable + whenNotPaused + { + // Auction contract checks input sizes + require(_owns(msg.sender, _matronId)); + require(isReadyToBreed(_matronId)); + require(_canBreedWithViaAuction(_matronId, _sireId)); + + // Define the current price of the auction. + uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); + require(msg.value >= currentPrice + autoBirthFee); + + // Siring auction will throw if the bid fails. + siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); + _breedWith(uint32(_matronId), uint32(_sireId)); + } + + /// @dev Transfers the balance of the sale auction contract + /// to the KittyCore contract. We use two-step withdrawal to + /// prevent two transfer calls in the auction bid function. + function withdrawAuctionBalances() external onlyCLevel { + saleAuction.withdrawBalance(); + siringAuction.withdrawBalance(); + } +} + + +/// @title all functions related to creating kittens +contract KittyMinting is KittyAuction { + + // Limits the number of cats the contract owner can ever create. + uint256 public constant PROMO_CREATION_LIMIT = 5000; + uint256 public constant GEN0_CREATION_LIMIT = 45000; + + // Constants for gen0 auctions. + uint256 public constant GEN0_STARTING_PRICE = 10 sun; + uint256 public constant GEN0_AUCTION_DURATION = 1 days; + + // Counts the number of cats the contract owner has created. + uint256 public promoCreatedCount; + uint256 public gen0CreatedCount; + + /// @dev we can create promo kittens, up to a limit. Only callable by COO + /// @param _genes the encoded genes of the kitten to be created, any value is accepted + /// @param _owner the future owner of the created kittens. Default to contract COO + function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { + address kittyOwner = _owner; + if (kittyOwner == address(0)) { + kittyOwner = cooAddress; + } + require(promoCreatedCount < PROMO_CREATION_LIMIT); + + promoCreatedCount++; + _createKitty(0, 0, 0, _genes, kittyOwner); + } + + /// @dev Creates a new gen0 kitty with the given genes and + /// creates an auction for it. + function createGen0Auction(uint256 _genes) external onlyCOO { + require(gen0CreatedCount < GEN0_CREATION_LIMIT); + + uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); + _approve(kittyId, address(saleAuction)); + + saleAuction.createAuction( + kittyId, + _computeNextGen0Price(), + 0, + GEN0_AUCTION_DURATION, + address(uint160(address(this))) + ); + + gen0CreatedCount++; + } + + /// @dev Computes the next gen0 auction starting price, given + /// the average of the past 5 prices + 50%. + function _computeNextGen0Price() internal view returns (uint256) { + uint256 avePrice = saleAuction.averageGen0SalePrice(); + + // Sanity check to ensure we don't overflow arithmetic + require(avePrice == uint256(uint128(avePrice))); + + uint256 nextPrice = avePrice + (avePrice / 2); + + // We never auction for less than starting price + if (nextPrice < GEN0_STARTING_PRICE) { + nextPrice = GEN0_STARTING_PRICE; + } + + return nextPrice; + } +} + + + +/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. +/// @author Axiom Zen (https://www.axiomzen.co) +/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. +contract KittyCore is KittyMinting { + + // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, + // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts + // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are + // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping + // them in their own contracts, we can upgrade them without disrupting the main contract that tracks + // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of + // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. + // Don't worry, I'm sure someone will reverse engineer it soon enough! + // + // Secondly, we break the core contract into multiple files using inheritence, one for each major + // facet of functionality of CK. This allows us to keep related code bundled together while still + // avoiding a single giant file with everything in it. The breakdown is as follows: + // + // - KittyBase: This is where we define the most fundamental code shared throughout the core + // functionality. This includes our main data storage, constants and data types, plus + // internal functions for managing these items. + // + // - KittyAccessControl: This contract manages the various addresses and constraints for operations + // that can be executed only by specific roles. Namely CEO, CFO and COO. + // + // - KittyOwnership: This provides the methods required for basic non-fungible token + // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). + // + // - KittyBreeding: This file contains the methods necessary to breed cats together, including + // keeping track of siring offers, and relies on an external genetic combination contract. + // + // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring + // services. The actual auction functionality is handled in two sibling contracts (one + // for sales and one for siring), while auction creation and bidding is mostly mediated + // through this facet of the core contract. + // + // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. + // We can make up to 5000 "promo" cats that can be given away (especially important when + // the community is new), and all others can only be created and then immediately put up + // for auction via an algorithmically determined starting price. Regardless of how they + // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the + // community to breed, breed, breed! + + // Set in case the core contract is broken and an upgrade is required + address public newContractAddress; + + /// @notice Creates the main CryptoKitties smart contract instance. + constructor() public { + // Starts paused. + paused = true; + + // the creator of the contract is the initial CEO + ceoAddress = msg.sender; + + // the creator of the contract is also the initial COO + cooAddress = msg.sender; + + // start with the mythical kitten 0 - so we don't have generation-0 parent issues + _createKitty(0, 0, 0, uint256(-1), address(0)); + } + + /// @dev Used to mark the smart contract as upgraded, in case there is a serious + /// breaking bug. This method does nothing but keep track of the new contract and + /// emit a message indicating that the new address is set. It's up to clients of this + /// contract to update to the new contract address in that case. (This contract will + /// be paused indefinitely if such an upgrade takes place.) + /// @param _v2Address new address + function setNewAddress(address _v2Address) external onlyCEO whenPaused { + // See README.md for updgrade plan + newContractAddress = _v2Address; + emit ContractUpgrade(_v2Address); + } + + /// @notice No tipping! + /// @dev Reject all Ether from being sent here, unless it's from one of the + /// two auction contracts. (Hopefully, we can prevent user accidents.) + function() external payable { + require( + msg.sender == address(saleAuction) || + msg.sender == address(siringAuction) + ); + } + + /// @notice Returns all the relevant information about a specific kitty. + /// @param _id The ID of the kitty of interest. + function getKitty(uint256 _id) + external + view + returns ( + bool isGestating, + bool isReady, + uint256 cooldownIndex, + uint256 nextActionAt, + uint256 siringWithId, + uint256 birthTime, + uint256 matronId, + uint256 sireId, + uint256 generation, + uint256 genes + ) { + Kitty storage kit = kitties[_id]; + + // if this variable is 0 then it's not gestating + isGestating = (kit.siringWithId != 0); + isReady = (kit.cooldownEndBlock <= block.number); + cooldownIndex = uint256(kit.cooldownIndex); + nextActionAt = uint256(kit.cooldownEndBlock); + siringWithId = uint256(kit.siringWithId); + birthTime = uint256(kit.birthTime); + matronId = uint256(kit.matronId); + sireId = uint256(kit.sireId); + generation = uint256(kit.generation); + genes = kit.genes; + } + + /// @dev Override unpause so it requires all external contract addresses + /// to be set before contract can be unpaused. Also, we can't have + /// newContractAddress set either, because then the contract was upgraded. + /// @notice This is public rather than external so we can call super.unpause + /// without using an expensive CALL. + + function unpause() public onlyCEO whenPaused { + require(address(saleAuction) != address(0)); + require(address(siringAuction) != address(0)); + require(address(geneScience) != address(0)); + require(newContractAddress == address(0)); + + // Actually unpause the contract. + super.unpause(); + } + + // @dev Allows the CFO to capture the balance available to the contract. + function withdrawBalance() external onlyCFO { + uint256 balance = address(this).balance; + // Subtract all the currently pregnant kittens we have, plus 1 of margin. + uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; + + if (balance > subtractFees) { + cfoAddress.transfer(balance - subtractFees); + } + } +} + + + + + + + + + + + + + +// // Auction wrapper functions + + +// Auction wrapper functions + + + + + + + +/// @title SEKRETOOOO +contract GeneScienceInterface { + + function isGeneScience() public pure returns (bool){ + return true; + } + + /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor + /// @param genes1 genes of mom + /// @param genes2 genes of sire + /// @return the genes that are supposed to be passed down the child + function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ + + return (genes1+genes2+targetBlock)/2; + + +} +} + + + + + + + + + + + + + + + + +/// @title The external contract that is responsible for generating metadata for the kitties, +/// it has one function that will return the data as bytes. +contract ERC721Metadata { + /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. + function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { + if (_tokenId == 1) { + buffer[0] = "Hello World! :D"; + count = 15; + } else if (_tokenId == 2) { + buffer[0] = "I would definitely choose a medi"; + buffer[1] = "um length string."; + count = 49; + } else if (_tokenId == 3) { + buffer[0] = "Lorem ipsum dolor sit amet, mi e"; + buffer[1] = "st accumsan dapibus augue lorem,"; + buffer[2] = " tristique vestibulum id, libero"; + buffer[3] = " suscipit varius sapien aliquam."; + count = 128; + } + } +} + + + + + + + + + + + + + + + +/// @title Auction Core +/// @dev Contains models, variables, and internal methods for the auction. +/// @notice We omit a fallback function to prevent accidental sends to this contract. +contract ClockAuctionBase { + + // Represents an auction on an NFT + struct Auction { + // Current owner of NFT + address payable seller; + // Price (in wei) at beginning of auction + uint128 startingPrice; + // Price (in wei) at end of auction + uint128 endingPrice; + // Duration (in seconds) of auction + uint64 duration; + // Time when auction started + // NOTE: 0 if this auction has been concluded + uint64 startedAt; + } + + // Reference to contract tracking NFT ownership + ERC721 public nonFungibleContract; + + // Cut owner takes on each auction, measured in basis points (1/100 of a percent). + // Values 0-10,000 map to 0%-100% + uint256 public ownerCut; + + // Map from token ID to their corresponding auction. + mapping (uint256 => Auction) tokenIdToAuction; + + event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); + event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); + event AuctionCancelled(uint256 tokenId); + + /// @dev Returns true if the claimant owns the token. + /// @param _claimant - Address claiming to own the token. + /// @param _tokenId - ID of token whose ownership to verify. + function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { + return (nonFungibleContract.ownerOf(_tokenId) == _claimant); + } + + /// @dev Escrows the NFT, assigning ownership to this contract. + /// Throws if the escrow fails. + /// @param _owner - Current owner address of token to escrow. + /// @param _tokenId - ID of token whose approval to verify. + function _escrow(address _owner, uint256 _tokenId) internal { + // it will throw if transfer fails + nonFungibleContract.transferFrom(_owner, address(this), _tokenId); + } + + /// @dev Transfers an NFT owned by this contract to another address. + /// Returns true if the transfer succeeds. + /// @param _receiver - Address to transfer NFT to. + /// @param _tokenId - ID of token to transfer. + function _transfer(address _receiver, uint256 _tokenId) internal { + // it will throw if transfer fails + nonFungibleContract.transfer(_receiver, _tokenId); + } + + /// @dev Adds an auction to the list of open auctions. Also fires the + /// AuctionCreated event. + /// @param _tokenId The ID of the token to be put on auction. + /// @param _auction Auction to add. + function _addAuction(uint256 _tokenId, Auction memory _auction) internal { + // Require that all auctions have a duration of + // at least one minute. (Keeps our math from getting hairy!) + require(_auction.duration >= 1 minutes); + + tokenIdToAuction[_tokenId] = _auction; + + emit AuctionCreated( + uint256(_tokenId), + uint256(_auction.startingPrice), + uint256(_auction.endingPrice), + uint256(_auction.duration) + ); + } + + /// @dev Cancels an auction unconditionally. + function _cancelAuction(uint256 _tokenId, address _seller) internal { + _removeAuction(_tokenId); + _transfer(_seller, _tokenId); + emit AuctionCancelled(_tokenId); + } + + /// @dev Computes the price and transfers winnings. + /// Does NOT transfer ownership of token. + function _bid(uint256 _tokenId, uint256 _bidAmount) + internal + returns (uint256) + { + // Get a reference to the auction struct + Auction storage auction = tokenIdToAuction[_tokenId]; + + // Explicitly check that this auction is currently live. + // (Because of how Ethereum mappings work, we can't just count + // on the lookup above failing. An invalid _tokenId will just + // return an auction object that is all zeros.) + require(_isOnAuction(auction)); + + // Check that the bid is greater than or equal to the current price + uint256 price = _currentPrice(auction); + require(_bidAmount >= price); + + // Grab a reference to the seller before the auction struct + // gets deleted. + address payable seller = auction.seller; + + // The bid is good! Remove the auction before sending the fees + // to the sender so we can't have a reentrancy attack. + _removeAuction(_tokenId); + + // Transfer proceeds to seller (if there are any!) + if (price > 0) { + // Calculate the auctioneer's cut. + // (NOTE: _computeCut() is guaranteed to return a + // value <= price, so this subtraction can't go negative.) + uint256 auctioneerCut = _computeCut(price); + uint256 sellerProceeds = price - auctioneerCut; + + // NOTE: Doing a transfer() in the middle of a complex + // method like this is generally discouraged because of + // reentrancy attacks and DoS attacks if the seller is + // a contract with an invalid fallback function. We explicitly + // guard against reentrancy attacks by removing the auction + // before calling transfer(), and the only thing the seller + // can DoS is the sale of their own asset! (And if it's an + // accident, they can call cancelAuction(). ) + seller.transfer(sellerProceeds); + } + + // Calculate any excess funds included with the bid. If the excess + // is anything worth worrying about, transfer it back to bidder. + // NOTE: We checked above that the bid amount is greater than or + // equal to the price so this cannot underflow. + uint256 bidExcess = _bidAmount - price; + + // Return the funds. Similar to the previous transfer, this is + // not susceptible to a re-entry attack because the auction is + // removed before any transfers occur. + msg.sender.transfer(bidExcess); + + // Tell the world! + emit AuctionSuccessful(_tokenId, price, msg.sender); + + return price; + } + + /// @dev Removes an auction from the list of open auctions. + /// @param _tokenId - ID of NFT on auction. + function _removeAuction(uint256 _tokenId) internal { + delete tokenIdToAuction[_tokenId]; + } + + /// @dev Returns true if the NFT is on auction. + /// @param _auction - Auction to check. + function _isOnAuction(Auction storage _auction) internal view returns (bool) { + return (_auction.startedAt > 0); + } + + /// @dev Returns current price of an NFT on auction. Broken into two + /// functions (this one, that computes the duration from the auction + /// structure, and the other that does the price computation) so we + /// can easily test that the price computation works correctly. + function _currentPrice(Auction storage _auction) + internal + view + returns (uint256) + { + uint256 secondsPassed = 0; + + // A bit of insurance against negative values (or wraparound). + // Probably not necessary (since Ethereum guarnatees that the + // now variable doesn't ever go backwards). + if (now > _auction.startedAt) { + secondsPassed = now - _auction.startedAt; + } + + return _computeCurrentPrice( + _auction.startingPrice, + _auction.endingPrice, + _auction.duration, + secondsPassed + ); + } + + /// @dev Computes the current price of an auction. Factored out + /// from _currentPrice so we can run extensive unit tests. + /// When testing, make this function public and turn on + /// `Current price computation` test suite. + function _computeCurrentPrice( + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration, + uint256 _secondsPassed + ) + internal + pure + returns (uint256) + { + // NOTE: We don't use SafeMath (or similar) in this function because + // all of our public functions carefully cap the maximum values for + // time (at 64-bits) and currency (at 128-bits). _duration is + // also known to be non-zero (see the require() statement in + // _addAuction()) + if (_secondsPassed >= _duration) { + // We've reached the end of the dynamic pricing portion + // of the auction, just return the end price. + return _endingPrice; + } else { + // Starting price can be higher than ending price (and often is!), so + // this delta can be negative. + int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); + + // This multiplication can't overflow, _secondsPassed will easily fit within + // 64-bits, and totalPriceChange will easily fit within 128-bits, their product + // will always fit within 256-bits. + int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); + + // currentPriceChange can be negative, but if so, will have a magnitude + // less that _startingPrice. Thus, this result will always end up positive. + int256 currentPrice = int256(_startingPrice) + currentPriceChange; + + return uint256(currentPrice); + } + } + + /// @dev Computes owner's cut of a sale. + /// @param _price - Sale price of NFT. + function _computeCut(uint256 _price) internal view returns (uint256) { + // NOTE: We don't use SafeMath (or similar) in this function because + // all of our entry functions carefully cap the maximum values for + // currency (at 128-bits), and ownerCut <= 10000 (see the require() + // statement in the ClockAuction constructor). The result of this + // function is always guaranteed to be <= _price. + return _price * ownerCut / 10000; + } + +} + + + + + + + +/** + * @title Pausable + * @dev Base contract which allows children to implement an emergency stop mechanism. + */ +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + /** + * @dev modifier to allow actions only when the contract IS paused + */ + modifier whenNotPaused() { + require(!paused); + _; + } + + /** + * @dev modifier to allow actions only when the contract IS NOT paused + */ + modifier whenPaused { + require(paused); + _; + } + + /** + * @dev called by the owner to pause, triggers stopped state + */ + function pause() onlyOwner whenNotPaused public returns (bool) { + paused = true; + emit Pause(); + return true; + } + + /** + * @dev called by the owner to unpause, returns to normal state + */ + function unpause() onlyOwner whenPaused public returns (bool) { + paused = false; + emit Unpause(); + return true; + } +} + + +/// @title Clock auction for non-fungible tokens. +/// @notice We omit a fallback function to prevent accidental sends to this contract. +contract ClockAuction is Pausable, ClockAuctionBase { + + /// @dev The ERC-165 interface signature for ERC-721. + /// Ref: https://github.com/ethereum/EIPs/issues/165 + /// Ref: https://github.com/ethereum/EIPs/issues/721 + bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); + + /// @dev Constructor creates a reference to the NFT ownership contract + /// and verifies the owner cut is in the valid range. + /// @param _nftAddress - address of a deployed contract implementing + /// the Nonfungible Interface. + /// @param _cut - percent cut the owner takes on each auction, must be + /// between 0-10,000. + constructor(address _nftAddress, uint256 _cut) public { + require(_cut <= 10000); + ownerCut = _cut; + + ERC721 candidateContract = ERC721(_nftAddress); + require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); + nonFungibleContract = candidateContract; + } + + /// @dev Remove all Ether from the contract, which is the owner's cuts + /// as well as any Ether sent directly to the contract address. + /// Always transfers to the NFT contract, but can be called either by + /// the owner or the NFT contract. + function withdrawBalance() external { + address payable nftAddress = address(uint160(address(nonFungibleContract))); + + require( + msg.sender == owner || + msg.sender == nftAddress + ); + // We are using this boolean method to make sure that even if one fails it will still work + bool res = nftAddress.send(address(this).balance); + } + + /// @dev Creates and begins a new auction. + /// @param _tokenId - ID of token to auction, sender must be owner. + /// @param _startingPrice - Price of item (in wei) at beginning of auction. + /// @param _endingPrice - Price of item (in wei) at end of auction. + /// @param _duration - Length of time to move between starting + /// price and ending price (in seconds). + /// @param _seller - Seller, if not the message sender + function createAuction( + uint256 _tokenId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration, + address payable _seller + ) + external + whenNotPaused + { + // Sanity check that no inputs overflow how many bits we've allocated + // to store them in the auction struct. + require(_startingPrice == uint256(uint128(_startingPrice))); + require(_endingPrice == uint256(uint128(_endingPrice))); + require(_duration == uint256(uint64(_duration))); + + require(_owns(msg.sender, _tokenId)); + _escrow(msg.sender, _tokenId); + Auction memory auction = Auction( + _seller, + uint128(_startingPrice), + uint128(_endingPrice), + uint64(_duration), + uint64(now) + ); + _addAuction(_tokenId, auction); + } + + /// @dev Bids on an open auction, completing the auction and transferring + /// ownership of the NFT if enough Ether is supplied. + /// @param _tokenId - ID of token to bid on. + function bid(uint256 _tokenId) + external + payable + whenNotPaused + { + // _bid will throw if the bid or funds transfer fails + _bid(_tokenId, msg.value); + _transfer(msg.sender, _tokenId); + } + + /// @dev Cancels an auction that hasn't been won yet. + /// Returns the NFT to original owner. + /// @notice This is a state-modifying function that can + /// be called while the contract is paused. + /// @param _tokenId - ID of token on auction + function cancelAuction(uint256 _tokenId) + external + { + Auction storage auction = tokenIdToAuction[_tokenId]; + require(_isOnAuction(auction)); + address seller = auction.seller; + require(msg.sender == seller); + _cancelAuction(_tokenId, seller); + } + + /// @dev Cancels an auction when the contract is paused. + /// Only the owner may do this, and NFTs are returned to + /// the seller. This should only be used in emergencies. + /// @param _tokenId - ID of the NFT on auction to cancel. + function cancelAuctionWhenPaused(uint256 _tokenId) + whenPaused + onlyOwner + external + { + Auction storage auction = tokenIdToAuction[_tokenId]; + require(_isOnAuction(auction)); + _cancelAuction(_tokenId, auction.seller); + } + + /// @dev Returns auction info for an NFT on auction. + /// @param _tokenId - ID of NFT on auction. + function getAuction(uint256 _tokenId) + external + view + returns + ( + address seller, + uint256 startingPrice, + uint256 endingPrice, + uint256 duration, + uint256 startedAt + ) { + Auction storage auction = tokenIdToAuction[_tokenId]; + require(_isOnAuction(auction)); + return ( + auction.seller, + auction.startingPrice, + auction.endingPrice, + auction.duration, + auction.startedAt + ); + } + + /// @dev Returns the current price of an auction. + /// @param _tokenId - ID of the token price we are checking. + function getCurrentPrice(uint256 _tokenId) + external + view + returns (uint256) + { + Auction storage auction = tokenIdToAuction[_tokenId]; + require(_isOnAuction(auction)); + return _currentPrice(auction); + } + +} + + +/// @title Reverse auction modified for siring +/// @notice We omit a fallback function to prevent accidental sends to this contract. +contract SiringClockAuction is ClockAuction { + + // @dev Sanity check that allows us to ensure that we are pointing to the + // right auction in our setSiringAuctionAddress() call. + bool public isSiringClockAuction = true; + + // Delegate constructor + constructor(address _nftAddr, uint256 _cut) public + ClockAuction(_nftAddr, _cut) {} + + /// @dev Creates and begins a new auction. Since this function is wrapped, + /// require sender to be KittyCore contract. + /// @param _tokenId - ID of token to auction, sender must be owner. + /// @param _startingPrice - Price of item (in wei) at beginning of auction. + /// @param _endingPrice - Price of item (in wei) at end of auction. + /// @param _duration - Length of auction (in seconds). + /// @param _seller - Seller, if not the message sender + function createAuction( + uint256 _tokenId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration, + address payable _seller + ) + external + { + // Sanity check that no inputs overflow how many bits we've allocated + // to store them in the auction struct. + require(_startingPrice == uint256(uint128(_startingPrice))); + require(_endingPrice == uint256(uint128(_endingPrice))); + require(_duration == uint256(uint64(_duration))); + + require(msg.sender == address(nonFungibleContract)); + _escrow(_seller, _tokenId); + Auction memory auction = Auction( + _seller, + uint128(_startingPrice), + uint128(_endingPrice), + uint64(_duration), + uint64(now) + ); + _addAuction(_tokenId, auction); + } + + /// @dev Places a bid for siring. Requires the sender + /// is the KittyCore contract because all bid methods + /// should be wrapped. Also returns the kitty to the + /// seller rather than the winner. + function bid(uint256 _tokenId) + external + payable + { + require(msg.sender == address(nonFungibleContract)); + address seller = tokenIdToAuction[_tokenId].seller; + // _bid checks that token ID is valid and will throw if bid fails + _bid(_tokenId, msg.value); + // We transfer the kitty back to the seller, the winner will get + // the offspring + _transfer(seller, _tokenId); + } + +} + + + + + +/// @title Clock auction modified for sale of kitties +/// @notice We omit a fallback function to prevent accidental sends to this contract. +contract SaleClockAuction is ClockAuction { + + // @dev Sanity check that allows us to ensure that we are pointing to the + // right auction in our setSaleAuctionAddress() call. + bool public isSaleClockAuction = true; + + // Tracks last 5 sale price of gen0 kitty sales + uint256 public gen0SaleCount; + uint256[5] public lastGen0SalePrices; + + // Delegate constructor + constructor(address _nftAddr, uint256 _cut) public + ClockAuction(_nftAddr, _cut) {} + + /// @dev Creates and begins a new auction. + /// @param _tokenId - ID of token to auction, sender must be owner. + /// @param _startingPrice - Price of item (in wei) at beginning of auction. + /// @param _endingPrice - Price of item (in wei) at end of auction. + /// @param _duration - Length of auction (in seconds). + /// @param _seller - Seller, if not the message sender + function createAuction( + uint256 _tokenId, + uint256 _startingPrice, + uint256 _endingPrice, + uint256 _duration, + address payable _seller + ) + external + { + // Sanity check that no inputs overflow how many bits we've allocated + // to store them in the auction struct. + require(_startingPrice == uint256(uint128(_startingPrice))); + require(_endingPrice == uint256(uint128(_endingPrice))); + require(_duration == uint256(uint64(_duration))); + + require(msg.sender == address(nonFungibleContract)); + _escrow(_seller, _tokenId); + Auction memory auction = Auction( + _seller, + uint128(_startingPrice), + uint128(_endingPrice), + uint64(_duration), + uint64(now) + ); + _addAuction(_tokenId, auction); + } + + /// @dev Updates lastSalePrice if seller is the nft contract + /// Otherwise, works the same as default bid method. + function bid(uint256 _tokenId) + external + payable + { + // _bid verifies token ID size + address seller = tokenIdToAuction[_tokenId].seller; + uint256 price = _bid(_tokenId, msg.value); + _transfer(msg.sender, _tokenId); + + // If not a gen0 auction, exit + if (seller == address(nonFungibleContract)) { + // Track gen0 sale prices + lastGen0SalePrices[gen0SaleCount % 5] = price; + gen0SaleCount++; + } + } + + function averageGen0SalePrice() external view returns (uint256) { + uint256 sum = 0; + for (uint256 i = 0; i < 5; i++) { + sum += lastGen0SalePrices[i]; + } + return sum / 5; + } + +} + + + + + + + diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario012.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario012.sol new file mode 100644 index 00000000000..7bed08dd111 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractScenario012.sol @@ -0,0 +1,57 @@ +//pragma solidity ^0.4.0; +contract PayTest { + +uint256 public n; +constructor() payable public{ +n = 0; +} + +function nPlusOne() public{ +n = n+1; +} + +//get current contract balance +function getBalance() payable public returns (uint) { +return address(this).balance; +} + +function getSenderBalance() public view returns(address, uint) { +return (msg.sender, msg.sender.balance); +} + +address public user; + +//deposit 1 coin to msg.sender +function depositOneCoin() payable public returns(bool success){ +return msg.sender.send(1); +} + +// function transferOneCoin() payable public returns(){ +// address(msg.sender).transfer(1); +// } + +// function depositOneCoin() payable public returns(address addr, uint amount, bool success){ +// return (msg.sender, msg.value, msg.sender.send(1)); +// } + +//deposit coin to msg.sender +function deposit(uint256 money) payable public returns(bool success){ +return msg.sender.send(money); +} +// function deposit(uint money) payable public returns(address addr, uint amount, bool success){ +// return (msg.sender, msg.value, msg.sender.send(money)); +// } + +// function () payable { +// msg.sender.send(1); +// } + +function sendToAddress(address payable _receiver) payable public{ +_receiver.transfer(msg.value); +} + +function sendToAddress2(address payable _receiver) payable public{ +_receiver.transfer(5); +} + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario013.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario013.sol new file mode 100644 index 00000000000..b91085d018e --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractScenario013.sol @@ -0,0 +1,8 @@ +//pragma solidity ^0.4.0; +contract timetest { + +function time() public{ +require(1 trx == 1000000 sun); + +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario014.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario014.sol new file mode 100644 index 00000000000..41ea739e231 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractScenario014.sol @@ -0,0 +1,34 @@ +//pragma solidity ^0.4.0; +contract Contract1 { + constructor() public payable{} + function send5SunToReceiver(address payable _receiver) payable public{ + _receiver.transfer(5); + } +} +contract contract2 { + address public payContract; + + constructor(address _add) payable public{ + payContract = _add; + } + + function triggerContract1(address _receiver) payable public{ + payContract.call(abi.encodeWithSignature("send5SunToReceiver(address)",_receiver)); + } + + function triggerContract1ButRevert(address _receiver) payable public{ + payContract.call(abi.encodeWithSignature("send5SunToReceiver(address)",_receiver)); + require(1 == 2); + } + +} +contract contract3 { + address public payContract; + constructor(address _add) payable public{ + payContract = _add; + } + + function triggerContract2(address _receiver) payable public{ + payContract.call(abi.encodeWithSignature("triggerContract1(address)",_receiver)); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTest.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTest.sol new file mode 100644 index 00000000000..409545eaabb --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTest.sol @@ -0,0 +1,19 @@ +//pragma solidity ^0.4.4; + +contract Test{ + +function a() public returns (uint){ + +uint256 count = 0; + +for (uint256 i = 1; i > 0; i++) { + +count++; + +} + +return count; + +} + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractToMathedFeed.sol b/framework/src/test/resources/soliditycode_0.5.15/contractToMathedFeed.sol new file mode 100644 index 00000000000..a5d181ad927 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractToMathedFeed.sol @@ -0,0 +1,21 @@ +//pragma solidity ^0.4.0; + +contract ToMathedFeed { + uint public i=1; + function ToMathed (uint value) public { + i=value; + } +} + +contract ToMathedUseINContract { + function ToMathedIUseNR(address a,uint256 n) public returns(bool){ + address payContract=a; + (bool success, bytes memory data) = payContract.call(abi.encodeWithSignature("ToMathedNot(uint256)",n)); + return success; + } + function ToMathedIUseNRE(address a,uint256 value) public returns(bool){ + address payContract=a; + (bool success, bytes memory data) = payContract.call(abi.encodeWithSignature("ToMathed(uint256)",value)); + return success; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTransferToken001.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTransferToken001.sol new file mode 100644 index 00000000000..e91c0d7bf0f --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTransferToken001.sol @@ -0,0 +1,22 @@ +contract A { + address public a; + constructor() public payable{} + function kill(address payable toAddress) payable public{ + selfdestruct(toAddress); + } + function newB() public payable returns(address){ + B bAddress=new B(); + a= address(bAddress); + return a; + + } + + } + +contract B{ + constructor() public payable {} + function() external payable {} + function kill(address payable toAddress) payable public{ + selfdestruct(toAddress); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken001.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken001.sol new file mode 100644 index 00000000000..0db64f36336 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken001.sol @@ -0,0 +1,30 @@ +//pragma solidity ^0.4.24; + + contract tokenTest{ + trcToken idCon = 0; + uint256 tokenValueCon=0; + uint256 callValueCon = 0; + + // positive case + function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ + //trcToken id = 0x74657374546f6b656e; + toAddress.transferToken(amount,id); + } + + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ + trcToken id = msg.tokenid; + uint256 tokenValue = msg.tokenvalue; + uint256 callValue = msg.value; + return (id, tokenValue, callValue); + } + + constructor() public payable { + idCon = msg.tokenid; + tokenValueCon = msg.tokenvalue; + callValueCon = msg.value; + } + + function getResultInCon() public payable returns(trcToken, uint256, uint256) { + return (idCon, tokenValueCon, callValueCon); + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken002.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken002.sol new file mode 100644 index 00000000000..0db64f36336 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken002.sol @@ -0,0 +1,30 @@ +//pragma solidity ^0.4.24; + + contract tokenTest{ + trcToken idCon = 0; + uint256 tokenValueCon=0; + uint256 callValueCon = 0; + + // positive case + function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ + //trcToken id = 0x74657374546f6b656e; + toAddress.transferToken(amount,id); + } + + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ + trcToken id = msg.tokenid; + uint256 tokenValue = msg.tokenvalue; + uint256 callValue = msg.value; + return (id, tokenValue, callValue); + } + + constructor() public payable { + idCon = msg.tokenid; + tokenValueCon = msg.tokenvalue; + callValueCon = msg.value; + } + + function getResultInCon() public payable returns(trcToken, uint256, uint256) { + return (idCon, tokenValueCon, callValueCon); + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken003.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken003.sol new file mode 100644 index 00000000000..48205199eec --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken003.sol @@ -0,0 +1,16 @@ +//pragma solidity ^0.4.24; + + contract tokenTest{ + constructor() public payable{} + // positive case + function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ + //trcToken id = 0x74657374546f6b656e; + toAddress.transferToken(amount,id); + } + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ + trcToken id = msg.tokenid; + uint256 tokenValue = msg.tokenvalue; + uint256 callValue = msg.value; + return (id, tokenValue, callValue); + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken005.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken005.sol new file mode 100644 index 00000000000..48205199eec --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken005.sol @@ -0,0 +1,16 @@ +//pragma solidity ^0.4.24; + + contract tokenTest{ + constructor() public payable{} + // positive case + function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ + //trcToken id = 0x74657374546f6b656e; + toAddress.transferToken(amount,id); + } + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ + trcToken id = msg.tokenid; + uint256 tokenValue = msg.tokenvalue; + uint256 callValue = msg.value; + return (id, tokenValue, callValue); + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken011.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken011.sol new file mode 100644 index 00000000000..f815c26b136 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken011.sol @@ -0,0 +1,35 @@ +//pragma solidity ^0.4.24; +contract transferTokenContract { + constructor() payable public{} + function() payable external{} + function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { + toAddress.transferToken(tokenValue, id); + } + function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { + toAddress.transferToken(1, 9223372036854775809); + } + function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { + toAddress.transferToken(1, 36893488147420103233); + } + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ + trcToken id = msg.tokenid; + uint256 value = msg.tokenvalue; + return (id, value); + } + function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ + trcToken id = 1000001; + return accountAddress.tokenBalance(id); + } + function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ + return toAddress.tokenBalance(tokenId); + } +} + + +contract Result { + event log(uint256,uint256,uint256); + constructor() payable public{} + function() payable external{ + emit log(msg.tokenid,msg.tokenvalue,msg.value); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken012.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken012.sol new file mode 100644 index 00000000000..668f67ae205 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken012.sol @@ -0,0 +1,26 @@ +//pragma solidity ^0.4.24; +contract transferTokenContract { + constructor() payable public{} + function() payable external{} + function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { + toAddress.transferToken(tokenValue, id); + } + function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { + toAddress.transferToken(1, 9223372036854775809); + } + function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { + toAddress.transferToken(1, 36893488147420103233); + } + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ + trcToken id = msg.tokenid; + uint256 value = msg.tokenvalue; + return (id, value); + } + function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ + trcToken id = 1000001; + return accountAddress.tokenBalance(id); + } + function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ + return toAddress.tokenBalance(tokenId); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken014.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken014.sol new file mode 100644 index 00000000000..3753770398a --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken014.sol @@ -0,0 +1,34 @@ +//pragma solidity ^0.4.24; +contract transferTokenContract { + constructor() payable public{} + function() payable external{} + function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { + toAddress.transferToken(tokenValue, id); + } + function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { + toAddress.transferToken(1, 9223372036854775809); + } + function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { + toAddress.transferToken(1, 36893488147420103233); + } + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ + trcToken id = msg.tokenid; + uint256 value = msg.tokenvalue; + return (id, value); + } + function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ + trcToken id = 1000001; + return accountAddress.tokenBalance(id); + } + function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ + return toAddress.tokenBalance(tokenId); + } +} + +contract Result { + event log(uint256,uint256,uint256); + constructor() payable public{} + function() payable external{ + emit log(msg.tokenid,msg.tokenvalue,msg.value); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken018.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken018.sol new file mode 100644 index 00000000000..668f67ae205 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken018.sol @@ -0,0 +1,26 @@ +//pragma solidity ^0.4.24; +contract transferTokenContract { + constructor() payable public{} + function() payable external{} + function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { + toAddress.transferToken(tokenValue, id); + } + function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { + toAddress.transferToken(1, 9223372036854775809); + } + function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { + toAddress.transferToken(1, 36893488147420103233); + } + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ + trcToken id = msg.tokenid; + uint256 value = msg.tokenvalue; + return (id, value); + } + function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ + trcToken id = 1000001; + return accountAddress.tokenBalance(id); + } + function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ + return toAddress.tokenBalance(tokenId); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken023.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken023.sol new file mode 100644 index 00000000000..99b19beb107 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken023.sol @@ -0,0 +1,26 @@ +//pragma solidity ^0.4.24; + + contract tokenTest{ + constructor() public payable{} + function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ + toAddress.transferToken(amount,id); + } + } + +contract B{ + uint256 public flag = 0; + constructor() public payable {} + function() external { + flag = 1; +} + +} +//pragma solidity ^0.4.24; +contract C{ + uint256 public flag = 0; + constructor() public payable {} + function() external payable { + //flag = 1; +} + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken026.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken026.sol new file mode 100644 index 00000000000..66635521150 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken026.sol @@ -0,0 +1,31 @@ +//pragma solidity ^0.4.24; + +contract token{ + constructor() payable public{} + function() payable external{} + function testInCall(address callBAddress,address callCAddress, address toAddress ,uint256 amount,trcToken id) payable public{ + //callBAddress.call(bytes4(keccak256("transC(address,address,uint256,trcToken)")),callCAddress,toAddress,amount,id); + callBAddress.call(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callCAddress,toAddress,amount,id)); + } + function testIndelegateCall(address callBddress,address callAddressC, address toAddress,uint256 amount, trcToken id) payable public{ + callBddress.delegatecall(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callAddressC,toAddress,amount,id)); + } + } + + + +contract B{ + constructor() public payable{} + function() external payable{} + function transC(address payable callCAddress,address payable toAddress,uint256 amount, trcToken id) payable public{ + callCAddress.call(abi.encodeWithSignature("trans(address,uint256,trcToken)",toAddress,amount,id)); + } +} +contract C{ + constructor() payable public{} + function() payable external{} + function trans(address payable toAddress,uint256 amount, trcToken id) payable public{ + toAddress.transferToken(amount,id); + } + +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken027.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken027.sol new file mode 100644 index 00000000000..ee9c1d3eb46 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken027.sol @@ -0,0 +1,30 @@ +//pragma solidity ^0.4.24; + +contract token{ + constructor() payable public{} + function() payable external{} + function testInCall(address callBAddress,address callCAddress, address toAddress ,uint256 amount,trcToken id) payable public{ + callBAddress.call(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callCAddress,toAddress,amount,id)); + } + function testIndelegateCall(address callBddress,address callAddressC, address toAddress,uint256 amount, trcToken id) payable public{ + callBddress.delegatecall(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callAddressC,toAddress,amount,id)); + } + } + + + +contract B{ + constructor() public payable{} + function() external payable{} + function transC(address callCAddress,address toAddress,uint256 amount, trcToken id) payable public{ + callCAddress.call(abi.encodeWithSignature("trans(address,uint256,trcToken)",toAddress,amount,id)); + } +} +contract C{ + constructor() payable public{} + function() payable external{} + function trans(address payable toAddress,uint256 amount, trcToken id) payable public{ + toAddress.transferToken(amount,id); + } + +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken028.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken028.sol new file mode 100644 index 00000000000..957f1c3c60d --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken028.sol @@ -0,0 +1,25 @@ +//pragma solidity ^0.4.24; + +contract token{ + uint256 public a=1; + constructor() public payable{} + function tokenBalanceWithSameName(trcToken id) public payable{ + B b= new B(); + a= b.tokenBalance(id); + } + function getA() public returns(uint256){ + return a; + } +} + + +contract B{ + uint256 public flag =0; + constructor() public payable{} + function() external payable{} + function tokenBalance(trcToken id) payable public returns(uint256){ + flag =9; + return flag; + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken029.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken029.sol new file mode 100644 index 00000000000..e8f5cbc0988 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken029.sol @@ -0,0 +1,24 @@ +//pragma solidity ^0.4.24; + +contract token{ + address public a; + constructor() public payable{} + function transferTokenWithSameName(trcToken id,uint256 amount) public payable{ + B b= new B(); + b.transferToken(amount,id); + a= address(b); + } +} + + +contract B{ + uint256 public flag =0; + constructor() public payable{} + function() external payable{} + function transferToken(uint256 amount, trcToken id) payable public returns(bool){ + flag =9; + } + function getFlag() public view returns (uint256){ + return flag; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken030.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken030.sol new file mode 100644 index 00000000000..5693292d127 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken030.sol @@ -0,0 +1,18 @@ +//pragma solidity ^0.4.24; + + contract token{ + constructor() public payable{} + + // 4)suicide也会转移token + // 所有token,trx均被转移到toAddress, + // 若toAddress为合约地址本身,则所有token,trx均被烧掉进黑洞 + function kill(address payable toAddress) payable public{ + selfdestruct(toAddress); + } + + } + +contract B{ + constructor() public payable {} + function() external payable {} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken031.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken031.sol new file mode 100644 index 00000000000..5693292d127 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken031.sol @@ -0,0 +1,18 @@ +//pragma solidity ^0.4.24; + + contract token{ + constructor() public payable{} + + // 4)suicide也会转移token + // 所有token,trx均被转移到toAddress, + // 若toAddress为合约地址本身,则所有token,trx均被烧掉进黑洞 + function kill(address payable toAddress) payable public{ + selfdestruct(toAddress); + } + + } + +contract B{ + constructor() public payable {} + function() external payable {} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken034.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken034.sol new file mode 100644 index 00000000000..c9a5e70a3fb --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken034.sol @@ -0,0 +1,23 @@ +//pragma solidity ^0.4.24; + + contract token{ + + // 2. 异常测试 + // 1)revert, 金额回退 + function failTransferTokenRevert(address payable toAddress,uint256 amount, trcToken id) public payable{ + toAddress.transferToken(amount,id); + require(1==2); + } + + // 2)Error, 金额回退, fee limit 扣光 + function failTransferTokenError(address payable toAddress,uint256 amount, trcToken id) public payable{ + toAddress.transferToken(amount,id); + assert(1==2); + } + + } + contract B{ + uint256 public flag = 0; + constructor() public payable {} + function() external payable {} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken035.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken035.sol new file mode 100644 index 00000000000..c9a5e70a3fb --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken035.sol @@ -0,0 +1,23 @@ +//pragma solidity ^0.4.24; + + contract token{ + + // 2. 异常测试 + // 1)revert, 金额回退 + function failTransferTokenRevert(address payable toAddress,uint256 amount, trcToken id) public payable{ + toAddress.transferToken(amount,id); + require(1==2); + } + + // 2)Error, 金额回退, fee limit 扣光 + function failTransferTokenError(address payable toAddress,uint256 amount, trcToken id) public payable{ + toAddress.transferToken(amount,id); + assert(1==2); + } + + } + contract B{ + uint256 public flag = 0; + constructor() public payable {} + function() external payable {} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036.sol new file mode 100644 index 00000000000..6a4c61d1e07 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036.sol @@ -0,0 +1,52 @@ +//pragma solidity ^0.4.24; +contract IllegalDecorate { +constructor() payable public{} +function() payable external{} +event log(uint256); +function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public payable { +emit log(msg.value); +emit log(msg.tokenvalue); +emit log(msg.tokenid); +toAddress.transferToken(msg.tokenvalue, msg.tokenid); +toAddress.transfer(msg.value); +} +} + +contract IllegalDecorate1 { +constructor() payable public{} +function() payable external{} +event log(uint256); +function transferTokenWithConstant(address payable toAddress, uint256 tokenValue) public payable { +emit log(msg.value); +emit log(msg.tokenvalue); +emit log(msg.tokenid); +toAddress.transferToken(msg.tokenvalue, msg.tokenid); +toAddress.transfer(msg.value); +} +} + +contract IllegalDecorate2 { +constructor() payable public{} +function() payable external{} +event log(uint256); +function transferTokenWithView(address payable toAddress, uint256 tokenValue) public payable { +emit log(msg.value); +emit log(msg.tokenvalue); +emit log(msg.tokenid); +toAddress.transferToken(msg.tokenvalue, msg.tokenid); +toAddress.transfer(msg.value); +} +} + +contract IllegalDecorate3 { +event log(uint256); +constructor() payable public{} +function() payable external{} +function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue) public { +emit log(msg.value); +emit log(msg.tokenvalue); +emit log(msg.tokenid); +toAddress.transferToken(msg.tokenvalue, msg.tokenid); +toAddress.transfer(msg.value); +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_1.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_1.sol new file mode 100644 index 00000000000..cd039f3e39d --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_1.sol @@ -0,0 +1,13 @@ +//pragma solidity ^0.4.24; +contract IllegalDecorate { +constructor() payable public{} +function() payable external{} +event log(uint256); +function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public pure { +emit log(msg.value); +emit log(msg.tokenvalue); +emit log(msg.tokenid); +toAddress.transferToken(msg.tokenvalue, msg.tokenid); +toAddress.transfer(msg.value); +} +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_2.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_2.sol new file mode 100644 index 00000000000..0b4d56e086b --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_2.sol @@ -0,0 +1,13 @@ +//pragma solidity ^0.4.24; +contract IllegalDecorate { +constructor() payable public{} +function() payable external{} +event log(uint256); +function transferTokenWithConstant(address toAddress, uint256 tokenValue) public constant { +emit log(msg.value); +emit log(msg.tokenvalue); +emit log(msg.tokenid); +toAddress.transferToken(msg.tokenvalue, msg.tokenid); +toAddress.transfer(msg.value); +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_3.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_3.sol new file mode 100644 index 00000000000..b8c7d750514 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_3.sol @@ -0,0 +1,13 @@ +//pragma solidity ^0.4.24; +contract IllegalDecorate { +constructor() payable public{} +function() payable external{} +event log(uint256); +function transferTokenWithView(address payable toAddress, uint256 tokenValue) public view { +emit log(msg.value); +emit log(msg.tokenvalue); +emit log(msg.tokenid); +toAddress.transferToken(msg.tokenvalue, msg.tokenid); +toAddress.transfer(msg.value); +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_4.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_4.sol new file mode 100644 index 00000000000..29c1990962b --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_4.sol @@ -0,0 +1,13 @@ +//pragma solidity ^0.4.24; +contract IllegalDecorate { +event log(uint256); +constructor() payable public{} +function() payable external{} +function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue) public { +emit log(msg.value); +emit log(msg.tokenvalue); +emit log(msg.tokenid); +toAddress.transferToken(msg.tokenvalue, msg.tokenid); +toAddress.transfer(msg.value); +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_old.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_old.sol new file mode 100644 index 00000000000..7ea2561a1e1 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_old.sol @@ -0,0 +1,41 @@ +//pragma solidity ^0.4.24; + + +contract IllegalDecorate1 { +constructor() payable public{} +function() payable public{} +event log(uint256); +function transferTokenWithConstant(address toAddress, uint256 tokenValue) public constant { +emit log(msg.value); +emit log(msg.tokenvalue); +emit log(msg.tokenid); +toAddress.transferToken(msg.tokenvalue, msg.tokenid); +toAddress.transfer(msg.value); +} +} + +contract IllegalDecorate2 { +constructor() payable public{} +function() payable public{} +event log(uint256); +function transferTokenWithView(address toAddress, uint256 tokenValue) public view { +emit log(msg.value); +emit log(msg.tokenvalue); +emit log(msg.tokenid); +toAddress.transferToken(msg.tokenvalue, msg.tokenid); +toAddress.transfer(msg.value); +} +} + +contract IllegalDecorate3 { +event log(uint256); +constructor() payable public{} +function() payable public{} +function transferTokenWithOutPayable(address toAddress, uint256 tokenValue) public { +emit log(msg.value); +emit log(msg.tokenvalue); +emit log(msg.tokenid); +toAddress.transferToken(msg.tokenvalue, msg.tokenid); +toAddress.transfer(msg.value); +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken037.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken037.sol new file mode 100644 index 00000000000..5e3fbcb8270 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken037.sol @@ -0,0 +1,24 @@ +//pragma solidity ^0.4.24; + +contract transferTrc10 { + function receive(address payable rec) public payable { + uint256 aamount=address(this).tokenBalance(msg.tokenid); + uint256 bamount=rec.tokenBalance(msg.tokenid); + require(msg.tokenvalue==aamount); + require(aamount==msg.tokenvalue); + rec.transferToken(aamount,msg.tokenid); + require(0==address(this).tokenBalance(msg.tokenid)); + require(bamount+aamount==rec.tokenBalance(msg.tokenid)); + (bool success, bytes memory data) =rec.call(abi.encodeWithSignature("checkTrc10(uint256,trcToken,uint256)",bamount+aamount,msg.tokenid,0)); + require(success); + + } +} + +contract receiveTrc10 { + function() external payable {} + function checkTrc10(uint256 amount,trcToken tid,uint256 meamount) public{ + require(amount==address(this).tokenBalance(tid)); + require(meamount==msg.sender.tokenBalance(tid)); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken038.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken038.sol new file mode 100644 index 00000000000..713d7661e84 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken038.sol @@ -0,0 +1,24 @@ +//pragma solidity ^0.4.24; + +contract transferTrc10 { + function receive(address payable rec) public payable { + uint256 aamount=address(this).tokenBalance(msg.tokenid); + uint256 bamount=rec.tokenBalance(msg.tokenid); + require(msg.tokenvalue==aamount); + require(aamount==msg.tokenvalue); + rec.transferToken(aamount,msg.tokenid); + //require(rec.call(abi.encode(bytes4(keccak256("AssertError()"))))); + (bool suc, bytes memory data) = rec.call(abi.encodeWithSignature("AssertError()")); + require(suc); + require(aamount==address(this).tokenBalance(msg.tokenid)); + require(bamount==rec.tokenBalance(msg.tokenid)); + } +} + +contract receiveTrc10 { + function() external payable { + } + function AssertError() public{ + assert(1==2); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken039.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken039.sol new file mode 100644 index 00000000000..e60b3285652 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken039.sol @@ -0,0 +1,44 @@ +//pragma solidity ^0.4.24; +/* + * 1. caller账户issue一个token + * 2. caller部署proxy, 传入1000 token,1000 trx + * 3. caller部署A + * 4. caller部署B + * 5. caller调用proxy中upgradetTo函数,传入A的地址 + * 6. caller调用proxy中不存在的trans(uint256,address,trcToken)函数,注意这时trcToken是无意义的,但也带上tokenid。address是任意另外某账户的地址 + * 7. 可以看到目标地址trx增长5,caller账户trx减少5 + * 8. caller调用proxy中upgradeTo函数,传入B的地址 + * 9. caller调用proxy中不存在的trans(uint256,address,trcToken)函数。 + * 10. 可以看到目标地址token增长5,caller账户token减少5 +*/ +contract Proxy { + constructor() payable public{} + address public implementation; + function upgradeTo(address _address) public { + implementation = _address; + } + function() payable external{ + address addr = implementation; + require(addr != address(0)); + assembly { + let freememstart := mload(0x40) + calldatacopy(freememstart, 0, calldatasize()) + let success := delegatecall(not(0), addr, freememstart, calldatasize(), freememstart, 0) + returndatacopy(freememstart, 0, returndatasize()) + switch success + case 0 { revert(freememstart, returndatasize()) } + default { return(freememstart, returndatasize()) } + } + } +} + +contract A { + function trans(uint256 amount, address payable toAddress, trcToken id) payable public { + toAddress.transfer(amount); + } +} +contract B{ + function trans(uint256 amount, address payable toAddress, trcToken id) payable public { + toAddress.transferToken(amount,id); + } +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken041.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken041.sol new file mode 100644 index 00000000000..a6272bc813d --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken041.sol @@ -0,0 +1,20 @@ +//pragma solidity ^0.4.24; + + contract tokenTest{ + constructor() public payable{} + // positive case + function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ + //trcToken id = 0x74657374546f6b656e; + toAddress.transferToken(amount,id); + } + } + +contract B{ + uint256 public flag = 0; + constructor() public payable {} + function() external payable {} + + function setFlag() public payable{ + flag = 1; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken043.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken043.sol new file mode 100644 index 00000000000..f815c26b136 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken043.sol @@ -0,0 +1,35 @@ +//pragma solidity ^0.4.24; +contract transferTokenContract { + constructor() payable public{} + function() payable external{} + function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { + toAddress.transferToken(tokenValue, id); + } + function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { + toAddress.transferToken(1, 9223372036854775809); + } + function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { + toAddress.transferToken(1, 36893488147420103233); + } + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ + trcToken id = msg.tokenid; + uint256 value = msg.tokenvalue; + return (id, value); + } + function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ + trcToken id = 1000001; + return accountAddress.tokenBalance(id); + } + function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ + return toAddress.tokenBalance(tokenId); + } +} + + +contract Result { + event log(uint256,uint256,uint256); + constructor() payable public{} + function() payable external{ + emit log(msg.tokenid,msg.tokenvalue,msg.value); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken048.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken048.sol new file mode 100644 index 00000000000..de2844608c0 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken048.sol @@ -0,0 +1,14 @@ +//pragma solidity ^0.4.24; + + contract Test { + event log(uint256); + function testMsgTokenValue() payable public returns(uint256 value) { + emit log(msg.tokenvalue); + return msg.tokenvalue; + } + + function testMsgValue() payable public returns(uint256 value) { + emit log(msg.value); + return msg.value; + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken049.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken049.sol new file mode 100644 index 00000000000..3fd502c89fd --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken049.sol @@ -0,0 +1,10 @@ +//pragma solidity ^0.4.24; + + contract tokenTest{ + constructor() public payable{} + // positive case + function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ + //trcToken id = 0x74657374546f6b656e; + toAddress.transferToken(amount,id); + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken050.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken050.sol new file mode 100644 index 00000000000..3fd502c89fd --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken050.sol @@ -0,0 +1,10 @@ +//pragma solidity ^0.4.24; + + contract tokenTest{ + constructor() public payable{} + // positive case + function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ + //trcToken id = 0x74657374546f6b656e; + toAddress.transferToken(amount,id); + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken051.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken051.sol new file mode 100644 index 00000000000..b5b9efd4817 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken051.sol @@ -0,0 +1,11 @@ +//pragma solidity ^0.4.24; + + contract tokenTest{ + constructor() public payable{} + function() external payable{} + // positive case + function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ + //trcToken id = 0x74657374546f6b656e; + toAddress.transferToken(amount,id); + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken052.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken052.sol new file mode 100644 index 00000000000..3fd502c89fd --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken052.sol @@ -0,0 +1,10 @@ +//pragma solidity ^0.4.24; + + contract tokenTest{ + constructor() public payable{} + // positive case + function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ + //trcToken id = 0x74657374546f6b656e; + toAddress.transferToken(amount,id); + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken054.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken054.sol new file mode 100644 index 00000000000..48205199eec --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken054.sol @@ -0,0 +1,16 @@ +//pragma solidity ^0.4.24; + + contract tokenTest{ + constructor() public payable{} + // positive case + function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ + //trcToken id = 0x74657374546f6b656e; + toAddress.transferToken(amount,id); + } + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ + trcToken id = msg.tokenid; + uint256 tokenValue = msg.tokenvalue; + uint256 callValue = msg.value; + return (id, tokenValue, callValue); + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken055.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken055.sol new file mode 100644 index 00000000000..48205199eec --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken055.sol @@ -0,0 +1,16 @@ +//pragma solidity ^0.4.24; + + contract tokenTest{ + constructor() public payable{} + // positive case + function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ + //trcToken id = 0x74657374546f6b656e; + toAddress.transferToken(amount,id); + } + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ + trcToken id = msg.tokenid; + uint256 tokenValue = msg.tokenvalue; + uint256 callValue = msg.value; + return (id, tokenValue, callValue); + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken060.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken060.sol new file mode 100644 index 00000000000..0db64f36336 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken060.sol @@ -0,0 +1,30 @@ +//pragma solidity ^0.4.24; + + contract tokenTest{ + trcToken idCon = 0; + uint256 tokenValueCon=0; + uint256 callValueCon = 0; + + // positive case + function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ + //trcToken id = 0x74657374546f6b656e; + toAddress.transferToken(amount,id); + } + + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ + trcToken id = msg.tokenid; + uint256 tokenValue = msg.tokenvalue; + uint256 callValue = msg.value; + return (id, tokenValue, callValue); + } + + constructor() public payable { + idCon = msg.tokenid; + tokenValueCon = msg.tokenvalue; + callValueCon = msg.value; + } + + function getResultInCon() public payable returns(trcToken, uint256, uint256) { + return (idCon, tokenValueCon, callValueCon); + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken061.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken061.sol new file mode 100644 index 00000000000..0db64f36336 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken061.sol @@ -0,0 +1,30 @@ +//pragma solidity ^0.4.24; + + contract tokenTest{ + trcToken idCon = 0; + uint256 tokenValueCon=0; + uint256 callValueCon = 0; + + // positive case + function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ + //trcToken id = 0x74657374546f6b656e; + toAddress.transferToken(amount,id); + } + + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ + trcToken id = msg.tokenid; + uint256 tokenValue = msg.tokenvalue; + uint256 callValue = msg.value; + return (id, tokenValue, callValue); + } + + constructor() public payable { + idCon = msg.tokenid; + tokenValueCon = msg.tokenvalue; + callValueCon = msg.value; + } + + function getResultInCon() public payable returns(trcToken, uint256, uint256) { + return (idCon, tokenValueCon, callValueCon); + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken064.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken064.sol new file mode 100644 index 00000000000..cf2a6fe8097 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken064.sol @@ -0,0 +1,49 @@ +//pragma solidity ^0.4.24; +contract transferTokenContract { + constructor() payable public{} + function() payable external{} + function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { + toAddress.transferToken(tokenValue, id); + } + function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { + toAddress.transferToken(1, 9223372036854775809); + } + function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { + toAddress.transferToken(1, 36893488147420103233); + } + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ + trcToken id = msg.tokenid; + uint256 value = msg.tokenvalue; + return (id, value); + } + function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ + trcToken id = 1000001; + return accountAddress.tokenBalance(id); + } + function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ + return toAddress.tokenBalance(tokenId); + } + function transferTokenTestValueMaxBigInteger(address payable toAddress) payable public { + toAddress.transferToken(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, 0); + } + function transferTokenTestValueOverBigInteger(address payable toAddress) payable public { + toAddress.transferToken(9223372036854775808, 1000001); + } + function transferTokenTestValueMaxLong(address payable toAddress) payable public { + toAddress.transferToken(9223372036854775807, 1000001); + } + function transferTokenTestValue0IdBigInteger(address payable toAddress) payable public { + toAddress.transferToken(0, 9223372036854775809); + } +} + + + + +contract Result { + event log(uint256,uint256,uint256); + constructor() payable public{} + function() payable external{ + emit log(msg.tokenid,msg.tokenvalue,msg.value); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken066.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken066.sol new file mode 100644 index 00000000000..f815c26b136 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken066.sol @@ -0,0 +1,35 @@ +//pragma solidity ^0.4.24; +contract transferTokenContract { + constructor() payable public{} + function() payable external{} + function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { + toAddress.transferToken(tokenValue, id); + } + function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { + toAddress.transferToken(1, 9223372036854775809); + } + function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { + toAddress.transferToken(1, 36893488147420103233); + } + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ + trcToken id = msg.tokenid; + uint256 value = msg.tokenvalue; + return (id, value); + } + function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ + trcToken id = 1000001; + return accountAddress.tokenBalance(id); + } + function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ + return toAddress.tokenBalance(tokenId); + } +} + + +contract Result { + event log(uint256,uint256,uint256); + constructor() payable public{} + function() payable external{ + emit log(msg.tokenid,msg.tokenvalue,msg.value); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken067.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken067.sol new file mode 100644 index 00000000000..f815c26b136 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken067.sol @@ -0,0 +1,35 @@ +//pragma solidity ^0.4.24; +contract transferTokenContract { + constructor() payable public{} + function() payable external{} + function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { + toAddress.transferToken(tokenValue, id); + } + function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { + toAddress.transferToken(1, 9223372036854775809); + } + function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { + toAddress.transferToken(1, 36893488147420103233); + } + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ + trcToken id = msg.tokenid; + uint256 value = msg.tokenvalue; + return (id, value); + } + function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ + trcToken id = 1000001; + return accountAddress.tokenBalance(id); + } + function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ + return toAddress.tokenBalance(tokenId); + } +} + + +contract Result { + event log(uint256,uint256,uint256); + constructor() payable public{} + function() payable external{ + emit log(msg.tokenid,msg.tokenvalue,msg.value); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken073.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken073.sol new file mode 100644 index 00000000000..9cb13ec7268 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken073.sol @@ -0,0 +1,17 @@ +//pragma solidity ^0.4.0; + +contract Dest { + event logFallback(uint256 indexed, uint256 indexed, uint256 indexed); + event logGetToken(uint256 indexed, uint256 indexed, uint256 indexed, uint256); + + + constructor() payable public {} + + function getToken(trcToken tokenId) payable public{ + emit logGetToken(msg.sender.tokenBalance(tokenId), msg.tokenid, msg.tokenvalue, msg.value); + } + + function () payable external{ + emit logFallback(msg.tokenid, msg.tokenvalue, msg.value); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken075.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken075.sol new file mode 100644 index 00000000000..2a32fd7e8d3 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken075.sol @@ -0,0 +1,26 @@ +//pragma solidity ^0.4.0; + +contract Dest { + event logFallback(uint256 indexed, uint256 indexed, uint256 indexed); + event logGetToken(uint256 indexed, uint256 indexed, uint256 indexed, uint256); + + constructor() payable public {} + + function getToken(trcToken tokenId) payable public{ + emit logGetToken(msg.sender.tokenBalance(tokenId), msg.tokenid, msg.tokenvalue, msg.value); + } + + function getTokenLongMin() payable public{ + // long.min - 1000020 + emit logGetToken(msg.sender.tokenBalance(trcToken(-9223372036855775828)), msg.tokenid, msg.tokenvalue, msg.value); + } + + function getTokenLongMax() payable public{ + // long.max + 1000020 + emit logGetToken(msg.sender.tokenBalance(trcToken(9223372036855775827)), msg.tokenid, msg.tokenvalue, msg.value); + } + + function () payable external{ + emit logFallback(msg.tokenid, msg.tokenvalue, msg.value); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken076.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken076.sol new file mode 100644 index 00000000000..9de79a327c3 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken076.sol @@ -0,0 +1,19 @@ +//pragma solidity ^0.4.24; +contract Test { + address public origin; + address public sender; + bool public result1; + bool public result2; + function test() external { + origin = tx.origin; + sender = msg.sender; + result1 = msg.sender == tx.origin; // true + result2 = origin == sender; // true + } +function getResult1() public returns(bool){ + return result1; +} +function getResult2() public returns(bool){ + return result2; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken077.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken077.sol new file mode 100644 index 00000000000..e110f24e2fc --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken077.sol @@ -0,0 +1,11 @@ +//pragma solidity ^0.4.24; + +contract trcToken077 { +function addressTest() public returns(bytes32 addressValue) { + assembly{ + let x := mload(0x40) //Find empty storage location using "free memory pointer" + mstore(x,address) //Place current contract address + addressValue := mload(x) + } + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken078.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken078.sol new file mode 100644 index 00000000000..f7504ea55aa --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken078.sol @@ -0,0 +1,35 @@ +//pragma solidity ^0.4.24; +contract callerContract { + constructor() public payable{} + function() external payable{} + function sendToB(address called_address, address c) public payable{ + called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); + } + function sendToB2(address called_address,address c) public payable{ + called_address.call(abi.encodeWithSignature("transferTo(address)",c)); + } + function sendToB3(address called_address,address c) public payable{ + called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); + } +} + contract calledContract { + function() external payable{} + constructor() public payable {} + function transferTo(address payable toAddress)public payable{ + toAddress.transfer(5); + } + + function setIinC(address c) public payable{ + c.call.value(5)(abi.encode(bytes4(keccak256("setI()")))); + } + + } + contract c{ + address public origin; + address public sender; + constructor() public payable{} + event log(address,address); + function() payable external{ + emit log(tx.origin,msg.sender); + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken079.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken079.sol new file mode 100644 index 00000000000..48205199eec --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken079.sol @@ -0,0 +1,16 @@ +//pragma solidity ^0.4.24; + + contract tokenTest{ + constructor() public payable{} + // positive case + function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ + //trcToken id = 0x74657374546f6b656e; + toAddress.transferToken(amount,id); + } + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ + trcToken id = msg.tokenid; + uint256 tokenValue = msg.tokenvalue; + uint256 callValue = msg.value; + return (id, tokenValue, callValue); + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken080.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken080.sol new file mode 100644 index 00000000000..27529ce48e8 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken080.sol @@ -0,0 +1,30 @@ +//pragma solidity ^0.4.24; + + contract tokenTest{ + trcToken idCon = 0; + uint256 tokenValueCon=0; + uint256 callValueCon = 0; + function() external payable{} + // positive case + function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ + //trcToken id = 0x74657374546f6b656e; + toAddress.transferToken(amount,id); + } + + function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ + trcToken id = msg.tokenid; + uint256 tokenValue = msg.tokenvalue; + uint256 callValue = msg.value; + return (id, tokenValue, callValue); + } + + constructor() public payable { + idCon = msg.tokenid; + tokenValueCon = msg.tokenvalue; + callValueCon = msg.value; + } + + function getResultInCon() public payable returns(trcToken, uint256, uint256) { + return (idCon, tokenValueCon, callValueCon); + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcTokenToOther.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcTokenToOther.sol new file mode 100644 index 00000000000..22456df9e8e --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractTrcTokenToOther.sol @@ -0,0 +1,44 @@ +//pragma solidity ^0.4.24; + +contract ConvertType { + +constructor() payable public{} + +function() payable external{} + +//function trcTokenOnStorage(trcToken storage token) internal { // ERROR: Data location can only be specified for array, struct or mapping types, but "storage" was given. +//} + +function trcTokenToString(trcToken token) public pure returns(string memory s){ +// s = token; // ERROR +// s = string(token); // ERROR +} + +function trcTokenToUint256(trcToken token) public pure returns(uint256 r){ +uint256 u = token; // OK +uint256 u2 = uint256(token); // OK +r = u2; +} + +function trcTokenToAddress(trcToken token) public pure returns(address r){ +//r = token; // ERROR +token = 0x1234567812345678123456781234567812345678123456781234567812345678; +address a2 = address(token); // OK +r = a2; +} + +function trcTokenToBytes(trcToken token) public pure returns(bytes memory r){ +//r = token; // ERROR +// r = bytes(token); // ERROR +} + +function trcTokenToBytes32(trcToken token) public pure returns(bytes32 r){ +// r = token; // ERROR +bytes32 b2 = bytes32(token); // OK +r = b2; +} + +function trcTokenToArray(trcToken token) public pure returns(uint[] memory r){ +//r = token; // ERROR +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractUnknownException.sol b/framework/src/test/resources/soliditycode_0.5.15/contractUnknownException.sol new file mode 100644 index 00000000000..37c28468be1 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/contractUnknownException.sol @@ -0,0 +1,65 @@ +// pragma solidity ^0.4.24; + +contract testA { + constructor() public payable { + A a = (new A).value(10)(); + a.fun(); + } +} + +contract testB { + constructor() public payable { + B b = (new B).value(10)(); + b.fun(); + } +} + + +contract testC { + constructor() public payable{ + C c = (new C).value(10)(); + c.fun(); + } +} + +contract testD { + constructor() public payable{ + D d = (new D).value(10)(); + d.fun(); + } +} + + +contract A { + constructor() public payable{ + selfdestruct(msg.sender); + } + function fun() public { + } + +} + +contract B { + constructor() public payable { + revert(); + } + function fun() public { + } +} + + +contract C { + constructor() public payable { + assert(1==2); + } + function fun() public { + } +} + +contract D { + constructor() public payable { + require(1==2); + } + function fun() public { + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/create2CallContract.sol b/framework/src/test/resources/soliditycode_0.5.15/create2CallContract.sol new file mode 100644 index 00000000000..f2de1c7ee13 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/create2CallContract.sol @@ -0,0 +1,37 @@ +contract callerContract { + constructor() payable public{} + function() payable external{} + function delegateCallCreate2(address called_address, bytes memory code, uint256 salt) public { + called_address.delegatecall(abi.encodeWithSignature("deploy(bytes,uint256)",code,salt)); + } + function callCreate2(address called_address,bytes memory code, uint256 salt) public returns(bool,bytes memory){ + return called_address.call(abi.encodeWithSignature("deploy(bytes,uint256)",code,salt)); + } +} + + +contract Factory { + event Deployed(address addr, uint256 salt, address sender); + function deploy(bytes memory code, uint256 salt) public returns(address){ + address addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed(addr, salt, msg.sender); + return addr; + } +} + + +contract TestConstract { + uint public i; + constructor () public { + } + function plusOne() public returns(uint){ + i++; + return i; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/create2Istanbul.sol b/framework/src/test/resources/soliditycode_0.5.15/create2Istanbul.sol new file mode 100644 index 00000000000..b79db6e4639 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/create2Istanbul.sol @@ -0,0 +1,28 @@ +pragma solidity ^0.5.12; + +contract create2Istanbul { + function deploy(bytes memory code, uint256 salt) public returns(address) { + address addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + + } + return addr; + } + + // prefix in main net is 0x41, testnet config is 0xa0 + function get(bytes1 prefix, bytes calldata code, uint256 salt) external view returns(address) { + //bytes32 hash = keccak256(abi.encodePacked(bytes1(0x41),address(this), salt, keccak256(code))); + bytes32 hash = keccak256(abi.encodePacked(prefix,address(this), salt, keccak256(code))); + address addr = address(uint160(uint256(hash))); + return addr; + } + +} + +contract B { + constructor() public payable{} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/create2contract.sol b/framework/src/test/resources/soliditycode_0.5.15/create2contract.sol new file mode 100644 index 00000000000..0171f4d5486 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/create2contract.sol @@ -0,0 +1,52 @@ +contract Factory { + event Deployed(address addr, uint256 salt, address sender); + function deploy(bytes memory code, uint256 salt) public returns(address){ + address addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed(addr, salt, msg.sender); + return addr; + } + + event Deployed(address addr, bytes32 salt, address sender); + function deploy(bytes memory code, bytes32 salt) public returns(address){ + address addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed(addr, salt, msg.sender); + return addr; + } +} + +contract FactoryBytes { + event Deployed(address addr, bytes32 salt, address sender); + function deploy(bytes memory code, bytes32 salt) public returns(address){ + address addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed(addr, salt, msg.sender); + return addr; + } +} + +contract TestConstract { + uint public i; + constructor () public { + } + function plusOne() public returns(uint){ + i++; + return i; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/create2contract22.sol b/framework/src/test/resources/soliditycode_0.5.15/create2contract22.sol new file mode 100644 index 00000000000..c33cb08edc3 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/create2contract22.sol @@ -0,0 +1,109 @@ +contract Factory { + event Deployed(address addr, trcToken salt, address sender); + event Deployed1(address addr, uint8 salt, address sender); + event Deployed2(address addr, address salt, address sender); + event Deployed3(address addr, string salt, address sender); + + + function deploy(bytes memory code, trcToken salt) public returns(address){ + address addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed(addr, salt, msg.sender); + return addr; + } + + function deploy1(bytes memory code, uint8 salt) public returns(address){ + address addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed1(addr, salt, msg.sender); + return addr; + } + + function deploy2(bytes memory code, address salt) public returns(address){ + address addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed2(addr, salt, msg.sender); + return addr; + } + + function deploy3(bytes memory code, string memory salt) public returns(address){ + address addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed3(addr, salt, msg.sender); + return addr; + } + +} + + +contract TestConstract { + uint public i=1; + function testTransfer(uint256 i) payable public{ + msg.sender.transfer(i); + } + function testTransferToken(uint256 i,trcToken tokenId) payable public{ + msg.sender.transferToken(i, tokenId); + } + function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { + selfdestruct(nonexistentTarget); + } +} + +contract TestConstract1 { + uint public i=2; + function testTransfer(uint256 i) payable public{ + msg.sender.transfer(i); + } + function testTransferToken(uint256 i,trcToken tokenId) payable public{ + msg.sender.transferToken(i, tokenId); + } + function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { + selfdestruct(nonexistentTarget); + } +} + +contract TestConstract2 { + uint public i=3; + function testTransfer(uint256 i) payable public{ + msg.sender.transfer(i); + } + function testTransferToken(uint256 i,trcToken tokenId) payable public{ + msg.sender.transferToken(i, tokenId); + } + function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { + selfdestruct(nonexistentTarget); + } +} + +contract TestConstract3 { + uint public i=4; + function testTransfer(uint256 i) payable public{ + msg.sender.transfer(i); + } + function testTransferToken(uint256 i,trcToken tokenId) payable public{ + msg.sender.transferToken(i, tokenId); + } + function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { + selfdestruct(nonexistentTarget); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/create2contractn.sol b/framework/src/test/resources/soliditycode_0.5.15/create2contractn.sol new file mode 100644 index 00000000000..e0e3ae64c16 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/create2contractn.sol @@ -0,0 +1,29 @@ +contract Factory { + event Deployed(address addr, uint256 salt, address sender); + function deploy(bytes memory code, uint256 salt) public returns(address){ + address addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed(addr, salt, msg.sender); + return addr; + } +} + + + +contract TestConstract { + uint public i=1; + function testTransfer(uint256 i) payable public{ + msg.sender.transfer(i); + } + function testTransferToken(uint256 i,trcToken tokenId) payable public{ + msg.sender.transferToken(i, tokenId); + } + function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { + selfdestruct(nonexistentTarget); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/create2contractn2.sol b/framework/src/test/resources/soliditycode_0.5.15/create2contractn2.sol new file mode 100644 index 00000000000..626988c4e04 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/create2contractn2.sol @@ -0,0 +1,26 @@ +contract Factory { + event Deployed(address addr, uint256 salt, address sender); + function deploy(bytes memory code, uint256 salt) public returns(address){ + address addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed(addr, salt, msg.sender); + return addr; + } +} + + + +contract TestConstract { + uint public i=1; + function set() payable public { + i=5; + } + function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { + selfdestruct(nonexistentTarget); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/demo.sol b/framework/src/test/resources/soliditycode_0.5.15/demo.sol new file mode 100644 index 00000000000..c7f6d0d4da9 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/demo.sol @@ -0,0 +1,73 @@ +//pragma solidity ^0.4.24; + + contract tokenTest{ + uint256 codesize; + constructor() payable public{ + uint256 m; + address addr = address(this); + assembly { + m := extcodesize(addr) + } + codesize = m; + } + + // positive case + function pulsone() public payable{ + uint256 j = 0; + uint i = 100; + for (; i < i; i++) { + j++; + } + } + + + function getCodeSize() public returns (uint256){ + return codesize; + } + + } + + contract confirmTest{ + + uint256 codesize; + constructor() payable public{ + uint256 m; + address addr = address(this); + assembly { + m := extcodesize(addr) + + } + codesize = m; + } + + function getCodeSize() public returns (uint256){ + return codesize; + } + + function confirm(address addr) public returns (uint256){ + uint256 j; + assembly { + j := extcodesize(addr) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + return j; + } + + function at(address _addr) public returns (bytes memory o_code) { + assembly { + // retrieve the size of the code, this needs assembly + let size := extcodesize(_addr) + // allocate output byte array - this could also be done without assembly + // by using o_code = new bytes(size) + o_code := mload(0x40) + // new "memory end" including padding + mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f)))) + // store length in memory + mstore(o_code, size) + // actually retrieve the code, this needs assembly + extcodecopy(_addr, add(o_code, 0x20), 0, size) + } + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/event001.sol b/framework/src/test/resources/soliditycode_0.5.15/event001.sol new file mode 100644 index 00000000000..7662df3a5c6 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/event001.sol @@ -0,0 +1,10 @@ +contract Event { + event xixi(uint256 id) ; + event log2(uint256,uint256,uint256); + constructor() public payable{} + function messageI() payable public returns (uint ret) { + //emit log2(1,2,3); + emit xixi(1); + return 1; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/event002.sol b/framework/src/test/resources/soliditycode_0.5.15/event002.sol new file mode 100644 index 00000000000..70a5275521c --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/event002.sol @@ -0,0 +1,52 @@ +pragma solidity >=0.4.0 <0.7.0; + +contract Event { + + event _0(); + event a_0() anonymous; + event a_4i(uint256 indexed x1, uint256 indexed x2 , uint256 indexed x3, uint256 indexed x4, uint256 x5)anonymous ; + event _3i(uint256 x1, uint256 indexed x2 , uint256 indexed x3, uint256 x4, uint256 x5) ; + event _1i(uint256 indexed x1, uint256, uint256 indexed, uint256 x4) ; + event a_1i(uint256) anonymous; + event _ai(uint8[2], uint8) ; + event a_ai(uint8[2], uint8) anonymous; + event _a1i(uint8[2] indexed, uint8) ; + event a_a1i(uint8[2] indexed, uint8) anonymous; + + constructor () public { + // emit a_0(); + // emit a_1i(123); + // emit a_4i(1,2,3,5,16); + // emit _0(); + emit _3i(1,2,3,5,16); + // emit _1i(1,2,3,5); + // emit _ai([1,2], 3); + // emit a_ai([3,4], 5); + // emit _a1i([1,2], 3); + // emit a_a1i([3,4], 5); + } + + function e() public { + emit _1i(1,2,3,4); + } + + function l() public { + emit a_1i(1); + } + + function k() public{ + emit a_4i(2,3,4,5,17); + emit _3i(2,3,4,5,16); + emit _1i(2,3,4,5); + emit a_1i(128); + emit _0(); + emit a_0(); + //selfdestruct(msg.sender); + //emit a_4i(1,2,3,5,16); + //emit _3i(1,2,3,5,16); + //emit _1i(1,2,3,5); + //emit a_1i(123); + //emit _0(); + //emit a_0(); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/extCodeHash.sol b/framework/src/test/resources/soliditycode_0.5.15/extCodeHash.sol new file mode 100644 index 00000000000..d6209770682 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/extCodeHash.sol @@ -0,0 +1,13 @@ +contract TestExtCodeHash { + + function getCodeHashByAddr(address _addr) public returns (bytes32 _hash) { + assembly { + _hash := extcodehash(_addr) + } + } + function getCodeHashByUint(uint256 _addr) public returns (bytes32 _hash) { + assembly { + _hash := extcodehash(_addr) + } + } +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/extCodeHash11.sol b/framework/src/test/resources/soliditycode_0.5.15/extCodeHash11.sol new file mode 100644 index 00000000000..ad59f6cce1c --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/extCodeHash11.sol @@ -0,0 +1,103 @@ +contract Counter { +uint count = 0; +address payable owner; +event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); +constructor() public{ +owner = msg.sender; +} +function getCodeHashByAddr() public returns (bytes32 _hashBefore, bytes32 _hashAfter) { +address addr = address(this); +assembly { +_hashBefore := extcodehash(addr) +} +if (owner == msg.sender) { +selfdestruct(owner); +} +assembly { +_hashAfter := extcodehash(addr) +} +revert(); +emit LogResult(_hashBefore, _hashAfter); +} +} + +contract Counter1 { +uint count = 0; +address payable owner; +event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); +constructor() public{ +owner = msg.sender; +} +function getCodeHashByAddr() public returns (bytes32 _hashBefore, bytes32 _hashAfter) { +address addr = address(this); +assembly { +_hashBefore := extcodehash(addr) +} +if (owner == msg.sender) { +selfdestruct(owner); +} +assembly { +_hashAfter := extcodehash(addr) +} + +emit LogResult(_hashBefore, _hashAfter); +} +} + + +contract Counter2 { +uint count = 0; +address payable owner; +event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); +constructor() public{ +owner = msg.sender; +} +function getCodeHashByAddr(address c) public returns (bytes32 _hashBefore, bytes32 _hashAfter) { + TestConstract t=new TestConstract(); +address addr = address(t); +assembly { +_hashBefore := extcodehash(addr) +} + addr.call(abi.encodeWithSignature("testSuicideNonexistentTarget(address)",c)); + + +assembly { +_hashAfter := extcodehash(addr) +} + +emit LogResult(_hashBefore, _hashAfter); +} +} + + +contract Counter3 { +uint count = 0; +address payable owner; +event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); +constructor() public{ +owner = msg.sender; +} +function getCodeHashByAddr(address c) public returns (bytes32 _hashBefore, bytes32 _hashAfter) { + TestConstract t=new TestConstract(); +address addr = address(t); +assembly { +_hashBefore := extcodehash(addr) +} +if (owner == msg.sender) { +selfdestruct(owner); +} + +assembly { +_hashAfter := extcodehash(addr) +} + +emit LogResult(_hashBefore, _hashAfter); +} +} + +contract TestConstract { + uint public i=1; + function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { + selfdestruct(nonexistentTarget); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/extCodeHashConstruct.sol b/framework/src/test/resources/soliditycode_0.5.15/extCodeHashConstruct.sol new file mode 100644 index 00000000000..6bb91b3d3b1 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/extCodeHashConstruct.sol @@ -0,0 +1,14 @@ +contract CounterConstruct { + uint count = 0; + address payable owner; + event LogResult(bytes32 _hashBefore); + constructor() public{ + owner = msg.sender; + address addr = address(this); + bytes32 _hashBefore; + assembly { + _hashBefore := extcodehash(addr) + } + emit LogResult(_hashBefore); + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/extCodeHashStress.sol b/framework/src/test/resources/soliditycode_0.5.15/extCodeHashStress.sol new file mode 100644 index 00000000000..cf41f3c8106 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/extCodeHashStress.sol @@ -0,0 +1,45 @@ +contract Trigger { + function test(address addr) public returns(uint i) { + bytes32 hash; + while (gasleft() > 1000) { + assembly { + hash := extcodehash(addr) + } + i++; + } + } + + function test(address[] memory addrs) public returns(uint i) { + bytes32 hash; + uint i = 0; + for (; i < addrs.length; i++) { + address addr = addrs[i]; + assembly { + hash := extcodehash(addr) + } + } + return i; + } + } + + + + contract TriggerNormal { + function test(address addr) public returns(uint i) { + i = 0; + while (gasleft() > 100000) { + i++; + } + } + } + + contract TriggerNormal1 { + function test(address[] memory addrs) public returns(uint i) { + bytes32 hash; + uint i = 0; + for (; i < addrs.length; i++) { + address addr = addrs[i]; + addr.balance; + } + } + } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/extCodeHashTestNoPayable.sol b/framework/src/test/resources/soliditycode_0.5.15/extCodeHashTestNoPayable.sol new file mode 100644 index 00000000000..c3a2ad8c6ae --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/extCodeHashTestNoPayable.sol @@ -0,0 +1,8 @@ +contract testConstantContract{ +uint256 public i; +function testNoPayable() public returns (uint256 z) { +i=1; +z=i; +return z; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/isSRCandidate.sol b/framework/src/test/resources/soliditycode_0.5.15/isSRCandidate.sol new file mode 100644 index 00000000000..723e6d0e93a --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/isSRCandidate.sol @@ -0,0 +1,35 @@ + +pragma solidity ^0.5.0; + +contract ContractB{ + address others; +} + +contract TestIsSRCandidate{ + + ContractB contractB = new ContractB(); + + function isSRCandidateTest(address addr) public view returns (bool) { + return address(addr).isSRCandidate; + } + + function zeroAddressTest() public view returns (bool) { + return address(0x0).isSRCandidate; + } + + function localContractAddrTest() public view returns (bool) { + return address(this).isSRCandidate; + } + + function otherContractAddrTest() public view returns (bool) { + return address(contractB).isSRCandidate; + } + + function nonpayableAddrTest(address addr) public view returns (bool) { + return addr.isSRCandidate; + } + + function payableAddrTest(address payable addr) public returns (bool) { + return addr.isSRCandidate; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/mappingGetter.sol b/framework/src/test/resources/soliditycode_0.5.15/mappingGetter.sol new file mode 100644 index 00000000000..dbd473717cb --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/mappingGetter.sol @@ -0,0 +1,4 @@ +contract mappingGetter { + mapping(bytes => uint256) public balances1; + mapping(string => uint256) public balances2; +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/multiValiSignPerformance01.sol b/framework/src/test/resources/soliditycode_0.5.15/multiValiSignPerformance01.sol new file mode 100644 index 00000000000..74baa963366 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/multiValiSignPerformance01.sol @@ -0,0 +1,37 @@ +pragma experimental ABIEncoderV2; + +contract ecrecoverValidateSign { + + using ECVerify for bytes32; + + function validateSign(bytes32 hash,bytes[] memory sig,address[] memory signer) public returns (bool) { + for(uint256 i=0;i bytes32) public nullifiers; // store nullifiers of spent commitments + mapping(bytes32 => bytes32) public roots; // store history root + mapping(uint256 => bytes32) public tree; + mapping(bytes32 => bytes32) public noteCommitment; + bytes32[33] frontier; + bytes32[32] zeroes = [bytes32(0x0100000000000000000000000000000000000000000000000000000000000000), bytes32(0x817de36ab2d57feb077634bca77819c8e0bd298c04f6fed0e6a83cc1356ca155), bytes32(0xffe9fc03f18b176c998806439ff0bb8ad193afdb27b2ccbc88856916dd804e34), bytes32(0xd8283386ef2ef07ebdbb4383c12a739a953a4d6e0d6fb1139a4036d693bfbb6c), bytes32(0xe110de65c907b9dea4ae0bd83a4b0a51bea175646a64c12b4c9f931b2cb31b49), bytes32(0x912d82b2c2bca231f71efcf61737fbf0a08befa0416215aeef53e8bb6d23390a), bytes32(0x8ac9cf9c391e3fd42891d27238a81a8a5c1d3a72b1bcbea8cf44a58ce7389613), bytes32(0xd6c639ac24b46bd19341c91b13fdcab31581ddaf7f1411336a271f3d0aa52813), bytes32(0x7b99abdc3730991cc9274727d7d82d28cb794edbc7034b4f0053ff7c4b680444), bytes32(0x43ff5457f13b926b61df552d4e402ee6dc1463f99a535f9a713439264d5b616b), bytes32(0xba49b659fbd0b7334211ea6a9d9df185c757e70aa81da562fb912b84f49bce72), bytes32(0x4777c8776a3b1e69b73a62fa701fa4f7a6282d9aee2c7a6b82e7937d7081c23c), bytes32(0xec677114c27206f5debc1c1ed66f95e2b1885da5b7be3d736b1de98579473048), bytes32(0x1b77dac4d24fb7258c3c528704c59430b630718bec486421837021cf75dab651), bytes32(0xbd74b25aacb92378a871bf27d225cfc26baca344a1ea35fdd94510f3d157082c), bytes32(0xd6acdedf95f608e09fa53fb43dcd0990475726c5131210c9e5caeab97f0e642f), bytes32(0x1ea6675f9551eeb9dfaaa9247bc9858270d3d3a4c5afa7177a984d5ed1be2451), bytes32(0x6edb16d01907b759977d7650dad7e3ec049af1a3d875380b697c862c9ec5d51c), bytes32(0xcd1c8dbf6e3acc7a80439bc4962cf25b9dce7c896f3a5bd70803fc5a0e33cf00), bytes32(0x6aca8448d8263e547d5ff2950e2ed3839e998d31cbc6ac9fd57bc6002b159216), bytes32(0x8d5fa43e5a10d11605ac7430ba1f5d81fb1b68d29a640405767749e841527673), bytes32(0x08eeab0c13abd6069e6310197bf80f9c1ea6de78fd19cbae24d4a520e6cf3023), bytes32(0x0769557bc682b1bf308646fd0b22e648e8b9e98f57e29f5af40f6edb833e2c49), bytes32(0x4c6937d78f42685f84b43ad3b7b00f81285662f85c6a68ef11d62ad1a3ee0850), bytes32(0xfee0e52802cb0c46b1eb4d376c62697f4759f6c8917fa352571202fd778fd712), bytes32(0x16d6252968971a83da8521d65382e61f0176646d771c91528e3276ee45383e4a), bytes32(0xd2e1642c9a462229289e5b0e3b7f9008e0301cbb93385ee0e21da2545073cb58), bytes32(0xa5122c08ff9c161d9ca6fc462073396c7d7d38e8ee48cdb3bea7e2230134ed6a), bytes32(0x28e7b841dcbc47cceb69d7cb8d94245fb7cb2ba3a7a6bc18f13f945f7dbd6e2a), bytes32(0xe1f34b034d4a3cd28557e2907ebf990c918f64ecb50a94f01d6fda5ca5c7ef72), bytes32(0x12935f14b676509b81eb49ef25f39269ed72309238b4c145803544b646dca62d), bytes32(0xb2eed031d4d6a4f02a097f80b54cc1541d4163c6b6f5971f88b6e41d35c53814)]; + address owner; + TokenTRC20 trc20Token; + + event MintNewLeaf(uint256 position, bytes32 cm, bytes32 cv, bytes32 epk, bytes32[21] c); + event TransferNewLeaf(uint256 position, bytes32 cm, bytes32 cv, bytes32 epk, bytes32[21] c); + event BurnNewLeaf(uint256 position, bytes32 cm, bytes32 cv, bytes32 epk, bytes32[21] c); + event TokenMint(address from, uint256 value); + event TokenBurn(address to, uint256 value, bytes32[3] ciphertext); + event NoteSpent(bytes32 nf); + + constructor (address trc20ContractAddress, uint256 scalingFactorExponent) public { + require(scalingFactorExponent < 77, "The scalingFactorExponent is out of range!"); + scalingFactor = 10 ** scalingFactorExponent; + owner = msg.sender; + trc20Token = TokenTRC20(trc20ContractAddress); + } + // output: cm, cv, epk, proof + function mint(uint256 rawValue, bytes32[9] calldata output, bytes32[2] calldata bindingSignature, bytes32[21] calldata c) external { + address sender = msg.sender; + // transfer the trc20Token from the sender to this contract + bool transferResult = trc20Token.transferFrom(sender, address(this), rawValue); + require(transferResult, "TransferFrom failed!"); + + require(noteCommitment[output[0]] == 0, "Duplicate noteCommitments!"); + uint64 value = rawValueToValue(rawValue); + bytes32 signHash = sha256(abi.encodePacked(address(this), value, output, c)); + (bytes32[] memory ret) = verifyMintProof(output, bindingSignature, value, signHash, frontier, leafCount); + uint256 result = uint256(ret[0]); + require(result == 1, "The proof and signature have not been verified by the contract!"); + + uint256 slot = uint256(ret[1]); + uint256 nodeIndex = leafCount + 2 ** 32 - 1; + tree[nodeIndex] = output[0]; + if (slot == 0) { + frontier[0] = output[0]; + } + for (uint256 i = 1; i < slot + 1; i++) { + nodeIndex = (nodeIndex - 1) / 2; + tree[nodeIndex] = ret[i + 1]; + if (i == slot) { + frontier[slot] = tree[nodeIndex]; + } + } + latestRoot = ret[slot + 2]; + roots[latestRoot] = latestRoot; + noteCommitment[output[0]] = output[0]; + leafCount ++; + + emit MintNewLeaf(leafCount - 1, output[0], output[1], output[2], c); + emit TokenMint(sender, rawValue); + } + //input: nf, anchor, cv, rk, proof + //output: cm, cv, epk, proof + function transfer(bytes32[10][] calldata input, bytes32[2][] calldata spendAuthoritySignature, bytes32[9][] calldata output, bytes32[2] calldata bindingSignature, bytes32[21][] calldata c) external { + require(input.length >= 1 && input.length <= 2, "Input number must be 1 or 2!"); + require(input.length == spendAuthoritySignature.length, "Input number must be equal to spendAuthoritySignature number!"); + require(output.length >= 1 && output.length <= 2, "Output number must be 1 or 2!"); + require(output.length == c.length, "Output number must be equal to c number!"); + + for (uint256 i = 0; i < input.length; i++) { + require(nullifiers[input[i][0]] == 0, "The note has already been spent!"); + require(roots[input[i][1]] != 0, "The anchor must exist!"); + } + for (uint256 i = 0; i < output.length; i++) { + require(noteCommitment[output[i][0]] == 0, "Duplicate noteCommitment!"); + } + + bytes32 signHash = sha256(abi.encodePacked(address(this), input, output, c)); + (bytes32[] memory ret) = verifyTransferProof(input, spendAuthoritySignature, output, bindingSignature, signHash, 0, frontier, leafCount); + uint256 result = uint256(ret[0]); + require(result == 1, "The proof and signature have not been verified by the contract!"); + + uint256 offset = 1; + //ret offset + for (uint256 i = 0; i < output.length; i++) { + uint256 slot = uint256(ret[offset++]); + uint256 nodeIndex = leafCount + 2 ** 32 - 1; + tree[nodeIndex] = output[i][0]; + if (slot == 0) { + frontier[0] = output[i][0]; + } + for (uint256 k = 1; k < slot + 1; k++) { + nodeIndex = (nodeIndex - 1) / 2; + tree[nodeIndex] = ret[offset++]; + if (k == slot) { + frontier[slot] = tree[nodeIndex]; + } + } + leafCount++; + } + latestRoot = ret[offset]; + roots[latestRoot] = latestRoot; + for (uint256 i = 0; i < input.length; i++) { + bytes32 nf = input[i][0]; + nullifiers[nf] = nf; + emit NoteSpent(nf); + } + for (uint256 i = 0; i < output.length; i++) { + noteCommitment[output[i][0]] = output[i][0]; + emit TransferNewLeaf(leafCount - (output.length - i), output[i][0], output[i][1], output[i][2], c[i]); + } + } + //input: nf, anchor, cv, rk, proof + //output: cm, cv, epk, proof + function burn(bytes32[10] calldata input, bytes32[2] calldata spendAuthoritySignature, uint256 rawValue, bytes32[2] calldata bindingSignature, address payTo, bytes32[3] calldata burnCipher, bytes32[9][] calldata output, bytes32[21][] calldata c) external { + uint64 value = rawValueToValue(rawValue); + bytes32 signHash = sha256(abi.encodePacked(address(this), input, output, c, payTo, value)); + + bytes32 nf = input[0]; + bytes32 anchor = input[1]; + require(nullifiers[nf] == 0, "The note has already been spent!"); + require(roots[anchor] != 0, "The anchor must exist!"); + + require(output.length <= 1, "Output number cannot exceed 1!"); + require(output.length == c.length, "Output number must be equal to length of c!"); + + // bytes32 signHash = sha256(abi.encodePacked(address(this), input, payTo, value, output, c)); + if (output.length == 0) { + (bool result) = verifyBurnProof(input, spendAuthoritySignature, value, bindingSignature, signHash); + require(result, "The proof and signature have not been verified by the contract!"); + } else { + transferInBurn(input, spendAuthoritySignature, value, bindingSignature, signHash, output, c); + } + + nullifiers[nf] = nf; + emit NoteSpent(nf); + //Finally, transfer trc20Token from this contract to the nominated address + bool transferResult = trc20Token.transfer(payTo, rawValue); + require(transferResult, "Transfer failed!"); + + emit TokenBurn(payTo, rawValue, burnCipher); + } + + function transferInBurn(bytes32[10] memory input, bytes32[2] memory spendAuthoritySignature, uint64 value, bytes32[2] memory bindingSignature, bytes32 signHash, bytes32[9][] memory output, bytes32[21][] memory c) private { + bytes32 cm = output[0][0]; + require(noteCommitment[cm] == 0, "Duplicate noteCommitment!"); + bytes32[10][] memory inputs = new bytes32[10][](1); + inputs[0] = input; + bytes32[2][] memory spendAuthoritySignatures = new bytes32[2][](1); + spendAuthoritySignatures[0] = spendAuthoritySignature; + (bytes32[] memory ret) = verifyTransferProof(inputs, spendAuthoritySignatures, output, bindingSignature, signHash, value, frontier, leafCount); + uint256 result = uint256(ret[0]); + require(result == 1, "The proof and signature have not been verified by the contract!"); + + uint256 slot = uint256(ret[1]); + uint256 nodeIndex = leafCount + 2 ** 32 - 1; + tree[nodeIndex] = cm; + if (slot == 0) { + frontier[0] = cm; + } + for (uint256 i = 1; i < slot + 1; i++) { + nodeIndex = (nodeIndex - 1) / 2; + tree[nodeIndex] = ret[i + 1]; + if (i == slot) { + frontier[slot] = tree[nodeIndex]; + } + } + latestRoot = ret[slot + 2]; + roots[latestRoot] = latestRoot; + noteCommitment[cm] = cm; + leafCount ++; + + emit BurnNewLeaf(leafCount - 1, cm, output[0][1], output[0][2], c[0]); + } + + //position: index of leafnode, start from 0 + function getPath(uint256 position) public view returns (bytes32, bytes32[32] memory) { + require(position >= 0, "Position should be non-negative!"); + require(position < leafCount, "Position should be smaller than leafCount!"); + uint256 index = position + 2 ** 32 - 1; + bytes32[32] memory path; + uint32 level = ancestorLevel(position); + bytes32 targetNodeValue = getTargetNodeValue(position, level); + for (uint32 i = 0; i < 32; i++) { + if (i == level) { + path[31 - i] = targetNodeValue; + } else { + if (index % 2 == 0) { + path[31 - i] = tree[index - 1]; + } else { + path[31 - i] = tree[index + 1] == 0 ? zeroes[i] : tree[index + 1]; + } + } + index = (index - 1) / 2; + } + return (latestRoot, path); + } + + //position: index of leafnode, start from 0 + function getPathByValueIsZero(uint256 position) public view returns (bytes32, bytes32[32] memory) { + require(position >= 0, "Position should be non-negative!"); + require(position < leafCount, "Position should be smaller than leafCount!"); + uint256 index = position + 2 ** 32 - 1; + bytes32[32] memory path; + uint32 level = ancestorLevel(position); + bytes32 targetNodeValue = getTargetNodeValueByValueIsZero(position, level); + for (uint32 i = 0; i < 32; i++) { + if (i == level) { + path[31 - i] = targetNodeValue; + } else { + if (index % 2 == 0) { + path[31 - i] = tree[index - 1]; + } else { + path[31 - i] = tree[index + 1] == 0 ? zeroes[i] : tree[index + 1]; + } + } + index = (index - 1) / 2; + } + return (latestRoot, path); + } + + function ancestorLevel(uint256 leafIndex) private view returns (uint32) { + uint256 nodeIndex1 = leafIndex + 2 ** 32 - 1; + uint256 nodeIndex2 = leafCount + 2 ** 32 - 2; + uint32 level = 0; + while (((nodeIndex1 - 1) / 2) != ((nodeIndex2 - 1) / 2)) { + nodeIndex1 = (nodeIndex1 - 1) / 2; + nodeIndex2 = (nodeIndex2 - 1) / 2; + level = level + 1; + } + return level; + } + + function getTargetNodeValue(uint256 leafIndex, uint32 level) private view returns (bytes32) { + bytes32 left; + bytes32 right; + uint256 index = leafIndex + 2 ** 32 - 1; + uint256 nodeIndex = leafCount + 2 ** 32 - 2; + bytes32 nodeValue = tree[nodeIndex]; + if (level == 0) { + if (index < nodeIndex) { + return nodeValue; + } + if (index == nodeIndex) { + if (index % 2 == 0) { + return tree[index - 1]; + } else { + return zeroes[0]; + } + } + } + for (uint32 i = 0; i < level; i++) { + if (nodeIndex % 2 == 0) { + left = tree[nodeIndex - 1]; + right = nodeValue; + } else { + left = nodeValue; + right = zeroes[i]; + } + nodeValue = pedersenHash(i, left, right); + nodeIndex = (nodeIndex - 1) / 2; + } + return nodeValue; + } + + function getTargetNodeValueByValueIsZero(uint256 leafIndex, uint32 level) private view returns (bytes32) { + bytes32 left; + bytes32 right; + uint256 index = leafIndex + 2 ** 32 - 1; + uint256 nodeIndex = leafCount + 2 ** 32 - 2; + bytes32 nodeValue = tree[nodeIndex]; + if (level == 0) { + if (index < nodeIndex) { + return nodeValue; + } + if (index == nodeIndex) { + if (index % 2 == 0) { + return tree[index - 1]; + } else { + return zeroes[0]; + } + } + } + for (uint32 i = 0; i < level; i++) { + if (nodeIndex % 2 == 0) { + left = tree[nodeIndex - 1]; + right = nodeValue; + } else { + left = nodeValue; + right = zeroes[i]; + } + left = bytes32(0x0); + right = bytes32(0x0); + nodeValue = pedersenHash(i, left, right); + nodeIndex = (nodeIndex - 1) / 2; + } + return nodeValue; + } + + function rawValueToValue(uint256 rawValue) private view returns (uint64) { + require(rawValue > 0, "Value must be positive!"); + require(rawValue.mod(scalingFactor) == 0, "Value must be integer multiples of scalingFactor!"); + uint256 value = rawValue.div(scalingFactor); + require(value < INT64_MAX); + return uint64(value); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest1TestRequireContract.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest1TestRequireContract.sol new file mode 100644 index 00000000000..dbb97ab4f04 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest1TestRequireContract.sol @@ -0,0 +1,15 @@ +//pragma solidity ^0.4.0; +contract TestThrowsContract{ + function testAssert() public { + assert(1==2); + } + function testRequire() public { + require(2==1); + } + function testRevert() public { + revert(); + } + //function testThrow(){ + // throw; + //} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest2TestThrowsContract.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest2TestThrowsContract.sol new file mode 100644 index 00000000000..abcc2d84ca2 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest2TestThrowsContract.sol @@ -0,0 +1,15 @@ +//pragma solidity ^0.4.0; +contract TestThrowsContract{ + function testAssert() public { + assert(1==2); + } + function testRequire() public { + require(2==1); + } + function testRevert() public { + revert(); + } + // function testThrow() public { + // throw; + //} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest3TestRevertContract.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest3TestRevertContract.sol new file mode 100644 index 00000000000..229fa6a74b0 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest3TestRevertContract.sol @@ -0,0 +1,15 @@ +//pragma solidity ^0.4.0; +contract TestThrowsContract{ + function testAssert() public { + assert(1==2); + } + function testRequire() public { + require(2==1); + } + function testRevert() public { + revert(); + } + // function testThrow(){ + // throw; + // } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest4noPayableContract.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest4noPayableContract.sol new file mode 100644 index 00000000000..aa043ad9c3b --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest4noPayableContract.sol @@ -0,0 +1,8 @@ +//pragma solidity ^0.4.0; + +contract noPayableContract { + +function noPayable() public payable returns (uint){ +return msg.value; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest4noPayableContract_1.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest4noPayableContract_1.sol new file mode 100644 index 00000000000..fe7ba275736 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest4noPayableContract_1.sol @@ -0,0 +1,8 @@ +//pragma solidity ^0.4.0; + +contract noPayableContract { + +function noPayable() public returns (uint){ +return msg.value; +} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest5noPayableConstructor.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest5noPayableConstructor.sol new file mode 100644 index 00000000000..e1733b0562b --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest5noPayableConstructor.sol @@ -0,0 +1,11 @@ +//pragma solidity ^0.4.0; + +contract MyContract { + uint money; + + //function MyContract(uint _money) { + constructor(uint _money) public payable{ + require(msg.value >= _money); + money = _money; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest5noPayableConstructor_1.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest5noPayableConstructor_1.sol new file mode 100644 index 00000000000..793b468d4c2 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest5noPayableConstructor_1.sol @@ -0,0 +1,11 @@ +//pragma solidity ^0.4.0; + +contract MyContract { + uint money; + + //function MyContract(uint _money) { + constructor(uint _money) public { + require(msg.value >= _money); + money = _money; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest6transferTestContract.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest6transferTestContract.sol new file mode 100644 index 00000000000..8c64ff740cd --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest6transferTestContract.sol @@ -0,0 +1,8 @@ +//pragma solidity ^0.4.0; + +contract transferTestContract { + function tranferTest(address payable addr) public payable{ + addr.transfer(10); + + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest7payableFallbakContract.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest7payableFallbakContract.sol new file mode 100644 index 00000000000..85cf454e08e --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest7payableFallbakContract.sol @@ -0,0 +1,14 @@ +//pragma solidity ^0.4.0; + +contract Test { + function() external { x = 1; } + uint x; +} + + +contract Caller { + function callTest(Test test) public { + //test.call(0xabcdef01); // hash does not exist + address(test).call(abi.encode(0xabcdef01)); // hash does not exist + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest8newContractGasNoenough.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest8newContractGasNoenough.sol new file mode 100644 index 00000000000..b322ac68591 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest8newContractGasNoenough.sol @@ -0,0 +1,19 @@ +//pragma solidity ^0.4.0; + +contract Account{ + uint256 public accId; + + // function Account(uint accountId) payable{ + constructor(uint accountId) payable public { + accId = accountId; + } +} + +contract Initialize{ + // Account public account = new Account(10); + + function newAccount() public { + Account account = new Account(1); + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest9MessageUsedErrorFeed.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest9MessageUsedErrorFeed.sol new file mode 100644 index 00000000000..05448bfd0ac --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest9MessageUsedErrorFeed.sol @@ -0,0 +1,18 @@ +//pragma solidity ^0.4.0; + +contract MathedFeed { + + function divideMathed() public returns (uint ret) { + uint x=1; + uint y=0; + return x/y; + } +} + + +contract MathedUseContract { + + function MathedUse(address addr) public returns (uint) { + return MathedFeed(addr).divideMathed(); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontestFunctionUsedErrorFeed.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontestFunctionUsedErrorFeed.sol new file mode 100644 index 00000000000..b7f5244954d --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontestFunctionUsedErrorFeed.sol @@ -0,0 +1,17 @@ +//pragma solidity ^0.4.0; + +contract MessageFeed { + + function mValue() payable public returns (uint ret) { + return msg.value; + } +} + +contract MessageUseContract { + function inputValue() payable public returns (uint){ + return msg.value; + } + function messageUse(address addr) payable public returns (uint) { + return MessageFeed(addr).mValue.value(1)(); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/selector.sol b/framework/src/test/resources/soliditycode_0.5.15/selector.sol new file mode 100644 index 00000000000..411e36b0b8e --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/selector.sol @@ -0,0 +1,21 @@ +pragma solidity ^0; + +library A { + function getBalance(address) public view returns (uint256) { + return address(this).balance; + } + + function getamount(address) external view returns (uint256) { + return address(this).balance; + } +} + +contract testSelector { + using A for address; + + + function getselector2() public view returns (bytes4, bytes4) { + return (A.getBalance.selector, A.getamount.selector); + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/stackContract001.sol b/framework/src/test/resources/soliditycode_0.5.15/stackContract001.sol new file mode 100644 index 00000000000..19041b1e405 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/stackContract001.sol @@ -0,0 +1,61 @@ +pragma solidity ^0.5.0; + +contract A{ + event log(uint256); + constructor() payable public{ + emit log(withdrawreward()); + emit log(address(this).rewardbalance); + } + function withdrawRewardTest() public returns (uint256){ + return withdrawreward(); + } + + function test() public{ + emit log(123); + } +} + +contract B{ + event log(uint256); + constructor() payable public{ + emit log(withdrawreward()); + emit log(address(this).rewardbalance); + } + function Stake(address sr, uint256 amount) public returns (bool result){ + return stake(sr, amount); + } + function UnStake() public returns (bool result){ + return unstake(); + } + function SelfdestructTest(address payable target) public{ + selfdestruct(target); + } + function rewardBalance(address addr) public view returns (uint256){ + return addr.rewardbalance; + } + + function nullAddressTest() public view returns (uint256) { + return address(0x0).rewardbalance; + } + + function localContractAddrTest() public view returns (uint256) { + address payable localContract = address(uint160(address(this))); + return localContract.rewardbalance; + } + + function withdrawRewardTest() public returns (uint256){ + return withdrawreward(); + } + + function contractBWithdrawRewardTest(address contractB) public returns (uint) { + return B(contractB).withdrawRewardTest(); + } + + function createA() public returns (address){ + return address(new A()); + } + + function callA(address Addr) public{ + A(Addr).test(); + } +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/stackSuicide001.sol b/framework/src/test/resources/soliditycode_0.5.15/stackSuicide001.sol new file mode 100644 index 00000000000..a71816ddabd --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/stackSuicide001.sol @@ -0,0 +1,84 @@ +pragma solidity ^0.5.0; +contract testStakeSuicide{ + B b; + constructor() payable public{} + function deployB() payable public returns (B addrB){ + b = (new B).value(1000000000)(); + return b; + } + function SelfdestructTest(address payable target) public{ + selfdestruct(target); + } + function SelfdestructTest2(address sr, uint256 amount, address payable target) public{ + stake(sr, amount); + selfdestruct(target); + } + function Stake(address sr, uint256 amount) public payable returns (bool result){ + return stake(sr, amount); + } + function Stake2(address sr, uint256 amount) public returns (bool result){ + stake(sr, amount); + return stake(sr, amount); + } + function UnStake() public returns (bool result){ + return unstake(); + } + function UnStake2() public returns (bool result){ + unstake(); + return unstake(); + } + function WithdrawReward() public { + withdrawreward(); + } + function RewardBalance(address addr) view public returns (uint256 balance) { + return addr.rewardbalance; + } + function revertTest1(address sr, uint256 amount, address payable transferAddr) public{ + transferAddr.transfer(1000000); + stake(sr, amount); + transferAddr.transfer(2000000); + stake(sr, 1000000000000000);//stake more than balance to fail + transferAddr.transfer(4000000); + } + function revertTest2(address payable transferAddr) public{ + transferAddr.transfer(1000000); + unstake(); + transferAddr.transfer(2000000); + unstake();//unstake twice to fail + transferAddr.transfer(4000000); + } + + function BStake(address sr, uint256 amount) public returns (bool result){ + return b.Stake(sr, amount); + } + function BUnStake() public returns (bool result){ + return b.UnStake(); + } + function transfer(address payable add,uint256 num) public { + return add.transfer(num); + } +} + +contract B{ + constructor() payable public{} + function Stake(address sr, uint256 amount) public returns (bool result){ + return stake(sr, amount); + } + function UnStake() public returns (bool result){ + return unstake(); + } + function SelfdestructTest(address payable target) public{ + selfdestruct(target); + } + + function deploy(bytes memory code, uint256 salt) public returns(address) { + address addr; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + return addr; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/stringSplit.sol b/framework/src/test/resources/soliditycode_0.5.15/stringSplit.sol new file mode 100644 index 00000000000..5a7f5bdd4c9 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/stringSplit.sol @@ -0,0 +1,45 @@ +pragma solidity ^0; + +contract testStringSplit { +string s1 = "s""1""2"",./"; +string s2 = "s123?\\'."; +string s3 = hex"41"hex"42"; +string s4 = hex"4142"; + +function getS1() public view returns (string memory) { +return s1; +} + +function getS1N1() public pure returns (string memory) { +string memory n1 = "s""1""2"",./"; +return n1; +} + +function getS2() public view returns (string memory) { +return s2; +} + +function getS2N2() public pure returns (string memory) { +string memory n2 = "s123?\'."; +return n2; +} + +function getS3() public view returns (string memory) { +return s3; +} + +function getS3N3() public pure returns (string memory) { +string memory n3 = hex"41"hex"42"; +return n3; +} + +function getS4() public view returns (string memory) { +return s4; +} + +function getS4N4() public pure returns (string memory) { +string memory n4 = hex"4142"; +return n4; +} + +} diff --git a/framework/src/test/resources/soliditycode_0.5.15/suicide001.sol b/framework/src/test/resources/soliditycode_0.5.15/suicide001.sol new file mode 100644 index 00000000000..3544f8bf84a --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/suicide001.sol @@ -0,0 +1,32 @@ +contract factory { + constructor() payable public { + } + + function create1() payable public returns (address){ + Caller add = (new Caller).value(0)(); + return address(add); + } + + function kill() payable public{ + selfdestruct(msg.sender); + } + + function create2(bytes memory code, uint256 salt) public returns(address){ + Caller addr; + Caller addr1; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + return address(addr); + } +} + + + +contract Caller { + constructor() payable public {} + function test() payable public returns (uint256){return 1;} +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/suicide002.sol b/framework/src/test/resources/soliditycode_0.5.15/suicide002.sol new file mode 100644 index 00000000000..160ab64f320 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/suicide002.sol @@ -0,0 +1,43 @@ +contract Factory { + uint256 public num; + event Deployed(address addr, uint256 salt, address sender); + constructor() public { + } + function deploy(bytes memory code, uint256 salt) public returns(address){ + TestConstract addr; + TestConstract addr1; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + + addr.testSuicideNonexistentTarget(msg.sender); + addr.set(); + + assembly { + addr1 := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed(address(addr), salt, msg.sender); + return address(addr); + } +} + + + +contract TestConstract { + uint public i=1; + constructor () public { + } + + function set() public{ + i=9; + } + function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { + selfdestruct(nonexistentTarget); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/testOutOfMem.sol b/framework/src/test/resources/soliditycode_0.5.15/testOutOfMem.sol new file mode 100644 index 00000000000..8d285b28b7d --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/testOutOfMem.sol @@ -0,0 +1,7 @@ +contract Test { + function testOutOfMem(uint256 x) public returns(bytes32 r) { + uint[] memory memVar; + memVar = new uint[](x); + } + +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/testStakeSuicide.sol b/framework/src/test/resources/soliditycode_0.5.15/testStakeSuicide.sol new file mode 100644 index 00000000000..6f8ddfe0e3e --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/testStakeSuicide.sol @@ -0,0 +1,71 @@ +pragma solidity ^0.5.0; +contract testStakeSuicide{ + B b; + constructor() payable public{} + function deployB() payable public returns (B addrB){ + b = (new B).value(1000000000)(); + return b; + } + function SelfdestructTest(address payable target) public{ + selfdestruct(target); + } + function SelfdestructTest2(address sr, uint256 amount, address payable target) public{ + stake(sr, amount); + selfdestruct(target); + } + function Stake(address sr, uint256 amount) public returns (bool result){ + return stake(sr, amount); + } + function Stake2(address sr, uint256 amount) public returns (bool result){ + stake(sr, amount); + return stake(sr, amount); + } + function UnStake() public returns (bool result){ + return unstake(); + } + function UnStake2() public returns (bool result){ + unstake(); + return unstake(); + } + function WithdrawReward() public { + withdrawreward(); + } + function RewardBalance(address addr) view public returns (uint256 balance) { + return addr.rewardbalance; + } + function revertTest1(address sr, uint256 amount, address payable transferAddr) public{ + transferAddr.transfer(1000000); + stake(sr, amount); + transferAddr.transfer(2000000); + stake(sr, 1000000000000000);//stake more than balance to fail + transferAddr.transfer(4000000); + } + function revertTest2(address payable transferAddr) public{ + transferAddr.transfer(1000000); + unstake(); + transferAddr.transfer(2000000); + unstake();//unstake twice to fail + transferAddr.transfer(4000000); + } + function BStake(address sr, uint256 amount) public returns (bool result){ + return b.Stake(sr, amount); + } + function BUnStake() public returns (bool result){ + return b.UnStake(); + } + function BSelfdestructTest(address payable target) public{ + b.SelfdestructTest(target); + } +} +contract B{ + constructor() payable public{} + function Stake(address sr, uint256 amount) public returns (bool result){ + return stake(sr, amount); + } + function UnStake() public returns (bool result){ + return unstake(); + } + function SelfdestructTest(address payable target) public{ + selfdestruct(target); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/tryCatch001.sol b/framework/src/test/resources/soliditycode_0.5.15/tryCatch001.sol new file mode 100644 index 00000000000..5692fe84540 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/tryCatch001.sol @@ -0,0 +1,105 @@ +pragma solidity ^0.6.0; + +enum ErrorType { + Revert_Error, //0 + RevertWithMsg_Error, //1 + Require_Error, //2 + RequirewithMsg_Error, //3 + Assert_Error, //4 + Tansfer_Error, //5 + Send_Error, //6 + Math_Error, //7 + ArrayOverFlow_Error //8 +} +contract errorContract { + uint256[] arraryUint ; + + function errorSwitch(uint256 errorType) public returns(string memory) { + if (ErrorType(errorType) == ErrorType.Revert_Error){ + revert(); + } else if (ErrorType(errorType) == ErrorType.RevertWithMsg_Error){ + revert("Revert Msg."); + } else if (ErrorType(errorType) == ErrorType.Require_Error) { + require(0>1); + } else if (ErrorType(errorType) == ErrorType.RequirewithMsg_Error) { + require(0>1,"Require Msg."); + } else if (ErrorType(errorType) == ErrorType.Assert_Error) { + assert(1<0); + } else if (ErrorType(errorType) == ErrorType.Tansfer_Error) { + payable(msg.sender).transfer(1); + } else if (ErrorType(errorType) == ErrorType.Send_Error) { + payable(msg.sender).send(1); + } else if (ErrorType(errorType) == ErrorType.Math_Error) { + uint256 a = 1; + uint256 b = 0; + uint256 n = a / b; + } else if (ErrorType(errorType) == ErrorType.ArrayOverFlow_Error) { + arraryUint.pop(); + } + return "success"; + + } + + function callFun(string memory functionStr, string memory argsStr) public{ + address(this).call(abi.encodeWithSignature(functionStr, argsStr)); + } + +} + +contract NewContract { + uint256[] arraryUint ; + + constructor(uint256 errorType) public payable{ + if (ErrorType(errorType) == ErrorType.Revert_Error){ + revert(); + } else if (ErrorType(errorType) == ErrorType.RevertWithMsg_Error){ + revert("Revert Msg."); + } else if (ErrorType(errorType) == ErrorType.Require_Error) { + require(0>1); + } else if (ErrorType(errorType) == ErrorType.RequirewithMsg_Error) { + require(0>1,"Require Msg."); + } else if (ErrorType(errorType) == ErrorType.Assert_Error) { + assert(1<0); + } else if (ErrorType(errorType) == ErrorType.Tansfer_Error) { + payable(msg.sender).transfer(1); + } else if (ErrorType(errorType) == ErrorType.Send_Error) { + payable(msg.sender).send(1); + } else if (ErrorType(errorType) == ErrorType.Math_Error) { + uint256 a = 1; + uint256 b = 0; + uint256 n = a / b; + } else if (ErrorType(errorType) == ErrorType.ArrayOverFlow_Error) { + arraryUint.pop(); + } + } +} + +contract tryTest { + function getData(errorContract inter, string memory functionStr, string memory argsStr) public payable returns(string memory) { + try inter.callFun(functionStr,argsStr) { + return "123"; + } catch Error(string memory errorMsg/* 出错原因 */) { + return errorMsg; + } catch (bytes memory) { + return "3"; + } + } + + function getErrorSwitch(errorContract add, uint256 errorType ) public payable returns(string memory) { + try add.errorSwitch(errorType) returns (string memory Msg) { + return Msg; + } catch Error(string memory errorMsg/* 出错原因 */) { + return errorMsg; + } catch (bytes memory) { + return "NoErrorMsg"; + } + } + + function catchNewErrorSwitch(uint256 errorType) public returns (address nc){ + try new NewContract(errorType) returns (NewContract nc){ + return address(nc); + }catch { + return address(0x00); + } + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue001.sol b/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue001.sol new file mode 100644 index 00000000000..fd3c817421b --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue001.sol @@ -0,0 +1,26 @@ +pragma solidity ^0.5.12; + +contract tvmAssetIssue001 { + constructor() payable public{} + + function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { + return assetissue(name, abbr, totalSupply, precision); + } + + function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { + return updateasset(tokenId, bytes(url), bytes(desc)); + } + + function updateOtherAccountAsset(string memory url, string memory desc) public returns (bool) { + trcToken tokenId = trcToken(1000004); + return updateasset(tokenId, bytes(url), bytes(desc)); + } + + function updateAssetOnBytes(trcToken tokenId, bytes memory url, bytes memory desc) public returns (bool) { + return updateasset(tokenId, url, desc); + } + + function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { + toAddress.transferToken(tokenValue, id); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue002.sol b/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue002.sol new file mode 100644 index 00000000000..b158faf6720 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue002.sol @@ -0,0 +1,15 @@ +pragma solidity ^0.5.12; + +contract tvmAssetIssue002 { + constructor() payable public{} + + function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { + assetissue(name, abbr, totalSupply, precision); + return assetissue(name, abbr, totalSupply, precision); + } + + function updateAsset(trcToken tokenId, string memory url1, string memory desc1, string memory url2, string memory desc2) public returns (bool) { + updateasset(tokenId, bytes(url1), bytes(desc1)); + return updateasset(tokenId, bytes(url2), bytes(desc2)); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue003.sol b/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue003.sol new file mode 100644 index 00000000000..40390238d8f --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue003.sol @@ -0,0 +1,23 @@ +pragma solidity ^0.5.12; + +contract tvmAssetIssue003 { + constructor() payable public{} + + function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { + return assetissue(name, abbr, totalSupply, precision); + } + + function tokenIssueAndTransfer(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision, address addr) public { + address payable newaddress = address(uint160(addr)); + newaddress.transfer(100000000); + assetissue(name, abbr, totalSupply, precision); + newaddress.transfer(100000000); + } + + function updateAssetAndTransfer(trcToken tokenId, string memory url, string memory desc, address addr) public { + address payable newaddress = address(uint160(addr)); + newaddress.transfer(100000000); + updateasset(tokenId, bytes(url), bytes(desc)); + newaddress.transfer(100000000); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue004.sol b/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue004.sol new file mode 100644 index 00000000000..fbebdb26e68 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue004.sol @@ -0,0 +1,39 @@ +pragma solidity ^0.5.12; + +contract A { + + constructor() payable public{} + function() payable external {} + + function tokenIssueA(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint){ + return assetissue(name, abbr, totalSupply, precision); + } + + function updateAssetA(trcToken tokenId, string memory url, string memory desc) public returns (bool) { + return updateasset(tokenId, bytes(url), bytes(desc)); + } + + function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { + toAddress.transferToken(tokenValue, id); + } +} + +contract tvmAssetIssue004 { + + A a; + + constructor() payable public{} + + function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { + return a.tokenIssueA(name, abbr, totalSupply, precision); + } + + function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { + return a.updateAssetA(tokenId, url, desc); + } + + function getContractAddress() public payable returns (address) { + a = (new A).value(1024000000)(); + return address(a); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue005.sol b/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue005.sol new file mode 100644 index 00000000000..20fd14944c2 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue005.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.5.12; + +contract tvmAssetIssue005 { + constructor() payable public{} + + function() external payable { + } + + function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { + return assetissue(name, abbr, totalSupply, precision); + } + + function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { + return updateasset(tokenId, bytes(url), bytes(desc)); + } + + function updateAssetOnBytes(trcToken tokenId, bytes memory url, bytes memory desc) public returns (bool) { + return updateasset(tokenId, url, desc); + } + + function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { + toAddress.transferToken(tokenValue, id); + } + + function SelfdestructTest(address payable target) public { + selfdestruct(target); + } +} + +contract B { + event Deployed(address addr, uint256 salt); + + function deploy(uint256 salt) public returns (address) { + address addr; + bytes memory code = type(tvmAssetIssue005).creationCode; + assembly { + addr := create2(0, add(code, 0x20), mload(code), salt) + if iszero(extcodesize(addr)) { + revert(0, 0) + } + } + emit Deployed(addr, salt); + return addr; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/typeName.sol b/framework/src/test/resources/soliditycode_0.5.15/typeName.sol new file mode 100644 index 00000000000..5b44abd1bbb --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/typeName.sol @@ -0,0 +1,5 @@ +contract TypeName { + function testTypeName() public returns (string memory){ + return type(TypeName).name; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/unStake001.sol b/framework/src/test/resources/soliditycode_0.5.15/unStake001.sol new file mode 100644 index 00000000000..54a9829cd40 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/unStake001.sol @@ -0,0 +1,90 @@ +pragma solidity ^0.5.0; + +contract unStakeTest { + B b; + constructor() payable public{} + function deployB() payable public returns (B addrB){ + b = (new B).value(1000000000)(); + return b; + } + + function selfdestructTest(address payable target) public { + selfdestruct(target); + } + + function selfdestructTest2(address sr, uint256 amount, address payable target) public { + stake(sr, amount); + selfdestruct(target); + } + + function Stake(address sr, uint256 amount) public returns (bool result){ + return stake(sr, amount); + } + + function stake2(address sr, uint256 amount) public returns (bool result){ + stake(sr, amount); + return stake(sr, amount); + } + + function unStake() public returns (bool result){ + return unstake(); + } + + function unStake2() public returns (bool result){ + unstake(); + return unstake(); + } + + function withdrawReward() public returns (uint256 amount) { + return withdrawreward(); + } + + function rewardBalance(address addr) view public returns (uint256 balance) { + return addr.rewardbalance; + } + + function revertTest1(address sr, uint256 amount, address payable transferAddr) public { + transferAddr.transfer(1000000); + stake(sr, amount); + transferAddr.transfer(2000000); + stake(sr, 1000000000000000); + //stake more than balance to fail + transferAddr.transfer(4000000); + } + + function revertTest2(address payable transferAddr) public { + transferAddr.transfer(1000000); + unstake(); + transferAddr.transfer(2000000); + unstake(); + //unstake twice to fail + transferAddr.transfer(4000000); + } + + function BStake(address sr, uint256 amount) public returns (bool result){ + return b.Stake(sr, amount); + } + + function BUnStake() public returns (bool result){ + return b.UnStake(); + } + + function BSelfdestructTest(address payable target) public { + b.SelfdestructTest(target); + } +} + +contract B { + constructor() payable public{} + function Stake(address sr, uint256 amount) public returns (bool result){ + return stake(sr, amount); + } + + function UnStake() public returns (bool result){ + return unstake(); + } + + function SelfdestructTest(address payable target) public { + selfdestruct(target); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/validatemultisign001.sol b/framework/src/test/resources/soliditycode_0.5.15/validatemultisign001.sol new file mode 100644 index 00000000000..cc0a742d0c5 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/validatemultisign001.sol @@ -0,0 +1,15 @@ +pragma experimental ABIEncoderV2; + +contract validatemultisignTest { + function testmulti(address a, uint256 perid, bytes32 hash, bytes[] memory signatures) public returns (bool){ + return validatemultisign(a, perid, hash, signatures); + } + + function testbatch(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns (bytes32){ + return batchvalidatesign(hash, signatures, addresses); + } + + function testMultiPrecompileContract(bytes memory data) public returns(bool, bytes memory){ + return address(0xa).delegatecall(data); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/verifyTransferProof001.sol b/framework/src/test/resources/soliditycode_0.5.15/verifyTransferProof001.sol new file mode 100644 index 00000000000..587b4defd10 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/verifyTransferProof001.sol @@ -0,0 +1,15 @@ +contract verifyTransferProofTest { + + function test1() public returns (bool, bytes memory){ + bytes memory empty = ""; + return address(0x1000002).delegatecall(empty); + } + + function test2(bytes memory data) public returns (bool, bytes memory){ + return address(0x1000002).delegatecall(data); + } + + function test3(bytes32[10][] memory input, bytes32[2][] memory spendAuthoritySignature, bytes32[9][] memory output, bytes32[2] memory bindingSignature, bytes32 signHash, uint64 valueBalance, bytes32[33] memory frontier, uint256 leafCount) public returns (bytes32[] memory){ + return verifyTransferProof(input, spendAuthoritySignature, output, bindingSignature, signHash, valueBalance, frontier, leafCount); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/walletTestMutiSign004.sol b/framework/src/test/resources/soliditycode_0.5.15/walletTestMutiSign004.sol new file mode 100644 index 00000000000..7b943aee5c1 --- /dev/null +++ b/framework/src/test/resources/soliditycode_0.5.15/walletTestMutiSign004.sol @@ -0,0 +1,51 @@ +contract timeoutTest { + string public iarray1; + // cpu + function oneCpu() public { + require(1==1); + } + + function storage8Char() public { + iarray1 = "12345678"; + } + + function testUseCpu(uint256 a) public returns (uint256){ + uint256 count = 0; + for (uint256 i = 0; i < a; i++) { + count++; + } + return count; + } + + + uint256[] public iarray; + uint public calculatedFibNumber; + mapping(address=>mapping(address=>uint256)) public m; + + function testUseStorage(uint256 a) public returns (uint256){ + uint256 count = 0; + for (uint256 i = 0; i < a; i++) { + count++; + iarray.push(i); + } + return count; + } + + // stack + //uint n = 0; + uint yy = 0; + function test() public { + //n += 1; + yy += 1; + test(); + } + + function setFibonacci(uint n) public returns (uint256){ + calculatedFibNumber = fibonacci(n); + return calculatedFibNumber; + } + + function fibonacci(uint n) internal returns (uint) { + return fibonacci(n - 1) + fibonacci(n - 2); + } +} \ No newline at end of file diff --git a/framework/src/test/resources/testng.conf b/framework/src/test/resources/testng.conf index 3a852f10b2d..8c00f8871d5 100644 --- a/framework/src/test/resources/testng.conf +++ b/framework/src/test/resources/testng.conf @@ -144,7 +144,7 @@ defaultParameter = { httpConnectionTimeout = 19000 httpSoTimeout = 18000 createWitnessAmount = 9999000000 - operations = 7fff1fc0033e0900000000000000000000000000000000000000000000000000 + operations = 7fff1fc0033e3300000000000000000000000000000000000000000000000000 delayTransactionFee = 100000 cancleDelayTransactionFee = 50000 solidityCompilerVersion = "v5" @@ -154,7 +154,7 @@ defaultParameter = { zenTokenFee = 10000000 zenTokenWhenCreateNewAddress = 1000000 zenTrc20TokenOwnerKey = ede941a01eb8234866f60c7e8e95db4614bb0d05298d82bae0abea81f1861046 - + blackHoleAddress = THmtHi1Rzq4gSKYGEKv1DPkV7au6xU1AUB } @@ -324,6 +324,14 @@ code = { code_SideGateway = "608060405260068054600160a060020a03199081166201000017909155600780549091166201000117905534801561003657600080fd5b50d3801561004357600080fd5b50d2801561005057600080fd5b50604051602080613c54833981016040908152905160048054600160a060020a03191633179055600160a060020a03166000908152600360205220805460ff19166001179055613baf806100a56000396000f300608060405260043610620001195763ffffffff60e060020a6000350416630a61c59f81146200011e5780630bb0482f14620001605780630f40ef09146200028e5780631f1767eb14620002dc57806331775cc6146200032e578063455042361462000377578063473c3bd714620003c257806355781fcf146200041e57806367bf590314620005175780637ce67366146200054b5780638da5cb5b14620005ce5780639435455f1462000602578063ab15bdf81462000647578063addd5099146200073b578063bcad917b146200077b578063cb912b1e1462000838578063db13a12b14620008c0578063ded8454a1462000900578063ede1a1e91462000940578063eff457d2146200098e578063fce16fec14620009d1575b600080fd5b3480156200012b57600080fd5b50d380156200013957600080fd5b50d280156200014757600080fd5b506200015e600160a060020a036004351662000a1a565b005b3480156200016d57600080fd5b50d380156200017b57600080fd5b50d280156200018957600080fd5b506040805160206004803580820135601f81018490048402850184019095528484526200021694369492936024939284019190819084018382808284375050604080516020601f89358b018035918201839004830284018301909452808352979a99988101979196509182019450925082915084018382808284375094975062000ac29650505050505050565b6040805160208082528351818301528351919283929083019185019080838360005b838110156200025257818101518382015260200162000238565b50505050905090810190601f168015620002805780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6040805160206004803580820135601f81018490048402850184019095528484526200015e94369492936024939284019190819084018382808284375094975062000bb49650505050505050565b348015620002e957600080fd5b50d38015620002f757600080fd5b50d280156200030557600080fd5b506200015e600160a060020a036004351660243560443560643560843560ff60a4351662000ca3565b3480156200033b57600080fd5b50d380156200034957600080fd5b50d280156200035757600080fd5b506200015e600160a060020a036004358116906024351660443562000e9c565b3480156200038457600080fd5b50d380156200039257600080fd5b50d28015620003a057600080fd5b50620003ae60043562001022565b604080519115158252519081900360200190f35b348015620003cf57600080fd5b50d38015620003dd57600080fd5b50d28015620003eb57600080fd5b5062000402600160a060020a036004351662001037565b60408051600160a060020a039092168252519081900360200190f35b3480156200042b57600080fd5b50d380156200043957600080fd5b50d280156200044757600080fd5b506040805160206004803580820135601f81018490048402850184019095528484526200040294369492936024939284019190819084018382808284375050604080516020601f89358b018035918201839004830284018301909452808352979a99988101979196509182019450925082915084018382808284375050604080516020601f89358b018035918201839004830284018301909452808352979a9998810197919650918201945092508291508401838280828437509497505050923560ff1693506200105292505050565b3480156200052457600080fd5b50d380156200053257600080fd5b50d280156200054057600080fd5b506200040262001344565b3480156200055857600080fd5b50d380156200056657600080fd5b50d280156200057457600080fd5b506040805160206004803580820135601f81018490048402850184019095528484526200040294369492936024939284019190819084018382808284375094975050509235600160a060020a031693506200135392505050565b348015620005db57600080fd5b50d38015620005e957600080fd5b50d28015620005f757600080fd5b5062000402620013da565b3480156200060f57600080fd5b50d380156200061d57600080fd5b50d280156200062b57600080fd5b506200015e600160a060020a03600435166024351515620013e9565b3480156200065457600080fd5b50d380156200066257600080fd5b50d280156200067057600080fd5b506040805160206004803580820135601f81018490048402850184019095528484526200040294369492936024939284019190819084018382808284375050604080516020601f89358b018035918201839004830284018301909452808352979a99988101979196509182019450925082915084018382808284375050604080516020601f89358b018035918201839004830284018301909452808352979a9998810197919650918201945092508291508401838280828437509497506200142c9650505050505050565b3480156200074857600080fd5b50d380156200075657600080fd5b50d280156200076457600080fd5b50620003ae600160a060020a036004351662001712565b3480156200078857600080fd5b50d380156200079657600080fd5b50d28015620007a457600080fd5b50604080516020600460443581810135601f810184900484028501840190955284845262000803948235600160a060020a0316946024803595369594606494920191908190840183828082843750949750620017279650505050505050565b604080517fffffffff000000000000000000000000000000000000000000000000000000009092168252519081900360200190f35b3480156200084557600080fd5b50d380156200085357600080fd5b50d280156200086157600080fd5b50604080516020600460443581810135601f810184900484028501840190955284845262000803948235600160a060020a0316946024803595369594606494920191908190840183828082843750949750620019019650505050505050565b348015620008cd57600080fd5b50d38015620008db57600080fd5b50d28015620008e957600080fd5b5062000402600160a060020a036004351662001b01565b3480156200090d57600080fd5b50d380156200091b57600080fd5b50d280156200092957600080fd5b5062000216600160a060020a036004351662001b1c565b6040805160206004803580820135601f81018490048402850184019095528484526200015e94369492936024939284019190819084018382808284375094975062001b519650505050505050565b3480156200099b57600080fd5b50d38015620009a957600080fd5b50d28015620009b757600080fd5b506200015e600160a060020a036004351660243562001cf1565b348015620009de57600080fd5b50d38015620009ec57600080fd5b50d28015620009fa57600080fd5b506200015e600160a060020a036004358116906024351660443562001dbf565b600454600160a060020a0316331462000a3257600080fd5b600160a060020a038116151562000a93576040805160e560020a62461bcd02815260206004820152601e60248201527f5f73756e546f6b656e41646472657373203d3d20616464726573732830290000604482015290519081900360640190fd5b6005805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0392909216919091179055565b6060826041836040516020018084805190602001908083835b6020831062000afc5780518252601f19909201916020918201910162000adb565b6001836020036101000a0380198251168184511680821785525050505050509050018360ff167f010000000000000000000000000000000000000000000000000000000000000002815260010182805190602001908083835b6020831062000b765780518252601f19909201916020918201910162000b55565b6001836020036101000a0380198251168184511680821785525050505050509050019350505050604051602081830303815290604052905092915050565b6040516000903480156108fc029183818181858288f1935050505015801562000be1573d6000803e3d6000fd5b507f7a47a70a1221ce1b92f8d000c55e2c92c0255a381cf1be25c3ca697593ecc96a3334836040518084600160a060020a0316600160a060020a0316815260200183815260200180602001828103825283818151815260200191508051906020019080838360005b8381101562000c6357818101518382015260200162000c49565b50505050905090810190601f16801562000c915780820380516001836020036101000a031916815260200191505b5094505050505060405180910390a150565b3360009081526003602052604081205460ff16151562000cc257600080fd5b620f42408611801562000cd85750621e84808611155b151562000d55576040805160e560020a62461bcd02815260206004820152602360248201527f7472633130203c3d2031303030303030206f72207472633130203e203230303060448201527f3030300000000000000000000000000000000000000000000000000000000000606482015290519081900360840190fd5b5060008581526002602052604090205460ff1680151562000d8a576000868152600260205260409020805460ff191660011790555b60075460408051878152602081018990528082018790526060810186905260ff851660808201529051600160a060020a039092169160a0808301926000929190829003018183865af1505050600160a060020a0387166108fc86150286888015801562000df657600080fd5b50806780000000000000001115801562000e0f57600080fd5b5080620f42401015801562000e2357600080fd5b50604051600081818185878a8ad094505050505015801562000e49573d6000803e3d6000fd5b5060408051600160a060020a03891681526020810188905280820187905290517f4aac44dc080543b9fe45d9dfaad396001ee0ecdc07499d64e2e798bfffc42fde9181900360600190a150505050505050565b3360009081526003602052604081205460ff16151562000ebb57600080fd5b50600160a060020a038083166000908152602081905260409020541680151562000f54576040805160e560020a62461bcd028152602060048201526024808201527f746865206d61696e20636861696e2061646472657373206861736e2774206d6160448201527f7070656400000000000000000000000000000000000000000000000000000000606482015290519081900360840190fd5b80600160a060020a03166340c10f1985846040518363ffffffff1660e060020a0281526004018083600160a060020a0316600160a060020a0316815260200182815260200192505050600060405180830381600087803b15801562000fb857600080fd5b505af115801562000fcd573d6000803e3d6000fd5b505060408051600160a060020a0380861682528816602082015280820186905290517f48c104169bad147dfc9c0b2ac8fc83202a035d4d9632e24e839680be759772089350908190036060019150a150505050565b60026020526000908152604090205460ff1681565b600060208190529081526040902054600160a060020a031681565b600080600062001063873362001353565b600160a060020a038082166000908152602081905260409020549193501615620010fd576040805160e560020a62461bcd02815260206004820152602160248201527f746865206d61696e20636861696e206164647265737320686173206d6170706560448201527f6400000000000000000000000000000000000000000000000000000000000000606482015290519081900360840190fd5b600554600160a060020a03838116911614156200118a576040805160e560020a62461bcd02815260206004820152602360248201527f6d61696e436861696e41646472657373203d3d2073756e546f6b656e4164647260448201527f6573730000000000000000000000000000000000000000000000000000000000606482015290519081900360840190fd5b308686866200119862001f45565b600160a060020a038516815260ff82166060820152608060208083018281528651928401929092528551604084019160a08501919088019080838360005b83811015620011f0578181015183820152602001620011d6565b50505050905090810190601f1680156200121e5780820380516001836020036101000a031916815260200191505b50838103825285518152855160209182019187019080838360005b838110156200125357818101518382015260200162001239565b50505050905090810190601f168015620012815780820380516001836020036101000a031916815260200191505b509650505050505050604051809103906000f080158015620012a7573d6000803e3d6000fd5b50600160a060020a03808416600081815260208181526040808320805495871673ffffffffffffffffffffffffffffffffffffffff1996871681179091558084526001835292819020805490951684179094558351338152908101929092528183015290519192507fee201bea1b0aff77f5f792b979e4732ba6605c2203d0f92f9aa45625eff88222919081900360600190a19695505050505050565b600554600160a060020a031681565b6000606080620013638462001b1c565b915062001371858362000ac2565b9050806040518082805190602001908083835b60208310620013a55780518252601f19909201916020918201910162001384565b5181516020939093036101000a6000190180199091169216919091179052604051920182900390912098975050505050505050565b600454600160a060020a031681565b600454600160a060020a031633146200140157600080fd5b600160a060020a03919091166000908152600360205260409020805460ff1916911515919091179055565b60008060006200143d863362001353565b600160a060020a038082166000908152602081905260409020549193501615620014d7576040805160e560020a62461bcd02815260206004820152602160248201527f746865206d61696e20636861696e206164647265737320686173206d6170706560448201527f6400000000000000000000000000000000000000000000000000000000000000606482015290519081900360840190fd5b600554600160a060020a038381169116141562001564576040805160e560020a62461bcd02815260206004820152602360248201527f6d61696e436861696e41646472657373203d3d2073756e546f6b656e4164647260448201527f6573730000000000000000000000000000000000000000000000000000000000606482015290519081900360840190fd5b3085856200157162001f56565b600160a060020a0384168152606060208083018281528551928401929092528451604084019160808501919087019080838360005b83811015620015c0578181015183820152602001620015a6565b50505050905090810190601f168015620015ee5780820380516001836020036101000a031916815260200191505b50838103825284518152845160209182019186019080838360005b838110156200162357818101518382015260200162001609565b50505050905090810190601f168015620016515780820380516001836020036101000a031916815260200191505b5095505050505050604051809103906000f08015801562001676573d6000803e3d6000fd5b50600160a060020a03808416600081815260208181526040808320805495871673ffffffffffffffffffffffffffffffffffffffff1996871681179091558084526001835292819020805490951684179094558351338152908101929092528183015290519192507fa2399d6f422f35b470d7aff96f7b2d8ce1c07bc14d978c9fbad6083461c564a7919081900360600190a195945050505050565b60036020526000908152604090205460ff1681565b33600081815260016020526040812054909190600160a060020a03168015156200179b576040805160e560020a62461bcd02815260206004820152601e60248201527f6d61696e436861696e41646472657373203d3d20616464726573732830290000604482015290519081900360640190fd5b81600160a060020a03166342966c68866040518263ffffffff1660e060020a02815260040180828152602001915050600060405180830381600087803b158015620017e557600080fd5b505af1158015620017fa573d6000803e3d6000fd5b505050507fc7b54407df97321a6170a99eeb667db3dc95205c9a9b12a4f1673bac84066544868683876040518085600160a060020a0316600160a060020a0316815260200184815260200183600160a060020a0316600160a060020a0316815260200180602001828103825283818151815260200191508051906020019080838360005b83811015620018985781810151838201526020016200187e565b50505050905090810190601f168015620018c65780820380516001836020036101000a031916815260200191505b509550505050505060405180910390a1507fbcad917b0000000000000000000000000000000000000000000000000000000095945050505050565b33600081815260016020526040812054909190600160a060020a03168015156200199b576040805160e560020a62461bcd02815260206004820152602360248201527f74686520747263373231206d7573742068617665206265656e206465706f736960448201527f7465640000000000000000000000000000000000000000000000000000000000606482015290519081900360840190fd5b81600160a060020a03166342966c68866040518263ffffffff1660e060020a02815260040180828152602001915050600060405180830381600087803b158015620019e557600080fd5b505af1158015620019fa573d6000803e3d6000fd5b505050507fa93bdc38faeb2081566bca9d2c041ba1545a11a459c67a8baf5c671a262e9b7c868683876040518085600160a060020a0316600160a060020a0316815260200184815260200183600160a060020a0316600160a060020a0316815260200180602001828103825283818151815260200191508051906020019080838360005b8381101562001a9857818101518382015260200162001a7e565b50505050905090810190601f16801562001ac65780820380516001836020036101000a031916815260200191505b509550505050505060405180910390a1507fcb912b1e0000000000000000000000000000000000000000000000000000000095945050505050565b600160205260009081526040902054600160a060020a031681565b60408051600160a060020a03929092167414000000000000000000000000000000000000000018601483015260348201905290565bd360009081526002602052604090205460ff16151562001bbb576040805160e560020a62461bcd02815260206004820152601e60248201527f74726331304d61705b6d73672e746f6b656e69645d203d3d2066616c73650000604482015290519081900360640190fd5b6000d280156108fc0290d38015801562001bd457600080fd5b50806780000000000000001115801562001bed57600080fd5b5080620f42401015801562001c0157600080fd5b50604051600081818185878a8ad094505050505015801562001c27573d6000803e3d6000fd5b507f4cdc0dc16c2640bf1cbeebfe9055747d6c36b74120ed1d06440846a8150cc4c333d2d3846040518085600160a060020a0316600160a060020a0316815260200184815260200183815260200180602001828103825283818151815260200191508051906020019080838360005b8381101562001cb057818101518382015260200162001c96565b50505050905090810190601f16801562001cde5780820380516001836020036101000a031916815260200191505b509550505050505060405180910390a150565b3360009081526003602052604090205460ff16151562001d1057600080fd5b600654604080518381529051600160a060020a03909216916020808301926000929190829003018183865af15050604051600160a060020a038416915082156108fc029083906000818181858888f1935050505015801562001d76573d6000803e3d6000fd5b5060408051600160a060020a03841681526020810183905281517f0e3147459e9437f793e793b98df267ee885cfe4ad096b279287f03dcd0ca0497929181900390910190a15050565b3360009081526003602052604081205460ff16151562001dde57600080fd5b50600160a060020a038083166000908152602081905260409020541680151562001e77576040805160e560020a62461bcd028152602060048201526024808201527f746865206d61696e20636861696e2061646472657373206861736e2774206d6160448201527f7070656400000000000000000000000000000000000000000000000000000000606482015290519081900360840190fd5b80600160a060020a03166340c10f1985846040518363ffffffff1660e060020a0281526004018083600160a060020a0316600160a060020a0316815260200182815260200192505050600060405180830381600087803b15801562001edb57600080fd5b505af115801562001ef0573d6000803e3d6000fd5b505060408051600160a060020a0380861682528816602082015280820186905290517fb49dbda83c867b85d55c88d22a084e7db05c8a29e16d027af1b02105906d16bc9350908190036060019150a150505050565b604051610d7c8062001f6883390190565b604051610ea08062002ce4833901905600608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50604051610d7c380380610d7c833981016040908152815160208084015192840151606085015160038054600160a060020a031916600160a060020a0386161790559385018051939590949101929091610089916004918601906100bf565b50815161009d9060059060208501906100bf565b506006805460ff191660ff92909216919091179055505060006002555061015a565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061010057805160ff191683800117855561012d565b8280016001018555821561012d579182015b8281111561012d578251825591602001919060010190610112565b5061013992915061013d565b5090565b61015791905b808211156101395760008155600101610143565b90565b610c13806101696000396000f3006080604052600436106100da5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166306fdde0381146100df578063095ea7b314610183578063116191b6146101d557806318160ddd1461022057806323b872dd14610261578063313ce567146102a557806339509351146102ea57806340c10f191461032857806342966c681461036857806349e118931461039a57806370a082311461041257806395d89b411461044d578063a457c2d71461047c578063a9059cbb146104ba578063dd62ed3e146104f8575b600080fd5b3480156100eb57600080fd5b50d380156100f857600080fd5b50d2801561010557600080fd5b5061010e610539565b6040805160208082528351818301528351919283929083019185019080838360005b83811015610148578181015183820152602001610130565b50505050905090810190601f1680156101755780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561018f57600080fd5b50d3801561019c57600080fd5b50d280156101a957600080fd5b506101c1600160a060020a03600435166024356105c7565b604080519115158252519081900360200190f35b3480156101e157600080fd5b50d380156101ee57600080fd5b50d280156101fb57600080fd5b506102046105dd565b60408051600160a060020a039092168252519081900360200190f35b34801561022c57600080fd5b50d3801561023957600080fd5b50d2801561024657600080fd5b5061024f6105ec565b60408051918252519081900360200190f35b34801561026d57600080fd5b50d3801561027a57600080fd5b50d2801561028757600080fd5b506101c1600160a060020a03600435811690602435166044356105f2565b3480156102b157600080fd5b50d380156102be57600080fd5b50d280156102cb57600080fd5b506102d4610649565b6040805160ff9092168252519081900360200190f35b3480156102f657600080fd5b50d3801561030357600080fd5b50d2801561031057600080fd5b506101c1600160a060020a0360043516602435610652565b34801561033457600080fd5b50d3801561034157600080fd5b50d2801561034e57600080fd5b50610366600160a060020a036004351660243561068e565b005b34801561037457600080fd5b50d3801561038157600080fd5b50d2801561038e57600080fd5b5061036660043561074f565b3480156103a657600080fd5b50d380156103b357600080fd5b50d280156103c057600080fd5b5060408051602060046024803582810135601f810185900485028601850190965285855261036695833595369560449491939091019190819084018382808284375094975061075c9650505050505050565b34801561041e57600080fd5b50d3801561042b57600080fd5b50d2801561043857600080fd5b5061024f600160a060020a03600435166108d0565b34801561045957600080fd5b50d3801561046657600080fd5b50d2801561047357600080fd5b5061010e6108eb565b34801561048857600080fd5b50d3801561049557600080fd5b50d280156104a257600080fd5b506101c1600160a060020a0360043516602435610946565b3480156104c657600080fd5b50d380156104d357600080fd5b50d280156104e057600080fd5b506101c1600160a060020a0360043516602435610982565b34801561050457600080fd5b50d3801561051157600080fd5b50d2801561051e57600080fd5b5061024f600160a060020a036004358116906024351661098f565b6004805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156105bf5780601f10610594576101008083540402835291602001916105bf565b820191906000526020600020905b8154815290600101906020018083116105a257829003601f168201915b505050505081565b60006105d43384846109ba565b50600192915050565b600354600160a060020a031681565b60025490565b60006105ff848484610a46565b600160a060020a03841660009081526001602090815260408083203380855292529091205461063f91869161063a908663ffffffff610b1316565b6109ba565b5060019392505050565b60065460ff1681565b336000818152600160209081526040808320600160a060020a038716845290915281205490916105d491859061063a908663ffffffff610b2816565b600354600160a060020a031633146106a557600080fd5b600160a060020a03821615156106ba57600080fd5b6002546106cd908263ffffffff610b2816565b600255600160a060020a0382166000908152602081905260409020546106f9908263ffffffff610b2816565b600160a060020a0383166000818152602081815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b6107593382610b3e565b50565b60035460009061077590600160a060020a031684610982565b506003546040517fbcad917b000000000000000000000000000000000000000000000000000000008152336004820181815260248301879052606060448401908152865160648501528651600160a060020a039095169463bcad917b94899389939092909160840190602085019080838360005b838110156108015781810151838201526020016107e9565b50505050905090810190601f16801561082e5780820380516001836020036101000a031916815260200191505b50945050505050602060405180830381600087803b15801561084f57600080fd5b505af1158015610863573d6000803e3d6000fd5b505050506040513d602081101561087957600080fd5b505190507fffffffff0000000000000000000000000000000000000000000000000000000081167fbcad917b00000000000000000000000000000000000000000000000000000000146108cb57600080fd5b505050565b600160a060020a031660009081526020819052604090205490565b6005805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156105bf5780601f10610594576101008083540402835291602001916105bf565b336000818152600160209081526040808320600160a060020a038716845290915281205490916105d491859061063a908663ffffffff610b1316565b60006105d4338484610a46565b600160a060020a03918216600090815260016020908152604080832093909416825291909152205490565b600160a060020a03821615156109cf57600080fd5b600160a060020a03831615156109e457600080fd5b600160a060020a03808416600081815260016020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b600160a060020a0382161515610a5b57600080fd5b600160a060020a038316600090815260208190526040902054610a84908263ffffffff610b1316565b600160a060020a038085166000908152602081905260408082209390935590841681522054610ab9908263ffffffff610b2816565b600160a060020a038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600082821115610b2257600080fd5b50900390565b81810182811015610b3857600080fd5b92915050565b600160a060020a0382161515610b5357600080fd5b600254610b66908263ffffffff610b1316565b600255600160a060020a038216600090815260208190526040902054610b92908263ffffffff610b1316565b600160a060020a038316600081815260208181526040808320949094558351858152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a350505600a165627a7a7230582030edf24eb27134d7c77898452315198f9886970c7fed0049b49cd05f121562db0029608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b5060405162000ea038038062000ea083398101604090815281516020808401519284015160048054600160a060020a031916600160a060020a038516179055928401805192949093019161008491600591908501906100a1565b5080516100989060069060208401906100a1565b5050505061013c565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106100e257805160ff191683800117855561010f565b8280016001018555821561010f579182015b8281111561010f5782518255916020019190600101906100f4565b5061011b92915061011f565b5090565b61013991905b8082111561011b5760008155600101610125565b90565b610d54806200014c6000396000f3006080604052600436106100cf5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166306fdde0381146100d4578063081812fc14610178578063095ea7b3146101c6578063116191b61461020657806323b872dd1461023557806340c10f191461027957806342966c68146102b757806349e11893146102e95780636352211e1461036157806370a082311461039357806395d89b41146103e0578063a22cb4651461040f578063a9059cbb1461044f578063e985e9c51461048d575b600080fd5b3480156100e057600080fd5b50d380156100ed57600080fd5b50d280156100fa57600080fd5b506101036104e2565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561013d578181015183820152602001610125565b50505050905090810190601f16801561016a5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561018457600080fd5b50d3801561019157600080fd5b50d2801561019e57600080fd5b506101aa600435610570565b60408051600160a060020a039092168252519081900360200190f35b3480156101d257600080fd5b50d380156101df57600080fd5b50d280156101ec57600080fd5b50610204600160a060020a03600435166024356105a2565b005b34801561021257600080fd5b50d3801561021f57600080fd5b50d2801561022c57600080fd5b506101aa610658565b34801561024157600080fd5b50d3801561024e57600080fd5b50d2801561025b57600080fd5b50610204600160a060020a0360043581169060243516604435610667565b34801561028557600080fd5b50d3801561029257600080fd5b50d2801561029f57600080fd5b50610204600160a060020a036004351660243561068c565b3480156102c357600080fd5b50d380156102d057600080fd5b50d280156102dd57600080fd5b50610204600435610763565b3480156102f557600080fd5b50d3801561030257600080fd5b50d2801561030f57600080fd5b5060408051602060046024803582810135601f81018590048502860185019096528585526102049583359536956044949193909101919081908401838280828437509497506107709650505050505050565b34801561036d57600080fd5b50d3801561037a57600080fd5b50d2801561038757600080fd5b506101aa6004356108e0565b34801561039f57600080fd5b50d380156103ac57600080fd5b50d280156103b957600080fd5b506103ce600160a060020a036004351661090a565b60408051918252519081900360200190f35b3480156103ec57600080fd5b50d380156103f957600080fd5b50d2801561040657600080fd5b5061010361093d565b34801561041b57600080fd5b50d3801561042857600080fd5b50d2801561043557600080fd5b50610204600160a060020a03600435166024351515610998565b34801561045b57600080fd5b50d3801561046857600080fd5b50d2801561047557600080fd5b50610204600160a060020a0360043516602435610a1c565b34801561049957600080fd5b50d380156104a657600080fd5b50d280156104b357600080fd5b506104ce600160a060020a0360043581169060243516610a2b565b604080519115158252519081900360200190f35b6005805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156105685780601f1061053d57610100808354040283529160200191610568565b820191906000526020600020905b81548152906001019060200180831161054b57829003601f168201915b505050505081565b600061057b82610a59565b151561058657600080fd5b50600090815260016020526040902054600160a060020a031690565b60006105ad826108e0565b9050600160a060020a0383811690821614156105c857600080fd5b33600160a060020a03821614806105e457506105e48133610a2b565b15156105ef57600080fd5b600082815260016020526040808220805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0387811691821790925591518593918516917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591a4505050565b600454600160a060020a031681565b6106713382610a76565b151561067c57600080fd5b610687838383610ad5565b505050565b600454600160a060020a031633146106a357600080fd5b600160a060020a03821615156106b857600080fd5b6106c181610a59565b156106cb57600080fd5b600081815260208181526040808320805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a03871690811790915583526002909152902054610718906001610bf0565b600160a060020a0383166000818152600260205260408082209390935591518392907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908290a45050565b61076d3382610c00565b50565b60045460009061078990600160a060020a031684610a1c565b600480546040517fcb912b1e0000000000000000000000000000000000000000000000000000000081523392810183815260248201879052606060448301908152865160648401528651600160a060020a039094169463cb912b1e949093899389939092909160840190602085019080838360005b838110156108165781810151838201526020016107fe565b50505050905090810190601f1680156108435780820380516001836020036101000a031916815260200191505b50945050505050602060405180830381600087803b15801561086457600080fd5b505af1158015610878573d6000803e3d6000fd5b505050506040513d602081101561088e57600080fd5b505190507fffffffff0000000000000000000000000000000000000000000000000000000081167fcb912b1e000000000000000000000000000000000000000000000000000000001461068757600080fd5b600081815260208190526040812054600160a060020a031680151561090457600080fd5b92915050565b6000600160a060020a038216151561092157600080fd5b50600160a060020a031660009081526002602052604090205490565b6006805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156105685780601f1061053d57610100808354040283529160200191610568565b600160a060020a0382163314156109ae57600080fd5b336000818152600360209081526040808320600160a060020a03871680855290835292819020805460ff1916861515908117909155815190815290519293927f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31929181900390910190a35050565b610a27338383610ad5565b5050565b600160a060020a03918216600090815260036020908152604080832093909416825291909152205460ff1690565b600090815260208190526040902054600160a060020a0316151590565b600080610a82836108e0565b905080600160a060020a031684600160a060020a03161480610abd575083600160a060020a0316610ab284610570565b600160a060020a0316145b80610acd5750610acd8185610a2b565b949350505050565b82600160a060020a0316610ae8826108e0565b600160a060020a031614610afb57600080fd5b600160a060020a0382161515610b1057600080fd5b610b1981610ccb565b600160a060020a038316600090815260026020526040902054610b4390600163ffffffff610d1316565b600160a060020a038085166000908152600260205260408082209390935590841681522054610b7990600163ffffffff610bf016565b600160a060020a03808416600081815260026020908152604080832095909555858252819052838120805473ffffffffffffffffffffffffffffffffffffffff1916831790559251849391928716917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a4505050565b8181018281101561090457600080fd5b81600160a060020a0316610c13826108e0565b600160a060020a031614610c2657600080fd5b610c2f81610ccb565b600160a060020a038216600090815260026020526040902054610c5990600163ffffffff610d1316565b600160a060020a038316600081815260026020908152604080832094909455848252819052828120805473ffffffffffffffffffffffffffffffffffffffff191690559151839291907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908390a45050565b600081815260016020526040902054600160a060020a03161561076d576000908152600160205260409020805473ffffffffffffffffffffffffffffffffffffffff19169055565b600082821115610d2257600080fd5b509003905600a165627a7a72305820e95bf2b25cae43edb66a8c2c9a5784778a3163ec94f09ffb86ca32624f6a8b1b0029a165627a7a72305820642e8c16e0d0768025001430bcf8dea875428b07fc9214f0b1b37c74a5b34c660029" code_shieldTrc20Token = "60806040526002805460ff1916600617905534801561001d57600080fd5b506040516109a53803806109a583398101604090815281516020808401518385015160025460ff16600a0a84026003819055336000908152600485529586205590850180519395909491019261007592850190610092565b508051610089906001906020840190610092565b5050505061012d565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106100d357805160ff1916838001178555610100565b82800160010185558215610100579182015b828111156101005782518255916020019190600101906100e5565b5061010c929150610110565b5090565b61012a91905b8082111561010c5760008155600101610116565b90565b6108698061013c6000396000f3006080604052600436106100b95763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166306fdde0381146100be578063095ea7b31461014857806318160ddd1461018057806323b872dd146101a7578063313ce567146101d157806342966c68146101fc57806370a082311461021457806379cc67901461023557806395d89b4114610259578063a9059cbb1461026e578063cae9ca5114610292578063dd62ed3e146102fb575b600080fd5b3480156100ca57600080fd5b506100d3610322565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561010d5781810151838201526020016100f5565b50505050905090810190601f16801561013a5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561015457600080fd5b5061016c600160a060020a03600435166024356103b0565b604080519115158252519081900360200190f35b34801561018c57600080fd5b506101956103dd565b60408051918252519081900360200190f35b3480156101b357600080fd5b5061016c600160a060020a03600435811690602435166044356103e3565b3480156101dd57600080fd5b506101e6610453565b6040805160ff9092168252519081900360200190f35b34801561020857600080fd5b5061016c60043561045c565b34801561022057600080fd5b50610195600160a060020a03600435166104d4565b34801561024157600080fd5b5061016c600160a060020a03600435166024356104e6565b34801561026557600080fd5b506100d36105b7565b34801561027a57600080fd5b5061016c600160a060020a0360043516602435610611565b34801561029e57600080fd5b50604080516020600460443581810135601f810184900484028501840190955284845261016c948235600160a060020a03169460248035953695946064949201919081908401838280828437509497506106259650505050505050565b34801561030757600080fd5b50610195600160a060020a036004358116906024351661073e565b6000805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156103a85780601f1061037d576101008083540402835291602001916103a8565b820191906000526020600020905b81548152906001019060200180831161038b57829003601f168201915b505050505081565b336000908152600560209081526040808320600160a060020a039590951683529390529190912055600190565b60035481565b600160a060020a038316600090815260056020908152604080832033845290915281205482111561041357600080fd5b600160a060020a038416600090815260056020908152604080832033845290915290208054839003905561044884848461075b565b506001949350505050565b60025460ff1681565b3360009081526004602052604081205482111561047857600080fd5b3360008181526004602090815260409182902080548690039055600380548690039055815185815291517fcc16f5dbb4873280815c1ee09dbd06736cffcc184412cf7a71a0fdb75d397ca59281900390910190a2506001919050565b60046020526000908152604090205481565b600160a060020a03821660009081526004602052604081205482111561050b57600080fd5b600160a060020a038316600090815260056020908152604080832033845290915290205482111561053b57600080fd5b600160a060020a0383166000818152600460209081526040808320805487900390556005825280832033845282529182902080548690039055600380548690039055815185815291517fcc16f5dbb4873280815c1ee09dbd06736cffcc184412cf7a71a0fdb75d397ca59281900390910190a250600192915050565b60018054604080516020600284861615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156103a85780601f1061037d576101008083540402835291602001916103a8565b600061061e33848461075b565b9392505050565b60008361063281856103b0565b15610736576040517f8f4ffcb10000000000000000000000000000000000000000000000000000000081523360048201818152602483018790523060448401819052608060648501908152875160848601528751600160a060020a03871695638f4ffcb195948b94938b939192909160a490910190602085019080838360005b838110156106ca5781810151838201526020016106b2565b50505050905090810190601f1680156106f75780820380516001836020036101000a031916815260200191505b5095505050505050600060405180830381600087803b15801561071957600080fd5b505af115801561072d573d6000803e3d6000fd5b50505050600191505b509392505050565b600560209081526000928352604080842090915290825290205481565b600080600160a060020a038416151561077357600080fd5b600160a060020a03851660009081526004602052604090205483111561079857600080fd5b600160a060020a03841660009081526004602052604090205483810110156107bf57600080fd5b50600160a060020a0380841660008181526004602090815260408083208054958a1680855282852080548a81039091559486905281548901909155815188815291519390950194927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929181900390910190a35060019493505050505600a165627a7a723058208600353fffbf658cb8b57929fba657c57e83d756e4101cf874b153cc6eb4bb1c0029" code_shield = "6104806040527f010000000000000000000000000000000000000000000000000000000000000060809081527f817de36ab2d57feb077634bca77819c8e0bd298c04f6fed0e6a83cc1356ca15560a0527fffe9fc03f18b176c998806439ff0bb8ad193afdb27b2ccbc88856916dd804e3460c0527fd8283386ef2ef07ebdbb4383c12a739a953a4d6e0d6fb1139a4036d693bfbb6c60e0527fe110de65c907b9dea4ae0bd83a4b0a51bea175646a64c12b4c9f931b2cb31b49610100527f912d82b2c2bca231f71efcf61737fbf0a08befa0416215aeef53e8bb6d23390a610120527f8ac9cf9c391e3fd42891d27238a81a8a5c1d3a72b1bcbea8cf44a58ce7389613610140527fd6c639ac24b46bd19341c91b13fdcab31581ddaf7f1411336a271f3d0aa52813610160527f7b99abdc3730991cc9274727d7d82d28cb794edbc7034b4f0053ff7c4b680444610180527f43ff5457f13b926b61df552d4e402ee6dc1463f99a535f9a713439264d5b616b6101a0527fba49b659fbd0b7334211ea6a9d9df185c757e70aa81da562fb912b84f49bce726101c0527f4777c8776a3b1e69b73a62fa701fa4f7a6282d9aee2c7a6b82e7937d7081c23c6101e0527fec677114c27206f5debc1c1ed66f95e2b1885da5b7be3d736b1de98579473048610200527f1b77dac4d24fb7258c3c528704c59430b630718bec486421837021cf75dab651610220527fbd74b25aacb92378a871bf27d225cfc26baca344a1ea35fdd94510f3d157082c610240527fd6acdedf95f608e09fa53fb43dcd0990475726c5131210c9e5caeab97f0e642f610260527f1ea6675f9551eeb9dfaaa9247bc9858270d3d3a4c5afa7177a984d5ed1be2451610280527f6edb16d01907b759977d7650dad7e3ec049af1a3d875380b697c862c9ec5d51c6102a0527fcd1c8dbf6e3acc7a80439bc4962cf25b9dce7c896f3a5bd70803fc5a0e33cf006102c0527f6aca8448d8263e547d5ff2950e2ed3839e998d31cbc6ac9fd57bc6002b1592166102e0527f8d5fa43e5a10d11605ac7430ba1f5d81fb1b68d29a640405767749e841527673610300527f08eeab0c13abd6069e6310197bf80f9c1ea6de78fd19cbae24d4a520e6cf3023610320527f0769557bc682b1bf308646fd0b22e648e8b9e98f57e29f5af40f6edb833e2c49610340527f4c6937d78f42685f84b43ad3b7b00f81285662f85c6a68ef11d62ad1a3ee0850610360527ffee0e52802cb0c46b1eb4d376c62697f4759f6c8917fa352571202fd778fd712610380527f16d6252968971a83da8521d65382e61f0176646d771c91528e3276ee45383e4a6103a0527fd2e1642c9a462229289e5b0e3b7f9008e0301cbb93385ee0e21da2545073cb586103c0527fa5122c08ff9c161d9ca6fc462073396c7d7d38e8ee48cdb3bea7e2230134ed6a6103e0527f28e7b841dcbc47cceb69d7cb8d94245fb7cb2ba3a7a6bc18f13f945f7dbd6e2a610400527fe1f34b034d4a3cd28557e2907ebf990c918f64ecb50a94f01d6fda5ca5c7ef72610420527f12935f14b676509b81eb49ef25f39269ed72309238b4c145803544b646dca62d610440527fb2eed031d4d6a4f02a097f80b54cc1541d4163c6b6f5971f88b6e41d35c5381461046052620004b390602890602062000580565b50348015620004c157600080fd5b50d38015620004cf57600080fd5b50d28015620004dd57600080fd5b506040516200354738038062003547833981016040819052620005009162000615565b604d811062000546576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016200053d90620006b5565b60405180910390fd5b600a0a60005560488054336001600160a01b031991821617909155604980549091166001600160a01b039290921691909117905562000713565b8260208101928215620005b1579160200282015b82811115620005b157825182559160200191906001019062000594565b50620005bf929150620005c3565b5090565b620005e091905b80821115620005bf5760008155600101620005ca565b90565b8051620005f081620006ee565b620005fb81620006d0565b9392505050565b80516200060f8162000708565b92915050565b600080604083850312156200062957600080fd5b6000620006378585620005e3565b92505060206200064a8582860162000602565b9150509250929050565b600062000663602a83620006c7565b7f546865207363616c696e67466163746f724578706f6e656e74206973206f757481527f206f662072616e67652100000000000000000000000000000000000000000000602082015260400192915050565b602080825281016200060f8162000654565b90815260200190565b60006001600160a01b0382166200060f565b6001600160a81b031690565b620006f981620006e2565b81146200070557600080fd5b50565b620006f981620005e0565b612e2480620007236000396000f3fe608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50600436106100c35760003560e01c80639110a55b1161008b5780639110a55b14610134578063ae6dead714610147578063cc1058751461015a578063d7b0fef11461016d578063e176507314610175578063ed3437f814610196576100c3565b80632997e86b146100c85780632a6bb45a146100f157806330e69fc314610104578063313529361461010c578063855d175e1461011f575b600080fd5b6100db6100d6366004611c30565b61019e565b6040516100e89190612a7d565b60405180910390f35b6100db6100ff366004611c30565b6101b0565b6100db6101c2565b6100db61011a366004611c30565b6101c8565b61013261012d366004611c6c565b6101da565b005b610132610142366004611a3d565b6105a9565b6100db610155366004611c30565b610bd4565b610132610168366004611b22565b610be6565b6100db61106c565b610188610183366004611c30565b611072565b6040516100e8929190612a8b565b6100db6111c5565b60036020526000908152604090205481565b60066020526000908152604090205481565b60015481565b60056020526000908152604090205481565b6049546040516323b872dd60e01b815233916000916001600160a01b03909116906323b872dd9061021390859030908b90600401612852565b602060405180830381600087803b15801561022d57600080fd5b505af1158015610241573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506102659190810190611c12565b90508061028d5760405162461bcd60e51b815260040161028490612ad8565b60405180910390fd5b8435600090815260066020526040902054156102bb5760405162461bcd60e51b815260040161028490612b58565b60006102c6876111cb565b905060006002308389886040516020016102e394939291906127fc565b60408051601f19818403018152908290526102fd91612846565b602060405180830381855afa15801561031a573d6000803e3d6000fd5b5050506040513d601f19601f8201168201806040525061033d9190810190611c4e565b90506060630100000188888585600760015460405161036196959493929190612a1d565b600060405180830381855afa15801561037e573d6000803e3d6000fd5b5050503d80600081146103ad576040519150601f19603f3d011682016040523d82523d6000602084013e6103b2565b606091505b5090506000816000815181106103c457fe5b602002602001015160001c9050806001146103f15760405162461bcd60e51b815260040161028490612b68565b60008260018151811061040057fe5b60209081029190910181015160015463ffffffff016000818152600590935260409092208c359055915081610435578a356007555b60015b826001018110156104aa576002600019830104915084816001018151811061045c57fe5b60200260200101516005600084815260200190815260200160002081905550828114156104a2576000828152600560205260409020546007846021811061049f57fe5b01555b600101610438565b508382600201815181106104ba57fe5b60209081029190910181015160028190556000818152600490925260408220558b906020020135600660008d81602090810291909101358252810191909152604001600090812091909155600180548082019091557fbe22cbc129fd01d04b02a7b3258b72e8c8ae5bfcf054d7f0359779be627a6b27918d9060200201358d600160200201358e600260200201358d60405161055a959493929190612bb8565b60405180910390a17f36bf5aa3964be01dbd95a0154a8930793fe68353bdc580871ffb2c911366bbc7888d60405161059392919061287a565b60405180910390a1505050505050505050505050565b600188108015906105bb575060028811155b6105d75760405162461bcd60e51b815260040161028490612b98565b8786146105f65760405162461bcd60e51b815260040161028490612b08565b60018410801590610608575060028411155b6106245760405162461bcd60e51b815260040161028490612b18565b8381146106435760405162461bcd60e51b815260040161028490612b38565b60005b8881101561070757600360008b8b8481811061065e57fe5b905061014002016000600a811061067157fe5b60200201358152602001908152602001600020546000801b146106a65760405162461bcd60e51b815260040161028490612ba8565b600460008b8b848181106106b657fe5b905061014002016001600a81106106c957fe5b60200201358152602001908152602001600020546000801b14156106ff5760405162461bcd60e51b815260040161028490612af8565b600101610646565b5060005b84811015610773576006600087878481811061072357fe5b9050610120020160006009811061073657fe5b60200201358152602001908152602001600020546000801b1461076b5760405162461bcd60e51b815260040161028490612ae8565b60010161070b565b5060006002308b8b898988886040516020016107959796959493929190612751565b60408051601f19818403018152908290526107af91612846565b602060405180830381855afa1580156107cc573d6000803e3d6000fd5b5050506040513d601f19601f820116820180604052506107ef9190810190611c4e565b9050606063010000028b8b8b8b8b8b8b896000600760015460405161081e9b9a999897969594939291906128bd565b600060405180830381855afa15801561083b573d6000803e3d6000fd5b5050503d806000811461086a576040519150601f19603f3d011682016040523d82523d6000602084013e61086f565b606091505b50905060008160008151811061088157fe5b602002602001015160001c9050806001146108ae5760405162461bcd60e51b815260040161028490612b68565b600160005b888110156109d95760008483806001019450815181106108cf57fe5b602090810291909101015160015490915063ffffffff018b8b848181106108f257fe5b9050610120020160006009811061090557fe5b60008381526005602090815260409091209102919091013590558161094c578b8b8481811061093057fe5b9050610120020160006009811061094357fe5b60200201356007555b60015b826001018110156109c4576002600019830104915086858060010196508151811061097657fe5b60200260200101516005600084815260200190815260200160002081905550828114156109bc57600082815260056020526040902054600784602181106109b957fe5b01555b60010161094f565b505060018054810181559190910190506108b3565b508281815181106109e657fe5b60209081029190910181015160028190556000818152600490925260408220555b8c811015610a8f5760008e8e83818110610a1d57fe5b905061014002016000600a8110610a3057fe5b602002013590508060036000838152602001908152602001600020819055507fd13faa8100906cf559aebacf9c16532cfc9708645c198c8f15798ee049dbcfc181604051610a7e9190612a7d565b60405180910390a150600101610a07565b5060005b88811015610bc457898982818110610aa757fe5b90506101200201600060098110610aba57fe5b6020020135600660008c8c85818110610acf57fe5b90506101200201600060098110610ae257fe5b60200201358152602001908152602001600020819055507f0f190e6ff1f0e1c1f4ec51aecdafdd02278c568898b57df5ca7dccba83a8181c818b8b905003600154038b8b84818110610b3057fe5b90506101200201600060098110610b4357fe5b60200201358c8c85818110610b5457fe5b90506101200201600160098110610b6757fe5b60200201358d8d86818110610b7857fe5b90506101200201600260098110610b8b57fe5b60200201358b8b87818110610b9c57fe5b90506102a00201604051610bb4959493929190612bb8565b60405180910390a1600101610a93565b5050505050505050505050505050565b60046020526000908152604090205481565b6000610bf1896111cb565b905060006002308d888888888e89604051602001610c16989796959493929190612795565b60408051601f1981840301815290829052610c3091612846565b602060405180830381855afa158015610c4d573d6000803e3d6000fd5b5050506040513d601f19601f82011682018060405250610c709190810190611c4e565b8c356000818152600360209081526040909120549293509091908e01359015610cab5760405162461bcd60e51b815260040161028490612ba8565b600081815260046020526040902054610cd65760405162461bcd60e51b815260040161028490612af8565b6001871115610cf75760405162461bcd60e51b815260040161028490612b28565b868514610d165760405162461bcd60e51b815260040161028490612b88565b86610d9d57600063010000038f8f878f88604051610d389594939291906129cc565b602060405180830381855afa158015610d55573d6000803e3d6000fd5b5050506040513d601f19601f82011682018060405250610d789190810190611c12565b905080610d975760405162461bcd60e51b815260040161028490612b68565b50610f21565b610f218e600a806020026040519081016040528092919082600a60200280828437600081840152601f19601f8201169050808301925050505050508e6002806020026040519081016040528092919082600260200280828437600081840152601f19601f820116905080830192505050505050868e6002806020026040519081016040528092919082600260200280828437600081840152601f19601f820116905080830192505050505050878d8d808060200260200160405190810160405280939291908181526020016000905b82821015610eae576040805161012081810190925290808402870190600990839083908082843760009201919091525050508152600190910190602001610e6c565b50505050508c8c808060200260200160405190810160405280939291908181526020016000905b82821015610f1757604080516102a081810190925290808402870190601590839083908082843760009201919091525050508152600190910190602001610ed5565b505050505061124e565b60008281526003602052604090819020839055517fd13faa8100906cf559aebacf9c16532cfc9708645c198c8f15798ee049dbcfc190610f62908490612a7d565b60405180910390a16000604960009054906101000a90046001600160a01b03166001600160a01b031663a9059cbb8c8f6040518363ffffffff1660e01b8152600401610faf92919061287a565b602060405180830381600087803b158015610fc957600080fd5b505af1158015610fdd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506110019190810190611c12565b9050806110205760405162461bcd60e51b815260040161028490612b48565b7f1daf70c304f467a9efbc9ac1ca7bfe859a478aa6c4b88131b4dbb1547029b9728b8e8c60405161105393929190612895565b60405180910390a1505050505050505050505050505050565b60025481565b600061107c611842565b600154831061109d5760405162461bcd60e51b815260040161028490612b78565b63ffffffff83016110ac611842565b60006110b7866115ab565b905060006110c587836115fa565b905060005b60208163ffffffff1610156111b4578263ffffffff168163ffffffff16141561110d57818482601f0363ffffffff166020811061110357fe5b60200201526111a2565b600285066111415760056000600187038152602001908152602001600020548482601f0363ffffffff166020811061110357fe5b60018501600090815260056020526040902054156111715760018501600090815260056020526040902054611187565b60288163ffffffff166020811061118457fe5b01545b8482601f0363ffffffff166020811061119c57fe5b60200201525b600260001986010494506001016110ca565b505060025494509092505050915091565b60005481565b60008082116111ec5760405162461bcd60e51b815260040161028490612ac8565b60005461120090839063ffffffff61174c16565b1561121d5760405162461bcd60e51b815260040161028490612ab8565b6000805461123290849063ffffffff61179516565b9050677fffffffffffffff811061124857600080fd5b92915050565b60008260008151811061125d57fe5b602002602001015160006009811061127157fe5b6020020151905060066000828152602001908152602001600020546000801b146112ad5760405162461bcd60e51b815260040161028490612ae8565b604080516001808252818301909252606091816020015b6112cc611861565b8152602001906001900390816112c457905050905088816000815181106112ef57fe5b6020908102919091010152604080516001808252818301909252606091816020015b611319611880565b815260200190600190039081611311579050509050888160008151811061133c57fe5b6020026020010181905250606063010000028383888b8b8e600760015460405161136d98979695949392919061294e565b600060405180830381855afa15801561138a573d6000803e3d6000fd5b5050503d80600081146113b9576040519150601f19603f3d011682016040523d82523d6000602084013e6113be565b606091505b5090506000816000815181106113d057fe5b602002602001015160001c9050806001146113fd5760405162461bcd60e51b815260040161028490612b68565b60008260018151811061140c57fe5b60209081029190910181015160015463ffffffff016000818152600590935260409092208890559150816114405760078790555b60015b826001018110156114b5576002600019830104915084816001018151811061146757fe5b60200260200101516005600084815260200190815260200160002081905550828114156114ad57600082815260056020526040902054600784602181106114aa57fe5b01555b600101611443565b508382600201815181106114c557fe5b602090810291909101810151600281905560008181526004835260408082209290925589815260069092528120889055600180548082019091558a517f3814d251636df4a739162facca3862684b45af01ce54bcc56ea488fa6a69412d928a918d919061152e57fe5b602002602001015160016009811061154257fe5b60200201518c60008151811061155457fe5b602002602001015160026009811061156857fe5b60200201518c60008151811061157a57fe5b6020026020010151604051611593959493929190612bfb565b60405180910390a15050505050505050505050505050565b60015460009063ffffffff83019063fffffffe01825b60026000198301046002600019850104146115f25760026000198401049250600260001983010491506001016115c1565b949350505050565b60015463fffffffe0160008181526005602052604081205490918291829163ffffffff8088019290871661167b578183101561163c5794506112489350505050565b8183141561167b576002830661166b575050600019016000908152600560205260409020549250611248915050565b5050602854935061124892505050565b60005b8763ffffffff168163ffffffff16101561174057600283066116ba576000198301600090815260056020526040902054955090935083906116d5565b81955060288163ffffffff16602081106116d057fe5b015494505b63010000048187876040516116ec93929190612c3e565b602060405180830381855afa158015611709573d6000803e3d6000fd5b5050506040513d601f19601f8201168201806040525061172c9190810190611c4e565b91506002600019840104925060010161167e565b50979650505050505050565b600061178e83836040518060400160405280601881526020017f536166654d6174683a206d6f64756c6f206279207a65726f00000000000000008152506117d7565b9392505050565b600061178e83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061180b565b600081836117f85760405162461bcd60e51b81526004016102849190612aa7565b5082848161180257fe5b06949350505050565b6000818361182c5760405162461bcd60e51b81526004016102849190612aa7565b50600083858161183857fe5b0495945050505050565b6040518061040001604052806020906020820280388339509192915050565b604051806101400160405280600a906020820280388339509192915050565b60405180604001604052806002906020820280388339509192915050565b80356118a981612d93565b61178e81612cbd565b60008083601f8401126118c457600080fd5b50813567ffffffffffffffff8111156118dc57600080fd5b602083019150836101408202830111156118f557600080fd5b9250929050565b60008083601f84011261190e57600080fd5b50813567ffffffffffffffff81111561192657600080fd5b602083019150836102a08202830111156118f557600080fd5b60008083601f84011261195157600080fd5b50813567ffffffffffffffff81111561196957600080fd5b6020830191508360408202830111156118f557600080fd5b60008083601f84011261199357600080fd5b50813567ffffffffffffffff8111156119ab57600080fd5b602083019150836101208202830111156118f557600080fd5b80610140810183101561124857600080fd5b806102a0810183101561124857600080fd5b806040810183101561124857600080fd5b806060810183101561124857600080fd5b80610120810183101561124857600080fd5b805161124881612daa565b803561124881612db3565b805161124881612db3565b600080600080600080600080600060c08a8c031215611a5b57600080fd5b893567ffffffffffffffff811115611a7257600080fd5b611a7e8c828d016118b2565b995099505060208a013567ffffffffffffffff811115611a9d57600080fd5b611aa98c828d0161193f565b975097505060408a013567ffffffffffffffff811115611ac857600080fd5b611ad48c828d01611981565b95509550506060611ae78c828d016119e8565b93505060a08a013567ffffffffffffffff811115611b0457600080fd5b611b108c828d016118fc565b92509250509295985092959850929598565b6000806000806000806000806000806102a08b8d031215611b4257600080fd5b6000611b4e8d8d6119c4565b9a5050610140611b608d828e016119e8565b995050610180611b728d828e01611a27565b9850506101a0611b848d828e016119e8565b9750506101e0611b968d828e0161189e565b965050610200611ba88d828e016119f9565b9550506102608b013567ffffffffffffffff811115611bc657600080fd5b611bd28d828e01611981565b94509450506102808b013567ffffffffffffffff811115611bf257600080fd5b611bfe8d828e016118fc565b92509250509295989b9194979a5092959850565b600060208284031215611c2457600080fd5b60006115f28484611a1c565b600060208284031215611c4257600080fd5b60006115f28484611a27565b600060208284031215611c6057600080fd5b60006115f28484611a32565b6000806000806104208587031215611c8357600080fd5b6000611c8f8787611a27565b9450506020611ca087828801611a0a565b935050610140611cb2878288016119e8565b925050610180611cc4878288016119d6565b91505092959194509250565b6000611cdc838361203e565b50506101400190565b6000611cdc838361204f565b6000611cfd83836120a3565b50506102a00190565b6000611d1283836120fc565b505060400190565b6000611d128383612154565b6000611d32838361224b565b50506101200190565b6000611d328383612258565b6000611d5383836122a4565b505060200190565b611d6481612cbd565b82525050565b611d64611d7682612cbd565b612d55565b6000611d878385612cab565b9350611d9282612c59565b8060005b85811015611dc857611da88284612cb9565b611db28882611cd0565b9750611dbd83612c8a565b925050600101611d96565b509495945050505050565b6000611ddf8385612cb4565b9350611dea82612c59565b8060005b85811015611dc857611e008284612cb9565b611e0a8882611cd0565b9750611e1583612c8a565b925050600101611dee565b6000611e2b82612c62565b611e358185612cab565b9350611e4083612c5c565b8060005b83811015611dc8578151611e588882611ce5565b9750611e6383612c5c565b925050600101611e44565b6000611e7a8385612cb4565b9350611e8582612c59565b8060005b85811015611dc857611e9b8284612cb9565b611ea58882611cf1565b9750611eb083612c91565b925050600101611e89565b6000611ec78385612cab565b9350611ed282612c59565b8060005b85811015611dc857611ee88284612cb9565b611ef28882611d06565b9750611efd83612c98565b925050600101611ed6565b6000611f1382612c62565b611f1d8185612cab565b9350611f2883612c5c565b8060005b83811015611dc8578151611f408882611d1a565b9750611f4b83612c5c565b925050600101611f2c565b6000611f628385612cab565b9350611f6d82612c59565b8060005b85811015611dc857611f838284612cb9565b611f8d8882611d26565b9750611f9883612c9e565b925050600101611f71565b6000611faf8385612cb4565b9350611fba82612c59565b8060005b85811015611dc857611fd08284612cb9565b611fda8882611d26565b9750611fe583612c9e565b925050600101611fbe565b6000611ffb82612c62565b6120058185612cab565b935061201083612c5c565b8060005b83811015611dc85781516120288882611d3b565b975061203383612c5c565b925050600101612014565b61204b6101408383612d06565b5050565b61205881612c66565b6120628184612cb4565b925061206d82612c59565b8060005b8381101561209b5781516120858782611d47565b965061209083612c5c565b925050600101612071565b505050505050565b61204b6102a08383612d06565b6120b981612c6c565b6120c38184612cb4565b92506120ce82612c59565b8060005b8381101561209b5781516120e68782611d47565b96506120f183612c5c565b9250506001016120d2565b61204b60408383612d06565b61211181612c72565b61211b8184612cb4565b925061212682612c59565b8060005b8381101561209b57815161213e8782611d47565b965061214983612c5c565b92505060010161212a565b61215d81612c72565b6121678184612cb4565b925061217282612c59565b8060005b8381101561209b57815161218a8782611d47565b965061219583612c5c565b925050600101612176565b6121a981612c78565b6121b38184612cb4565b92506121be82612c59565b8060005b8381101561209b5781516121d68782611d47565b96506121e183612c5c565b9250506001016121c2565b6121f581612c7e565b6121ff8184612cb4565b925061220a82612c59565b8060005b8381101561209b5761221f82612d71565b6122298782611d47565b965061223483612ca5565b92505060010161220e565b61204b60608383612d06565b61204b6101208383612d06565b61226181612c84565b61226b8184612cb4565b925061227682612c59565b8060005b8381101561209b57815161228e8782611d47565b965061229983612c5c565b92505060010161227a565b611d6481612c59565b60006122b882612c62565b6122c28185612cb4565b93506122d2818560208601612d12565b9290920192915050565b611d6481612cfb565b60006122f082612c62565b6122fa8185612cab565b935061230a818560208601612d12565b61231381612d7d565b9093019392505050565b600061232a603183612cab565b7f56616c7565206d75737420626520696e7465676572206d756c7469706c6573208152706f66207363616c696e67466163746f722160781b602082015260400192915050565b600061237d601783612cab565b7f56616c7565206d75737420626520706f73697469766521000000000000000000815260200192915050565b60006123b6601483612cab565b735472616e7366657246726f6d206661696c65642160601b815260200192915050565b60006123e6601983612cab565b7f4475706c6963617465206e6f7465436f6d6d69746d656e742100000000000000815260200192915050565b600061241f601683612cab565b7554686520616e63686f72206d7573742065786973742160501b815260200192915050565b6000612451603d83612cab565b7f496e707574206e756d626572206d75737420626520657175616c20746f20737081527f656e64417574686f726974795369676e6174757265206e756d62657221000000602082015260400192915050565b60006124b0601d83612cab565b7f4f7574707574206e756d626572206d7573742062652031206f72203221000000815260200192915050565b60006124e9601e83612cab565b7f4f7574707574206e756d6265722063616e6e6f74206578636565642031210000815260200192915050565b6000612522602883612cab565b7f4f7574707574206e756d626572206d75737420626520657175616c20746f2063815267206e756d6265722160c01b602082015260400192915050565b600061256c601083612cab565b6f5472616e73666572206661696c65642160801b815260200192915050565b6000612598601a83612cab565b7f4475706c6963617465206e6f7465436f6d6d69746d656e747321000000000000815260200192915050565b60006125d1603f83612cab565b7f5468652070726f6f6620616e64207369676e61747572652068617665206e6f7481527f206265656e2076657269666965642062792074686520636f6e74726163742100602082015260400192915050565b6000612630602a83612cab565b7f506f736974696f6e2073686f756c6420626520736d616c6c6572207468616e208152696c656166436f756e742160b01b602082015260400192915050565b600061267c602b83612cab565b7f4f7574707574206e756d626572206d75737420626520657175616c20746f206c81526a656e677468206f6620632160a81b602082015260400192915050565b60006126c9601c83612cab565b7f496e707574206e756d626572206d7573742062652031206f7220322100000000815260200192915050565b6000612702602083612cab565b7f546865206e6f74652068617320616c7265616479206265656e207370656e7421815260200192915050565b611d6481612ce5565b611d6481612cee565b611d6461274c82612cee565b612d66565b600061275d828a611d6a565b60148201915061276e82888a611dd3565b915061277b828688611fa3565b9150612788828486611e6e565b9998505050505050505050565b60006127a1828b611d6a565b6014820191506127b1828a61203e565b610140820191506127c382888a611fa3565b91506127d0828688611e6e565b91506127dc8285611d6a565b6014820191506127ec8284612740565b5060080198975050505050505050565b60006128088287611d6a565b6014820191506128188286612740565b600882019150612828828561224b565b6101208201915061283982846120a3565b506102a001949350505050565b600061178e82846122ad565b606081016128608286611d5b565b61286d6020830185611d5b565b6115f260408301846122a4565b604081016128888285611d5b565b61178e60208301846122a4565b60a081016128a38286611d5b565b6128b060208301856122a4565b6115f2604083018461223f565b61052080825281016128d0818d8f611d7b565b905081810360208301526128e5818b8d611ebb565b905081810360408301526128fa81898b611f56565b905061290960608301886120fc565b61291660a08301876122a4565b61292360c08301866122dc565b61293060e08301856121ec565b61293e6105008301846122a4565b9c9b505050505050505050505050565b6105208082528101612960818b611e20565b90508181036020830152612974818a611f08565b905081810360408301526129888189611ff0565b90506129976060830188612108565b6129a460a08301876122a4565b6129b160c0830186612737565b6129be60e08301856121ec565b6127886105008301846122a4565b61020081016129db828861203e565b6129e96101408301876120fc565b6129f7610180830186612737565b612a056101a08301856120fc565b612a136101e08301846122a4565b9695505050505050565b6105e08101612a2c828961224b565b612a3a6101208301886120fc565b612a48610160830187612737565b612a566101808301866122a4565b612a646101a08301856121ec565b612a726105c08301846122a4565b979650505050505050565b6020810161124882846122a4565b6104208101612a9a82856122a4565b61178e60208301846121a0565b6020808252810161178e81846122e5565b602080825281016112488161231d565b6020808252810161124881612370565b60208082528101611248816123a9565b60208082528101611248816123d9565b6020808252810161124881612412565b6020808252810161124881612444565b60208082528101611248816124a3565b60208082528101611248816124dc565b6020808252810161124881612515565b602080825281016112488161255f565b602080825281016112488161258b565b60208082528101611248816125c4565b6020808252810161124881612623565b602080825281016112488161266f565b60208082528101611248816126bc565b60208082528101611248816126f5565b6103208101612bc782886122a4565b612bd460208301876122a4565b612be160408301866122a4565b612bee60608301856122a4565b612a1360808301846120a3565b6103208101612c0a82886122a4565b612c1760208301876122a4565b612c2460408301866122a4565b612c3160608301856122a4565b612a1360808301846120b0565b60608101612c4c828661272e565b61286d60208301856122a4565b90565b60200190565b5190565b50600a90565b50601590565b50600290565b50602090565b50602190565b50600990565b6101400190565b6102a00190565b60400190565b6101200190565b60010190565b90815260200190565b919050565b5090565b600061124882612ccd565b151590565b6001600160a01b031690565b6001600160a81b031690565b63ffffffff1690565b67ffffffffffffffff1690565b600061124882612cee565b82818337506000910152565b60005b83811015612d2d578181015183820152602001612d15565b83811115612d3c576000848401525b50505050565b6000611248612d5083612c59565b612c59565b600061124882600061124882612d8d565b600061124882612d87565b60006112488254612d42565b601f01601f191690565b60c01b90565b60601b90565b612d9c81612cd9565b8114612da757600080fd5b50565b612d9c81612cc8565b612d9c81612c5956fea36474726f6e58207ef421e01e827fa1d2e384579b655503e18aef0f4bf9ff3e5176a254c97da9036c6578706572696d656e74616cf564736f6c637828302e352e31322d646576656c6f702e323032302e362e31352b636f6d6d69742e34323336323638380065" + code_getAddressChange = "608060405260e3806100126000396000f3fe6080604052348015600f57600080fd5b50d38015601b57600080fd5b50d28015602757600080fd5b5060043610604a5760003560e01c806358c6464814604f578063b4cef28d146071575b600080fd5b605560a6565b604080516001600160a01b039092168252519081900360200190f35b609460048036036020811015608557600080fd5b50356001600160a01b031660aa565b60408051918252519081900360200190f35b3090565b50479056fea26474726f6e58208f096542a0e814a7dd8434fd85def0ee9521b022f5cad9176f1c993e2615bdad64736f6c634300050f0031" + code_fallbackOldVersionTest = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b506101d98061003a6000396000f3fe60c0604052600860808190526766616c6c6261636b60c01b60a0908152610029916000919061010a565b506040805181815260008054600260001961010060018416150201909116049282018390527f1f0af026fd1015e37743a803fa8c7b92c09a6fc99890b1681a1e3c888427c25e9290918291369190819060208201906060830190869080156100d25780601f106100a7576101008083540402835291602001916100d2565b820191906000526020600020905b8154815290600101906020018083116100b557829003601f168201915b50508381038252848152602001858580828437600083820152604051601f909101601f191690920182900397509095505050505050a1005b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061014b57805160ff1916838001178555610178565b82800160010185558215610178579182015b8281111561017857825182559160200191906001019061015d565b50610184929150610188565b5090565b6101a291905b80821115610184576000815560010161018e565b9056fea26474726f6e5820e77b862582c00095aa34fd5c2839c0d8f209bdac194c0adeec660fa15a08fbe464736f6c634300050f0031" + code_fallbackOldVersionCall = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b506101748061003a6000396000f3fe60806040526004361061001e5760003560e01c8063f55332ab14610023575b600080fd5b6100496004803603602081101561003957600080fd5b50356001600160a01b031661005d565b604080519115158252519081900360200190f35b60408051600481526024810182526020810180516001600160e01b031663f85396d760e01b1781529151815160009384936001600160a01b038716939092909182918083835b602083106100c25780518252601f1990920191602091820191016100a3565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114610124576040519150601f19603f3d011682016040523d82523d6000602084013e610129565b606091505b505090508061013757600080fd5b5060019291505056fea26474726f6e58203498e1c23a661ae640e44836405d25839850ec79748cabd2dab945fd13ee0c7c64736f6c634300050f0031" + code_arrayLength_0.5.15 = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b506102708061003a6000396000f3fe608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50600436106100455760003560e01c8063cbcec91e1461004a575b600080fd5b6100526100a2565b60408051602080825283518183015283519192839290830191858101910280838360005b8381101561008e578181015183820152602001610076565b505050509050019250505060405180910390f35b60008054600181018255818052602081047f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56301805460ff601f9093166101000a928302191690911790556060906003906100fc90826101e5565b50600080549061010f90600183016101e5565b5060008054906101239060001983016101e5565b5060008054906101379060001983016101e5565b50600080548061014357fe5b60008281526020808220600019909301818104909301805460ff601f86166101000a0219169055919092558154604080518284028101840190915281815292918301828280156101da57602002820191906000526020600020906000905b825461010083900a900460f81b6001600160f81b0319168152602060019283018181049485019490930390920291018084116101a15790505b505050505090505b90565b81548183558181111561021957601f016020900481601f01602090048360005260206000209182019101610219919061021e565b505050565b6101e291905b808211156102385760008155600101610224565b509056fea26474726f6e582030f1b13e292e442f2c4de67e0d5bb6f78dd7f44f99e5f2fa3952de6c9d94dd8b64736f6c634300050e0031" + code_override001 = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b5060d8806100396000396000f3fe6080604052348015600f57600080fd5b50d38015601b57600080fd5b50d28015602757600080fd5b506004361060545760003560e01c80630c55699c14605957806355241077146071578063a56dfe4a14608d575b600080fd5b605f6093565b60408051918252519081900360200190f35b608b60048036036020811015608557600080fd5b50356099565b005b605f609e565b60005481565b600155565b6001548156fea26474726f6e58204b9c06785956097a789fe5d4b75dbe9390a30c48c3080d3c14d8655cb84e11e564736f6c634300050f0031" + code_override002 = "6080604052600460005534801561001557600080fd5b50d3801561002257600080fd5b50d2801561002f57600080fd5b5061012b8061003f6000396000f3fe6080604052348015600f57600080fd5b50d38015601b57600080fd5b50d28015602757600080fd5b506004361060545760003560e01c80630c55699c1460595780635524107714607157806374d393f014608d575b600080fd5b605f60a7565b60408051918252519081900360200190f35b608b60048036036020811015608557600080fd5b503560ad565b005b608b6004803603602081101560a157600080fd5b503560f2565b60005481565b6006600054101560f2576040805162461bcd60e51b815260206004820152600b60248201526a3c1036bab9ba101f1e901b60a91b604482015290519081900360640190fd5b60005556fea26474726f6e5820d72f89553adaa33af6034260ea794957bdaebd8e26bccaac25c685c1bd1e8f2764736f6c634300050f0031" + code_override003 = "608060405260008054600160ff19918216811761ff0019169092556301efa6ad9091556301efa6ac19600255630166654f6003908155600480546001600160a01b03191673dcad3a6d3569df655070ded06cb7a1b2ccd1d3af1790557fb55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105c6005556006805490921617905534801561009557600080fd5b50d380156100a257600080fd5b50d280156100af57600080fd5b506101c8806100bf6000396000f3fe608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50600436106100a25760003560e01c806398f42fe31161007557806398f42fe31461012d578063a223e05d14610135578063e5aa3d581461013d578063f8aab23814610145576100a2565b806375f12b21146100a757806383cdfab8146100c357806387cfa5bf146100dd578063938b5f3214610109575b600080fd5b6100af61014d565b604080519115158252519081900360200190f35b6100cb61015b565b60408051918252519081900360200190f35b6100e5610161565b604051808260038111156100f557fe5b60ff16815260200191505060405180910390f35b61011161016a565b604080516001600160a01b039092168252519081900360200190f35b6100e5610179565b6100cb610182565b6100cb610188565b6100cb61018e565b600054610100900460ff1681565b60025481565b60005460ff1681565b6004546001600160a01b031681565b60065460ff1681565b60035481565b60015481565b6005548156fea26474726f6e5820dacca6ecfb02875aede259b98aa35a6aba6aea8284a01f0c82fdeba6ffc8012d64736f6c634300050f0031" + code_virtual001 = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b506103778061003a6000396000f3fe608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b506004361061007c5760003560e01c80630c55699c146100815780631e26fd331461009b57806355241077146100bc5780637fcaf666146100d9578063a56dfe4a14610149578063c5d7802e14610165575b600080fd5b6100896101e2565b60408051918252519081900360200190f35b6100ba600480360360208110156100b157600080fd5b503515156101e8565b005b6100ba600480360360208110156100d257600080fd5b50356101fb565b6100ba600480360360208110156100ef57600080fd5b81019060208101813564010000000081111561010a57600080fd5b82018360208201111561011c57600080fd5b8035906020019184600183028401116401000000008311171561013e57600080fd5b509092509050610200565b610151610211565b604080519115158252519081900360200190f35b61016d61021a565b6040805160208082528351818301528351919283929083019185019080838360005b838110156101a757818101518382015260200161018f565b50505050905090810190601f1680156101d45780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60015481565b6002805460ff1916911515919091179055565b600155565b61020c600083836102a8565b505050565b60025460ff1681565b6000805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156102a05780601f10610275576101008083540402835291602001916102a0565b820191906000526020600020905b81548152906001019060200180831161028357829003601f168201915b505050505081565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106102e95782800160ff19823516178555610316565b82800160010185558215610316579182015b828111156103165782358255916020019190600101906102fb565b50610322929150610326565b5090565b61034091905b80821115610322576000815560010161032c565b9056fea26474726f6e5820b48ac0b0a646831f6a4069f95888081a6e12cd0ffb453b66d879c3f04e3b71ec64736f6c634300050f0031" } @@ -502,4 +510,12 @@ abi = { abi_SideGateway = "[{\"constant\":false,\"inputs\":[{\"name\":\"_sunTokenAddress\",\"type\":\"address\"}],\"name\":\"setSunTokenAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"b1\",\"type\":\"bytes\"},{\"name\":\"b2\",\"type\":\"bytes\"}],\"name\":\"concatBytes\",\"outputs\":[{\"name\":\"r\",\"type\":\"bytes\"}],\"payable\":false,\"stateMutability\":\"pure\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"txData\",\"type\":\"bytes\"}],\"name\":\"withdrawTRX\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"trc10\",\"type\":\"uint256\"},{\"name\":\"value\",\"type\":\"uint256\"},{\"name\":\"name\",\"type\":\"bytes32\"},{\"name\":\"symbol\",\"type\":\"bytes32\"},{\"name\":\"decimals\",\"type\":\"uint8\"}],\"name\":\"depositTRC10\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"mainChainAddress\",\"type\":\"address\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"depositTRC20\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"trc10Map\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"mainToSideContractMap\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"txId\",\"type\":\"bytes\"},{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"symbol\",\"type\":\"string\"},{\"name\":\"decimals\",\"type\":\"uint8\"}],\"name\":\"deployDAppTRC20AndMapping\",\"outputs\":[{\"name\":\"r\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"sunTokenAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"txId\",\"type\":\"bytes\"},{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"calcContractAddress\",\"outputs\":[{\"name\":\"r\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"pure\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_oracle\",\"type\":\"address\"},{\"name\":\"isOracle\",\"type\":\"bool\"}],\"name\":\"modifyOracle\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"txId\",\"type\":\"bytes\"},{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"symbol\",\"type\":\"string\"}],\"name\":\"deployDAppTRC721AndMapping\",\"outputs\":[{\"name\":\"r\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"oracles\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"from\",\"type\":\"address\"},{\"name\":\"value\",\"type\":\"uint256\"},{\"name\":\"txData\",\"type\":\"bytes\"}],\"name\":\"onTRC20Received\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes4\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"from\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"uint256\"},{\"name\":\"txData\",\"type\":\"bytes\"}],\"name\":\"onTRC721Received\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes4\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"sideToMainContractMap\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"a\",\"type\":\"address\"}],\"name\":\"addressToBytes\",\"outputs\":[{\"name\":\"b\",\"type\":\"bytes\"}],\"payable\":false,\"stateMutability\":\"pure\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"txData\",\"type\":\"bytes\"}],\"name\":\"withdrawTRC10\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"depositTRX\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"mainChainAddress\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"depositTRC721\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"_oracle\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"developer\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"mainChainAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"sideChainAddress\",\"type\":\"address\"}],\"name\":\"DeployDAppTRC20AndMapping\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"developer\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"mainChainAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"sideChainAddress\",\"type\":\"address\"}],\"name\":\"DeployDAppTRC721AndMapping\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"trc10\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"DepositTRC10\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"sideChainAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"DepositTRC20\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"sideChainAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"DepositTRC721\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"DepositTRX\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"trc10\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"txData\",\"type\":\"bytes\"}],\"name\":\"WithdrawTRC10\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"mainChainAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"txData\",\"type\":\"bytes\"}],\"name\":\"WithdrawTRC20\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"mainChainAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"txData\",\"type\":\"bytes\"}],\"name\":\"WithdrawTRC721\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"txData\",\"type\":\"bytes\"}],\"name\":\"WithdrawTRX\",\"type\":\"event\"}]" abi_shieldTrc20Token = "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"burn\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"burnFrom\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"},{\"name\":\"_extraData\",\"type\":\"bytes\"}],\"name\":\"approveAndCall\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"},{\"name\":\"\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialSupply\",\"type\":\"uint256\"},{\"name\":\"tokenName\",\"type\":\"string\"},{\"name\":\"tokenSymbol\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Burn\",\"type\":\"event\"}]" abi_shield = "[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"trc20ContractAddress\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"scalingFactorExponent\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"position\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"cm\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"cv\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"epk\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32[21]\",\"name\":\"c\",\"type\":\"bytes32[21]\"}],\"name\":\"BurnNewLeaf\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"position\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"cm\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"cv\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"epk\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32[21]\",\"name\":\"c\",\"type\":\"bytes32[21]\"}],\"name\":\"MintNewLeaf\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"nf\",\"type\":\"bytes32\"}],\"name\":\"NoteSpent\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes32[3]\",\"name\":\"ciphertext\",\"type\":\"bytes32[3]\"}],\"name\":\"TokenBurn\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"TokenMint\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"position\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"cm\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"cv\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"epk\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32[21]\",\"name\":\"c\",\"type\":\"bytes32[21]\"}],\"name\":\"TransferNewLeaf\",\"type\":\"event\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"bytes32[10]\",\"name\":\"input\",\"type\":\"bytes32[10]\"},{\"internalType\":\"bytes32[2]\",\"name\":\"spendAuthoritySignature\",\"type\":\"bytes32[2]\"},{\"internalType\":\"uint256\",\"name\":\"rawValue\",\"type\":\"uint256\"},{\"internalType\":\"bytes32[2]\",\"name\":\"bindingSignature\",\"type\":\"bytes32[2]\"},{\"internalType\":\"address\",\"name\":\"payTo\",\"type\":\"address\"},{\"internalType\":\"bytes32[3]\",\"name\":\"burnCipher\",\"type\":\"bytes32[3]\"},{\"internalType\":\"bytes32[9][]\",\"name\":\"output\",\"type\":\"bytes32[9][]\"},{\"internalType\":\"bytes32[21][]\",\"name\":\"c\",\"type\":\"bytes32[21][]\"}],\"name\":\"burn\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"position\",\"type\":\"uint256\"}],\"name\":\"getPath\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32[32]\",\"name\":\"\",\"type\":\"bytes32[32]\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"latestRoot\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"leafCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"rawValue\",\"type\":\"uint256\"},{\"internalType\":\"bytes32[9]\",\"name\":\"output\",\"type\":\"bytes32[9]\"},{\"internalType\":\"bytes32[2]\",\"name\":\"bindingSignature\",\"type\":\"bytes32[2]\"},{\"internalType\":\"bytes32[21]\",\"name\":\"c\",\"type\":\"bytes32[21]\"}],\"name\":\"mint\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"noteCommitment\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"nullifiers\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"roots\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"scalingFactor\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"bytes32[10][]\",\"name\":\"input\",\"type\":\"bytes32[10][]\"},{\"internalType\":\"bytes32[2][]\",\"name\":\"spendAuthoritySignature\",\"type\":\"bytes32[2][]\"},{\"internalType\":\"bytes32[9][]\",\"name\":\"output\",\"type\":\"bytes32[9][]\"},{\"internalType\":\"bytes32[2]\",\"name\":\"bindingSignature\",\"type\":\"bytes32[2]\"},{\"internalType\":\"bytes32[21][]\",\"name\":\"c\",\"type\":\"bytes32[21][]\"}],\"name\":\"transfer\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"tree\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" + abi_getAddressChange = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"getamount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"testaddress1\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" + abi_fallbackOldVersionTest = "[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"data\",\"type\":\"string\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"msg\",\"type\":\"bytes\"}],\"name\":\"FallbackCall\",\"type\":\"event\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" + abi_fallbackOldversionCall = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"contract Test0\",\"name\":\"test\",\"type\":\"address\"}],\"name\":\"call\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"}]" + abi_arrayLenth_0.5.15 = "[{\"constant\":false,\"inputs\":[],\"name\":\"ChangeSize\",\"outputs\":[{\"internalType\":\"bytes1[]\",\"name\":\"\",\"type\":\"bytes1[]\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" + abi_override001 = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_y\",\"type\":\"uint256\"}],\"name\":\"setValue\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"x\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"y\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" + abi_override002 = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_x\",\"type\":\"uint256\"}],\"name\":\"setValue\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_x\",\"type\":\"uint256\"}],\"name\":\"setValue2\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"x\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" + abi_override003 = "[{\"constant\":true,\"inputs\":[],\"name\":\"b32\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"choice\",\"outputs\":[{\"internalType\":\"enum Base.ActionChoices\",\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"choice2\",\"outputs\":[{\"internalType\":\"enum Base.ActionChoices\",\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"i\",\"outputs\":[{\"internalType\":\"int256\",\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"i2\",\"outputs\":[{\"internalType\":\"int256\",\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"origin\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"stopped\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"ui\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" + abi_virtual001 = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"bool\",\"name\":\"_y\",\"type\":\"bool\"}],\"name\":\"setBool\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"string\",\"name\":\"_z\",\"type\":\"string\"}],\"name\":\"setString\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_x\",\"type\":\"uint256\"}],\"name\":\"setValue\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"x\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"y\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"z\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" } \ No newline at end of file diff --git a/gradle/unixStartScript.txt b/gradle/unixStartScript.txt index 48cdff8c5f4..585998cb8c9 100644 --- a/gradle/unixStartScript.txt +++ b/gradle/unixStartScript.txt @@ -1,4 +1,4 @@ -#!/usr/bin/env sh +#!/usr/bin/env bash # # Copyright 2015 the original author or authors. diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 1b0ff046d00..1b00285c540 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.10-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip diff --git a/jitpack.yml b/jitpack.yml index 59c00d5783e..f951e400136 100644 --- a/jitpack.yml +++ b/jitpack.yml @@ -1,2 +1,2 @@ install: - - ./gradlew build publishToMavenLocal -x test + - ./gradlew clean -xtest -xlint -xcheck -PbinaryRelease=false install \ No newline at end of file diff --git a/protocol/src/main/protos/api/api.proto b/protocol/src/main/protos/api/api.proto index 7eb38fee78e..c56ced503b0 100644 --- a/protocol/src/main/protos/api/api.proto +++ b/protocol/src/main/protos/api/api.proto @@ -41,6 +41,26 @@ service Wallet { }; }; + rpc GetAccountBalance (AccountBalanceRequest) returns (AccountBalanceResponse) { + option (google.api.http) = { + post: "/wallet/getaccountbalance" + body: "*" + additional_bindings { + get: "/wallet/getaccountbalance" + } + }; + }; + + rpc GetBlockBalanceTrace (BlockBalanceTrace.BlockIdentifier) returns (BlockBalanceTrace) { + option (google.api.http) = { + post: "/wallet/getblockbalancetrace" + body: "*" + additional_bindings { + get: "/wallet/getblockbalancetrace" + } + }; + }; + //Please use CreateTransaction2 instead of this function. rpc CreateTransaction (TransferContract) returns (Transaction) { option (google.api.http) = { @@ -757,6 +777,9 @@ service Wallet { rpc GetTransactionInfoByBlockNum (NumberMessage) returns (TransactionInfoList) { } + + rpc GetBurnTrx (EmptyMessage) returns (NumberMessage) { + } }; service WalletSolidity { @@ -940,6 +963,8 @@ service WalletSolidity { rpc GetMarketPairList (EmptyMessage) returns (MarketOrderPairList) { } + rpc GetBurnTrx (EmptyMessage) returns (NumberMessage) { + } }; service WalletExtension { diff --git a/protocol/src/main/protos/core/Tron.proto b/protocol/src/main/protos/core/Tron.proto index ccc11cde4ec..4b5ca259466 100644 --- a/protocol/src/main/protos/core/Tron.proto +++ b/protocol/src/main/protos/core/Tron.proto @@ -445,6 +445,7 @@ message TransactionInfo { bytes orderId = 25; repeated MarketOrderDetail orderDetails = 26; + int64 packingFee = 27; } diff --git a/protocol/src/main/protos/core/contract/balance_contract.proto b/protocol/src/main/protos/core/contract/balance_contract.proto index 5dd3dd177ba..293f62bed5b 100644 --- a/protocol/src/main/protos/core/contract/balance_contract.proto +++ b/protocol/src/main/protos/core/contract/balance_contract.proto @@ -33,4 +33,50 @@ message TransferContract { bytes owner_address = 1; bytes to_address = 2; int64 amount = 3; -} \ No newline at end of file +} + +message TransactionBalanceTrace { + message Operation { + int64 operation_identifier = 1; + bytes address = 2; + int64 amount = 3; + } + + bytes transaction_identifier = 1; + repeated Operation operation = 2; + string type = 3; + string status = 4; +} + + + +message BlockBalanceTrace { + message BlockIdentifier { + bytes hash = 1; + int64 number = 2; + } + + BlockIdentifier block_identifier = 1; + int64 timestamp = 2; + repeated TransactionBalanceTrace transaction_balance_trace = 3; +// BlockIdentifier parent_block_identifier = 4; +} + +message AccountTrace { + int64 balance = 1; + int64 placeholder = 99; +} + +message AccountIdentifier { + bytes address = 1; +} + +message AccountBalanceRequest { + AccountIdentifier account_identifier = 1; + BlockBalanceTrace.BlockIdentifier block_identifier = 2; +} + +message AccountBalanceResponse { + int64 balance = 1; + BlockBalanceTrace.BlockIdentifier block_identifier = 2; +} diff --git a/protocol/src/main/protos/core/contract/smart_contract.proto b/protocol/src/main/protos/core/contract/smart_contract.proto index 4f09e76e67b..f53afa37be1 100644 --- a/protocol/src/main/protos/core/contract/smart_contract.proto +++ b/protocol/src/main/protos/core/contract/smart_contract.proto @@ -17,6 +17,7 @@ message SmartContract { Function = 2; Event = 3; Fallback = 4; + Receive = 5; } message Param { bool indexed = 1;