From 6326f6c82d29a2b7860a6bc03ff967b4417ee43a Mon Sep 17 00:00:00 2001 From: yangzhenlong Date: Wed, 28 Aug 2019 18:52:38 +0800 Subject: [PATCH 1/9] add introduction document --- README.md | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/README.md b/README.md index a51a0620..87898020 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,44 @@ public Object callContract(String contractAddress, AbiDefinition functionAbi, St While contract file is required when first deploy the contract, cita-sdk-java can get the abi file according to address when call methods in deployed contract. Please find complete code in [TokenAccountExample](https://github.com/cryptape/cita-sdk-java/blob/master/tests/src/main/java/com/cryptape/cita/tests/TokenAccountExample.java). +## Contributing + +### Creating a Bug Report +open a new issue: https://github.com/cryptape/cita-sdk-java/issues/new + +with your version info + +### Tech Stack + +#### Back end +Java +- Version: 8 +- Building: gradle-v5.0 + +### Coding style +coding style guide: Google Shell Style guide: +- https://google.github.io/styleguide/javaguide.html + +#### Installing the coding style settings in Intellij +1. Download the intellij-java-google-style.xml file from the http://code.google.com/p/google-styleguide/ repo. +2. go into Preferences -> Editor -> Code Style. Click on Manage and import the downloaded Style Setting file. Select GoogleStyle as new coding style. + +#### Installing the coding style settings in Eclipse +1. Download the eclipse-java-google-style.xml file from the http://code.google.com/p/google-styleguide/ repo. +2. Under Window/Preferences select Java/Code Style/Formatter. Import the settings file by selecting Import. + +### Commit your changes + +#### Workflow +[GitHub Flow](https://help.github.com/en/articles/github-flow), [Understanding the GitHub flow](https://guides.github.com/introduction/flow/) + +#### git style guide +use [git-style-guide](https://github.com/agis/git-style-guide) for Branches, Commits,Messages, Merging + +## Versioning +vx.y.z +- x.y Follow the version number of CITA +- z Defined by SDK itself:changed by fixing or adding features ## 简介 cita-sdk-java 是对以太坊 Web3j 进行改写,适配 CITA 的一个 Java 开发包。cita-sdk-java 集成了与 CITA 客户端交互的功能,可以用来对 CITA 发送交易,系统配置,信息查询。 @@ -198,6 +236,7 @@ https://node.cryptape.com 如果需要了解怎么部署 CITA 网络,请查阅[CITA](https://github.com/cryptape/cita)。 ### 快速教程 + #### 部署智能合约 与以太坊类似,智能合约是通过发送交易来部署的。CITA 交易对象定义在 [Transaction.java](https://github.com/cryptape/cita-sdk-java/blob/master/core/src/main/java/com/cryptape/cita/protocol/core/methods/request/Transaction.java)。 在 CITA 交易中,有三个特殊的参数: @@ -284,3 +323,42 @@ public Object callContract(String contractAddress, AbiDefinition functionAbi, St ``` 虽然在第一次部署合约的时候需要提供合约文件,但是在以后调用合约函数的时候 cita-sdk-java 通过 CITA 提供的 getAbi 接口根据合约地址得到对应的 abi。 请在 [TokenAccountExample](https://github.com/cryptape/cita-sdk-java/blob/master/tests/src/main/java/com/cryptape/cita/tests/TokenAccountExample.java) 中查看完整代码。 + +## 参与贡献 + +### 报告Bug +提交 issue: https://github.com/cryptape/cita-sdk-java/issues/new +记得声明所使用软件的版本信息 + +### 技术栈 + +#### Back end +Java +- Version: 8 +- Building: gradle-v5.0 + +### 编码规范 +使用《Google java编程规范》作为我们的编码规范: +- 英文版: https://google.github.io/styleguide/javaguide.html +- 中文版: https://jervyshi.gitbooks.io/google-java-styleguide-zh/content/ + +#### Installing the coding style settings in Intellij +1. Download the intellij-java-google-style.xml file from the http://code.google.com/p/google-styleguide/ repo. +2. go into Preferences -> Editor -> Code Style. Click on Manage and import the downloaded Style Setting file. Select GoogleStyle as new coding style. + +#### Installing the coding style settings in Eclipse +1. Download the eclipse-java-google-style.xml file from the http://code.google.com/p/google-styleguide/ repo. +2. Under Window/Preferences select Java/Code Style/Formatter. Import the settings file by selecting Import. + +### 代码提交规范 + +#### 代码提交流程 +[GitHub Flow](https://help.github.com/en/articles/github-flow), [Understanding the GitHub flow](https://guides.github.com/introduction/flow/) + +#### git style guide +我们要求遵守 [git-style-guide](https://github.com/agis/git-style-guide) 中的规则来进行分支创建、提交以及合并操作。 + +## 版本规则 +vx.y.z +- x.y 跟随 CITA 的版本号; +- z 由 SDK 自己定义:修复或增加feature 则变化 \ No newline at end of file From 9b653c0a750499f75514b2db1525d295e56eb1af Mon Sep 17 00:00:00 2001 From: qiaorong Date: Wed, 28 Aug 2019 09:53:23 +0800 Subject: [PATCH 2/9] Add some new functions for group management, modify queryGroups and newGroup for more rubust. --- .../protocol/system/CITASystemContract.java | 3 +- .../protocol/system/CITAjSystemContract.java | 144 +++++++++++++----- .../java/com/cryptape/cita/tests/Config.java | 3 + .../cita/tests/GroupManagerExample.java | 83 ++++++++-- .../main/resources/config.properties.example | 2 + 5 files changed, 177 insertions(+), 58 deletions(-) diff --git a/core/src/main/java/com/cryptape/cita/protocol/system/CITASystemContract.java b/core/src/main/java/com/cryptape/cita/protocol/system/CITASystemContract.java index 0b724b38..02c08af7 100644 --- a/core/src/main/java/com/cryptape/cita/protocol/system/CITASystemContract.java +++ b/core/src/main/java/com/cryptape/cita/protocol/system/CITASystemContract.java @@ -89,6 +89,7 @@ public interface CITASystemContract { String Authorization_MANAGER_CHECK_RESOURCE = "checkResource"; //User manager + String INTRA_GROUP_USER_MANAGEMENT_ADDR = "0xfFFfFFFFFffFFfffFFFFfffffFffffFFfF020009"; String USER_MANAGER_ADDR = "0xffffffffffffffffffffffffffffffffff02000a"; //User manager manipulation String USER_MANAGER_NEW_GROUP = "newGroup"; @@ -228,4 +229,4 @@ static AppCall sendCall(String from, String addr, } long getQuotaPrice(String from) throws IOException; -} \ No newline at end of file +} diff --git a/core/src/main/java/com/cryptape/cita/protocol/system/CITAjSystemContract.java b/core/src/main/java/com/cryptape/cita/protocol/system/CITAjSystemContract.java index 1da4586b..d6e267b7 100644 --- a/core/src/main/java/com/cryptape/cita/protocol/system/CITAjSystemContract.java +++ b/core/src/main/java/com/cryptape/cita/protocol/system/CITAjSystemContract.java @@ -116,72 +116,72 @@ public long getQuotaPrice(String from) throws IOException { } public boolean approveNode( - String nodeAddr, String adminPrivatekey, int version, BigInteger chainId) + String nodeAddr, String adminPrivateKey, int version, BigInteger chainId) throws IOException, InterruptedException { List inputParameters = Collections.singletonList(new Address(nodeAddr)); String funcData = CITASystemContract.encodeFunction( NODE_MANAGER_APPROVE_NODE, inputParameters); String txHash = CITASystemContract.sendTxAndGetHash( - NODE_MANAGER_ADDR, service, adminPrivatekey, funcData, version, chainId); + NODE_MANAGER_ADDR, service, adminPrivateKey, funcData, version, chainId); Log log = CITASystemContract.getReceiptLog(service, txHash, 0); return log != null && log.getTopics().contains(Util.addUpTo64Hex(nodeAddr)); } public boolean deleteNode( - String nodeAddr, String adminPrivatekey, int version, BigInteger chainId) + String nodeAddr, String adminPrivateKey, int version, BigInteger chainId) throws IOException, InterruptedException { List inputParameters = Collections.singletonList(new Address(nodeAddr)); String funcData = CITASystemContract.encodeFunction( NODE_MANAGER_DELETE_NODE, inputParameters); String txHash = CITASystemContract.sendTxAndGetHash( - NODE_MANAGER_ADDR, service, adminPrivatekey, funcData, version, chainId); + NODE_MANAGER_ADDR, service, adminPrivateKey, funcData, version, chainId); Log log = CITASystemContract.getReceiptLog(service, txHash, 0); return log != null && log.getTopics().contains(Util.addUpTo64Hex(nodeAddr)); } public boolean setStake( - String nodeAddr, int stake, String adminPrivatekey, int version, BigInteger chainId) + String nodeAddr, int stake, String adminPrivateKey, int version, BigInteger chainId) throws IOException, InterruptedException { List inputParameters = Arrays.asList(new Address(nodeAddr), new Uint64(stake)); String funcData = CITASystemContract.encodeFunction(NODE_MANAGER_SET_STAKE, inputParameters); String txHash = CITASystemContract.sendTxAndGetHash( - NODE_MANAGER_ADDR, service, adminPrivatekey, funcData, version, chainId); + NODE_MANAGER_ADDR, service, adminPrivateKey, funcData, version, chainId); Log log = CITASystemContract.getReceiptLog(service, txHash, 0); return log != null && log.getTopics().contains(Util.addUpTo64Hex(nodeAddr)); } public boolean setBql( - BigInteger bqlToSet, String adminPrivatekey, int version, BigInteger chainId) + BigInteger bqlToSet, String adminPrivateKey, int version, BigInteger chainId) throws IOException, InterruptedException { List inputParameters = Collections.singletonList(new Uint(bqlToSet)); String funcData = CITASystemContract.encodeFunction(QUOTA_MANAGER_SET_BQL, inputParameters); String txHash = CITASystemContract.sendTxAndGetHash( - QUOTA_MANAGER_ADDR, service, adminPrivatekey, funcData, version, chainId); + QUOTA_MANAGER_ADDR, service, adminPrivateKey, funcData, version, chainId); Log log = CITASystemContract.getReceiptLog(service, txHash, 0); return log != null && log.getTopics().contains(Util.addUpTo64Hex(bqlToSet.toString(16))); } public boolean setDefaultAql( - BigInteger defaultAqlToSet, String adminPrivatekey, int version, BigInteger chainId) + BigInteger defaultAqlToSet, String adminPrivateKey, int version, BigInteger chainId) throws IOException, InterruptedException { List inputParameters = Collections.singletonList(new Uint(defaultAqlToSet)); String funcData = CITASystemContract.encodeFunction(QUOTA_MANAGER_SET_DEFAULT_AQL, inputParameters); String txHash = CITASystemContract.sendTxAndGetHash( - QUOTA_MANAGER_ADDR, service, adminPrivatekey, funcData, version, chainId); + QUOTA_MANAGER_ADDR, service, adminPrivateKey, funcData, version, chainId); Log log = CITASystemContract.getReceiptLog(service, txHash, 0); return log != null && log.getTopics().contains(Util.addUpTo64Hex(defaultAqlToSet.toString(16))); } public boolean setAql( - String addrToSet, BigInteger aqlToSet, String adminPrivatekey, int version, BigInteger chainId) + String addrToSet, BigInteger aqlToSet, String adminPrivateKey, int version, BigInteger chainId) throws IOException, InterruptedException { List inputParameters = Arrays.asList(new Address(addrToSet), new Uint(aqlToSet)); String funcData = CITASystemContract.encodeFunction(QUOTA_MANAGER_SET_AQL, inputParameters); String txHash = CITASystemContract.sendTxAndGetHash( - QUOTA_MANAGER_ADDR, service, adminPrivatekey, funcData, version, chainId); + QUOTA_MANAGER_ADDR, service, adminPrivateKey, funcData, version, chainId); Log log = CITASystemContract.getReceiptLog(service, txHash, 0); return log != null && log.getTopics().contains(Util.addUpTo64Hex(addrToSet)); } @@ -257,7 +257,7 @@ public String newPermission( String name, List addrs, List funcs, - String adminPrivatekey, + String adminPrivateKey, int version, BigInteger chainId) throws IOException, InterruptedException { @@ -283,7 +283,7 @@ public String newPermission( String funcData = CITASystemContract.encodeFunction( PERMISSION_MANAGER_NEW_PERMISSION, inputParameters); String txHash = CITASystemContract.sendTxAndGetHash( - PERMISSION_MANAGER_ADDR, service, adminPrivatekey, funcData, version, chainId); + PERMISSION_MANAGER_ADDR, service, adminPrivateKey, funcData, version, chainId); Log log = CITASystemContract.getReceiptLog(service, txHash, 0); return log == null ? "" : log.getAddress(); @@ -580,6 +580,76 @@ public QueryResourceResult queryResource(String fromAddr, String permissionAddr) return new QueryResourceResult(contracts, functions); } + public boolean deleteGroup(String groupAddr, String adminPrivateKey, int version, BigInteger chainId) throws Exception { + List inputParameter = Arrays.asList(new Address(INTRA_GROUP_USER_MANAGEMENT_ADDR), + new Address(groupAddr)); + String funcData = CITASystemContract.encodeFunction( + USER_MANAGER_DELETE_GROUP, inputParameter); + String txHash = CITASystemContract.sendTxAndGetHash( + USER_MANAGER_ADDR, service, adminPrivateKey, funcData, version, chainId); + return CITASystemContract.checkReceipt(service, txHash); + } + + public boolean updateGroupName(String groupAddr, String newGroupName, String adminPrivateKey, int version, BigInteger chainId) throws Exception { + String nameHex = Util.addUpTo64Hex(ConvertStrByte.stringToHexString(newGroupName)); + byte[] nameBytes = ConvertStrByte.hexStringToBytes(Numeric.cleanHexPrefix(nameHex)); + + List inputParameters = Arrays.asList(new Address(INTRA_GROUP_USER_MANAGEMENT_ADDR), + new Address(groupAddr), new Bytes32(nameBytes)); + String funcData = CITASystemContract.encodeFunction( + USER_MANAGER_UPDATE_GROUP_NAME, inputParameters); + String txHash = CITASystemContract.sendTxAndGetHash( + USER_MANAGER_ADDR, service, adminPrivateKey, funcData, version, chainId); + return CITASystemContract.checkReceipt(service, txHash); + } + + public boolean addAccounts(String groupAddr, List accounts, String adminPrivateKey, int version, BigInteger chainId) throws Exception { + List
addrsToAdd = new ArrayList<>(); + for (String str : accounts) { + addrsToAdd.add(new Address(str)); + } + List inputParameters = Arrays.asList( + new Address(INTRA_GROUP_USER_MANAGEMENT_ADDR), + new Address(groupAddr), + new DynamicArray
(addrsToAdd)); + + String funcData = CITASystemContract.encodeFunction( + USER_MANAGER_ADD_ACCOUNTS, inputParameters); + String txHash = CITASystemContract.sendTxAndGetHash( + USER_MANAGER_ADDR, service, adminPrivateKey, funcData, version, chainId); + return CITASystemContract.checkReceipt(service, txHash); + } + + public boolean deleteAccounts(String groupAddr, List accounts, String adminPrivateKey, int version, BigInteger chainId) throws Exception { + List
addrsToAdd = new ArrayList<>(); + for (String str : accounts) { + addrsToAdd.add(new Address(str)); + } + List inputParameters = Arrays.asList( + new Address(INTRA_GROUP_USER_MANAGEMENT_ADDR), + new Address(groupAddr), + new DynamicArray
(addrsToAdd)); + + String funcData = CITASystemContract.encodeFunction( + USER_MANAGER_DELETE_ACCOUNTS, inputParameters); + String txHash = CITASystemContract.sendTxAndGetHash( + USER_MANAGER_ADDR, service, adminPrivateKey, funcData, version, chainId); + return CITASystemContract.checkReceipt(service, txHash); + } + + public boolean checkScope(String groupAddr, String adminPrivateKey, int version, BigInteger chainId) throws Exception { + List inputParameters = Arrays.asList( + new Address(INTRA_GROUP_USER_MANAGEMENT_ADDR), + new Address(groupAddr)); + + String funcData = CITASystemContract.encodeFunction( + USER_MANAGER_CHECK_SCOPE, inputParameters); + String txHash = CITASystemContract.sendTxAndGetHash( + USER_MANAGER_ADDR, service, adminPrivateKey, funcData, version, chainId); + return CITASystemContract.checkReceipt(service, txHash); + } + + /** * query all groups * @param senderAddress sender address @@ -593,9 +663,13 @@ public List queryGroups(String senderAddress) throws IOException { List> outputParamters = Collections.singletonList(new TypeReference>() {}); List resultTypes = CITASystemContract.decodeCallResult(callResult, outputParamters); + if (resultTypes.isEmpty()) + return null; + List list = new ArrayList<>(); ArrayList
results = (ArrayList
) resultTypes.get(0).getValue(); - List list = new ArrayList<>(results.size()); for (Address address : results) { + if (INTRA_GROUP_USER_MANAGEMENT_ADDR.equalsIgnoreCase(address.getValue())) + continue; list.add(address.getValue()); } return list; @@ -604,7 +678,6 @@ public List queryGroups(String senderAddress) throws IOException { /** * new group * @see newGroup - * @param superAdminAddress the address of super_admin * @param groupName the name of group to be created * @param accounts accounts added to the group * @param adminPrivateKey the private key of super_admin @@ -613,36 +686,25 @@ public List queryGroups(String senderAddress) throws IOException { * @return the transaction hash for creating group * @throws IOException */ - public String newGroup(String superAdminAddress, - String groupName, - List accounts, - String adminPrivateKey, - int version, - BigInteger chainId) throws IOException { - // account addresses convert to Address object list - List
addresses = new ArrayList<>(accounts.size()); - for(String acc : accounts){ - addresses.add(new Address(acc)); - } - - // groupName string convert to bytes32 + public String newGroup(String groupName, List accounts, String adminPrivateKey, int version, BigInteger chainId) throws Exception { String nameHex = Util.addUpTo64Hex(ConvertStrByte.stringToHexString(groupName)); byte[] nameBytes = ConvertStrByte.hexStringToBytes(Numeric.cleanHexPrefix(nameHex)); - - // build input parameters + List
addrsToAdd = new ArrayList<>(); + for (String str : accounts) { + addrsToAdd.add(new Address(str)); + } List inputParameters = Arrays.asList( - new Address(superAdminAddress),//origin - new Bytes32(nameBytes),//name - new DynamicArray
(addresses)//account - ); - - // encode input parameters - String funcData = CITASystemContract.encodeFunction(USER_MANAGER_NEW_GROUP, inputParameters); + new Address(INTRA_GROUP_USER_MANAGEMENT_ADDR), + new Bytes32(nameBytes), + new DynamicArray
(addrsToAdd)); - // send request to create group and return transaction hash + String funcData = CITASystemContract.encodeFunction( + USER_MANAGER_NEW_GROUP, inputParameters); String txHash = CITASystemContract.sendTxAndGetHash( USER_MANAGER_ADDR, service, adminPrivateKey, funcData, version, chainId); - return txHash; + + Log log = CITASystemContract.getReceiptLog(service, txHash, 0); + return log == null ? "" : log.getAddress(); } public Transaction constructStoreTransaction(String data, int version, BigInteger chainId) { @@ -651,4 +713,4 @@ public Transaction constructStoreTransaction(String data, int version, BigIntege Util.getValidUtilBlock(service).longValue(), version, chainId, "0", data); } -} \ No newline at end of file +} diff --git a/tests/src/main/java/com/cryptape/cita/tests/Config.java b/tests/src/main/java/com/cryptape/cita/tests/Config.java index 31e8a0d3..59b135c9 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/Config.java +++ b/tests/src/main/java/com/cryptape/cita/tests/Config.java @@ -25,6 +25,7 @@ public class Config { private static final String DEFAULT_QUOTA_Transfer = "QuotaForTransfer"; private static final String DEFAULT_QUOTA_Deployment = "QuotaForDeployment"; private static final String ADMIN_PRIVATE_KEY = "AdminPrivateKey"; + private static final String ADMIN_ADDRESS = "AdminAddress"; private static final String CRYPTO_TYPE = "CryptoType"; private Properties props; @@ -46,6 +47,7 @@ public class Config { public CITAj service; public String adminPrivateKey; public String cryptoTx; + public String adminAddress; public Config() { @@ -105,6 +107,7 @@ private void loadPropsToAttr(Properties props) { defaultQuotaDeployment = props.getProperty(DEFAULT_QUOTA_Deployment); adminPrivateKey = props.getProperty(ADMIN_PRIVATE_KEY); cryptoTx = props.getProperty(CRYPTO_TYPE); + adminAddress = props.getProperty(ADMIN_ADDRESS); } } diff --git a/tests/src/main/java/com/cryptape/cita/tests/GroupManagerExample.java b/tests/src/main/java/com/cryptape/cita/tests/GroupManagerExample.java index 08dac5f4..b5c07f67 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/GroupManagerExample.java +++ b/tests/src/main/java/com/cryptape/cita/tests/GroupManagerExample.java @@ -3,10 +3,14 @@ import com.cryptape.cita.protocol.core.methods.response.Log; import com.cryptape.cita.protocol.system.CITASystemContract; +import com.cryptape.cita.protocol.system.CITAjSystemContract; import java.io.IOException; +import java.math.BigInteger; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.concurrent.TimeUnit; /** * Group and Account Management @@ -14,21 +18,68 @@ * https://docs.citahub.com/zh-CN/cita/account-permission/account */ public class GroupManagerExample extends SystemContractExample { - public static void main(String[] args) throws IOException, InterruptedException { - // query groups - List groupAddress = sysContract.queryGroups("0xfFFfFFFFFffFFfffFFFFfffffFffffFFfF020009"); - System.out.println("groupAddress: " + groupAddress); - - // create a group - String transcationHash = sysContract.newGroup("0xfFFfFFFFFffFFfffFFFFfffffFffffFFfF020009", - "newGroup", - Arrays.asList("e1c4021742730ded647590a1686d5c4bfcbae0b0", "45a50f45cb81c8aedeab917ea0cd3c9178ebdcae"), - adminPriavteKey, - version, - chainId); - System.out.println("transcationHash: " + transcationHash); - // get receipt by hash - Log log = CITASystemContract.getReceiptLog(service, transcationHash, 0); - System.out.println("groupAddress: " + (log == null ? "null" : log.getAddress())); + static String senderAddr; + static String adminPrivateKey; + static int version; + static BigInteger chainId; + + static { + Config conf = new Config(); + conf.buildService(false); + service = conf.service; + senderAddr = conf.primaryAddr; + adminPrivateKey = conf.adminPrivateKey; + version = TestUtil.getVersion(service); + chainId = TestUtil.getChainId(service); + } + public static void main(String[] args) throws Exception { + CITAjSystemContract sysContract = new CITAjSystemContract(service); + + // New group + List addresses = new ArrayList<>(); + addresses.add("0x1c6eebf136ee234caff3a95e0d9d22e40c9ac4ca"); + String newGroupAddr = sysContract.newGroup("vlk1", addresses, adminPrivateKey, version, chainId); + if ("".equals(newGroupAddr)) { + System.out.println("New group failed!"); + return; + } + System.out.println("Address for new group: " + newGroupAddr); + TimeUnit.SECONDS.sleep(10); + + // Update group name + boolean updated = sysContract.updateGroupName(newGroupAddr, "TokenNew", adminPrivateKey, version, chainId); + System.out.println("Group updated: " + updated); + TimeUnit.SECONDS.sleep(10); + + // Add accounts + List addressNeedBeAdded = new ArrayList<>(); + addressNeedBeAdded.add("0xbac68e5cb986ead0253e0632da1131a0a96efa18"); + updated = sysContract.addAccounts(newGroupAddr, addressNeedBeAdded, adminPrivateKey, version, chainId); + System.out.println("Account is added: " + updated); + TimeUnit.SECONDS.sleep(10); + + // Delete accounts + updated = sysContract.deleteAccounts(newGroupAddr, addressNeedBeAdded, adminPrivateKey, version, chainId); + System.out.println("Account is deleted: " + updated); + TimeUnit.SECONDS.sleep(10); + + // Check scope + updated = sysContract.checkScope(newGroupAddr, adminPrivateKey, version, chainId); + System.out.println("Check scope: " + updated); + TimeUnit.SECONDS.sleep(10); + + // Query groups + List res = sysContract.queryGroups(senderAddr); + if (res != null) { + for (String s : res) { + System.out.println("Group address: " + s); + } + } + TimeUnit.SECONDS.sleep(10); + + // Delete group + updated = sysContract.deleteGroup(newGroupAddr, adminPrivateKey, version, chainId); + System.out.println("Group deleted: " + updated); + TimeUnit.SECONDS.sleep(10); } } diff --git a/tests/src/main/resources/config.properties.example b/tests/src/main/resources/config.properties.example index 1dea9796..443106e2 100644 --- a/tests/src/main/resources/config.properties.example +++ b/tests/src/main/resources/config.properties.example @@ -14,4 +14,6 @@ SimpleDataBin=tests/src/main/resources/SimpleData.bin QuotaForTransfer=21000 QuotaForDeployment=10000000 AdminPrivateKey=0x5a0257a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6 +# if use cita test net, you can recharge for this address +AdminAddress=0x827b05e4b070167a360e123fd06566eeb1a79fa5 CryptoType=SECP256K1 From 10b69c3684d4d899db20d47df04fa8f63ce79f3e Mon Sep 17 00:00:00 2001 From: chenhao Date: Thu, 19 Sep 2019 19:48:35 +0800 Subject: [PATCH 3/9] support matrix system test in travis --- .travis.yml | 29 +++++++--- scripts/run-system-test.sh | 44 +++++++++++++++ scripts/run-unit-test.sh | 4 ++ scripts/run.sh | 12 +++++ .../travis-upload-test-report-to-gh-pages.sh | 53 +++++++++++++++++++ 5 files changed, 134 insertions(+), 8 deletions(-) create mode 100644 scripts/run-system-test.sh create mode 100644 scripts/run-unit-test.sh create mode 100644 scripts/run.sh create mode 100755 scripts/travis-upload-test-report-to-gh-pages.sh diff --git a/.travis.yml b/.travis.yml index a65b5654..4dc2bf75 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,20 +5,33 @@ language: java jdk: - oraclejdk8 -sudo: false # as per http://blog.travis-ci.com/2014-12-17-faster-builds-with-container-based-infrastructure/ +env: + - TEST_TYPE=UT + - CITA_DOCKER_IMAGE_TAG_NAME=sha3 TEST_TYPE=ST TEST_CITA_VERSION=CITA1.0 + - CITA_DOCKER_IMAGE_TAG_NAME=sha3_88b90bb TEST_TYPE=ST TEST_CITA_VERSION=CITA0.25 + - CITA_DOCKER_IMAGE_TAG_NAME=sha3_1f10bc8 TEST_TYPE=ST TEST_CITA_VERSION=CITA0.24 + - CITA_DOCKER_IMAGE_TAG_NAME=sha3_b1e3048 TEST_TYPE=ST TEST_CITA_VERSION=CITA0.23.1 + +sudo: true # as per http://blog.travis-ci.com/2014-12-17-faster-builds-with-container-based-infrastructure/ # Avoid uploading cache after every build with Gradle - see https://docs.travis-ci.com/user/languages/java/#Caching before_cache: - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ + cache: directories: - - $HOME/.gradle/caches/ - - $HOME/.gradle/wrapper/ + - $HOME/.gradle/caches/ + - $HOME/.gradle/wrapper/ + +before_script: + # upgrade gradle to 5.0 + - wget http://services.gradle.org/distributions/gradle-5.0-all.zip > /dev/null + - unzip gradle-5.0-all.zip + - ./gradle-5.0/bin/gradle -v -# Add --info to view details of test failures -script: ./gradlew --info check jacocoRootTestReport +script: bash ./scripts/run.sh -# Upload code coverage metrics -after_success: - - bash <(curl -s https://codecov.io/bash) +## Upload code coverage metrics +#after_success: +# - bash <(curl -s https://codecov.io/bash) diff --git a/scripts/run-system-test.sh b/scripts/run-system-test.sh new file mode 100644 index 00000000..ce67a282 --- /dev/null +++ b/scripts/run-system-test.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash + +DEBUG_LOG_PATH=./debug_log.txt +# generate sdk and update docker image +rm -r console/build/libs/* | true +./gradle-5.0/bin/gradle shadowJar > ${DEBUG_LOG_PATH} +test -e console/build/libs/console-*-all.jar || echo "build sdk failed !!!" +test -e console/build/libs/console-*-all.jar || exit 1 +docker pull ${DOCKER_IMAGE_URL}:${CITA_DOCKER_IMAGE_TAG_NAME} > ${DEBUG_LOG_PATH} + +# get cita_quality code +cd .. +test -e cita_quality | git clone ${SYSTEM_TEST_CODE_URL} +cp cita-sdk-java/console/build/libs/console-*-all.jar ./cita_quality/systemTest/console.jar +cd ./cita_quality/systemTest +system_test_dir=$(pwd) +git checkout master | git pull + +# use local sdk change the maven sdk +CITA_SDk_VERSION=$( cat pom.xml | grep -A 1 ">core<" | grep version | awk -F "[<>]" '{print $3}') +CITA_SDK_LOCAL_FILE_PATH=${system_test_dir}/console-${CITA_SDk_VERSION}-all.jar +rm -r ${CITA_SDK_LOCAL_FILE_PATH} | true +cp -r ./console.jar ${CITA_SDK_LOCAL_FILE_PATH} + +echo ${CITA_SDK_LOCAL_FILE_PATH} +TARGET_TEXT_LINE=$(($( cat pom.xml | grep -n ">core<" | awk -F ":" '{print $1}')+2)) +echo ${TARGET_TEXT_LINE} +CITA_SDK_LOCAL_FILE_PATH=${CITA_SDK_LOCAL_FILE_PATH//\//\\/} +echo ${CITA_SDK_LOCAL_FILE_PATH} +sed -i "${TARGET_TEXT_LINE} s/^/${CITA_SDK_LOCAL_FILE_PATH}<\/systemPath>\n/" pom.xml +sed -i "${TARGET_TEXT_LINE} s/^/system<\/scope>\n/" pom.xml +cat pom.xml | grep -A 3 ">core<" + +# install cita-cli and run test +rm -r target/* +make install-cita-cli +mvn test -Dtest=com.cryptape.function.sdkcase.** +MAVEN_TEST_RESULT=$? + +# collect result +test -e $HOME/tmp || mkdir $HOME/tmp +test -e $HOME/tmp/${TRAVIS_JOB_ID} || mkdir $HOME/tmp/${TRAVIS_JOB_ID} +cp -R ${system_test_dir}/target/surefire-reports/html/* $HOME/tmp/${TRAVIS_JOB_ID}/ +exit ${MAVEN_TEST_RESULT} diff --git a/scripts/run-unit-test.sh b/scripts/run-unit-test.sh new file mode 100644 index 00000000..8e1119f9 --- /dev/null +++ b/scripts/run-unit-test.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash + +../gradlew --info check jacocoRootTestReport +bash <(curl -s https://codecov.io/bash) \ No newline at end of file diff --git a/scripts/run.sh b/scripts/run.sh new file mode 100644 index 00000000..689b6557 --- /dev/null +++ b/scripts/run.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + +if [ ${TEST_TYPE} == UT ]; then + echo "run unit test" + bash scripts/run-unit-test.sh +fi + +if [ ${TEST_TYPE} == ST ]; then + echo "run system test" + bash scripts/run-system-test.sh + bash scripts/travis-upload-test-report-to-gh-pages.sh $? +fi diff --git a/scripts/travis-upload-test-report-to-gh-pages.sh b/scripts/travis-upload-test-report-to-gh-pages.sh new file mode 100755 index 00000000..b5994664 --- /dev/null +++ b/scripts/travis-upload-test-report-to-gh-pages.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# This script is used to run on Travis CI to publish generated files to GitHub pages +# 1. Create a orphan branch named gh-pages: https://help.github.com/en/articles/creating-project-pages-using-the-command-line#create-a-master-branch +# 2. Enabling GitHub Pages to publish your site from gh-pages: https://help.github.com/en/articles/configuring-a-publishing-source-for-github-pages#enabling-github-pages-to-publish-your-site-from-master-or-gh-pages + +# NOTES: all UPPER-CASE variables are ENV variables, lower-case variables are local defined variables + +echo "Maven test result code :"$1 +MAVEN_TEST_RESULT=$1 + +echo "Starting to update gh-pages" +# gh page info +owner_name=`echo $TRAVIS_REPO_SLUG|cut -d / -f 1` +repo_name=`echo $TRAVIS_REPO_SLUG|cut -d / -f 2` +gh_pages_url="https://cryptape.github.io/cita-sdk-java/" +test_report_url="$gh_pages_url/reports/${TRAVIS_JOB_ID}/" + +test_result_mark="×" +if [ ${MAVEN_TEST_RESULT} -eq 0 ]; then + test_result_mark="✔" +fi + +# go to home +cd $HOME + +# using token clone gh-pages branch +git clone --quiet --branch=gh-pages ${TEST_REPORT_CODE_URL} gh-pages > /dev/null + +#go into diractory and copy data we're interested in to that directory +cd gh-pages +mkdir -p reports + +# TODO: delete outdated reports +# add new report +mv $HOME/tmp/${TRAVIS_JOB_ID} reports/ +ls -l reports/${TRAVIS_JOB_ID} + +# update index.html +echo "" >> index.html +# setup git user +git config user.email "travis@travis-ci.org" +git config user.name "Travis CI" + +# add, commit and push files +commit_message="Test report $test_report_url for CI build $travis_build_url" +git add -f . +git commit -m "$commit_message" +git push -fq origin gh-pages > /dev/null +echo "Test report uploaded to $test_report_url" + +# return maven test result +exit ${MAVEN_TEST_RESULT} + From 584822fac36b53219525bf9b488018bc4159bc05 Mon Sep 17 00:00:00 2001 From: chenhao Date: Mon, 23 Sep 2019 15:50:56 +0800 Subject: [PATCH 4/9] fix unit test cases --- .travis.yml | 3 - scripts/run-unit-test.sh | 33 +- tests/build.gradle | 3 + .../java/com/cryptape/cita/tests/RpcTest.java | 331 ------------------ .../cita/tests/AdvanceTransactionTest.java | 38 +- .../cita/tests/BlockFilterFlowableTest.java} | 8 +- .../tests/BlockFilterTransactionTest.java} | 20 +- .../java/com/cryptape/cita/tests/Config.java | 11 +- .../cryptape/cita/tests/DecodeTxTest.java} | 23 +- .../cita/tests/GroupManagerTest.java} | 22 +- .../cita/tests/PermissionManagerTest.java} | 35 +- .../cita/tests/QuotaManagerTest.java} | 25 +- .../java/com/cryptape/cita/tests/RpcTest.java | 286 +++++++++++++++ .../cita/tests/SM2ValidationTest.java | 6 +- .../cita/tests/SendTransactionSyncTest.java} | 70 ++-- .../cita/tests/SendTransactionTest.java} | 50 ++- .../cryptape/cita/tests/SimpleDataTest.java} | 47 ++- .../cryptape/cita/tests/StoreRecordTest.java} | 25 +- .../cita/tests/SystemContractTest.java} | 29 +- .../com/cryptape/cita/tests/TestUtil.java | 15 +- .../java/com/cryptape/cita/tests/Token.java | 0 .../cita/tests/TokenAccountTest.java} | 32 +- .../cita/tests/TokenCodegenTest.java} | 42 +-- .../cita/tests/TokenFilterCodeGenTest.java} | 69 ++-- .../cita/tests/TokenFilterFlowableTest.java} | 44 +-- .../tests/TokenFilterTransactionTest.java} | 34 +- .../cita/tests/TokenTransactionTest.java} | 32 +- .../cita/tests/VerifySignatureTest.java} | 18 +- .../src/{main => test}/resources/Advance.abi | 0 .../src/{main => test}/resources/Advance.bin | 0 .../src/{main => test}/resources/Advance.sol | 0 .../src/{main => test}/resources/SafeMath.sol | 0 .../{main => test}/resources/SimpleData.abi | 0 .../{main => test}/resources/SimpleData.bin | 0 .../{main => test}/resources/SimpleData.sol | 0 tests/src/{main => test}/resources/Token.abi | 0 tests/src/{main => test}/resources/Token.bin | 0 tests/src/{main => test}/resources/Token.sol | 0 .../src/{main => test}/resources/config.json | 0 .../resources/config.properties.example | 8 +- 40 files changed, 715 insertions(+), 644 deletions(-) delete mode 100644 tests/src/main/java/com/cryptape/cita/tests/RpcTest.java rename tests/src/{main => test}/java/com/cryptape/cita/tests/AdvanceTransactionTest.java (95%) rename tests/src/{main/java/com/cryptape/cita/tests/BlockFilterFlowableExample.java => test/java/com/cryptape/cita/tests/BlockFilterFlowableTest.java} (73%) rename tests/src/{main/java/com/cryptape/cita/tests/BlockFilterTransactionExample.java => test/java/com/cryptape/cita/tests/BlockFilterTransactionTest.java} (72%) rename tests/src/{main => test}/java/com/cryptape/cita/tests/Config.java (96%) rename tests/src/{main/java/com/cryptape/cita/tests/DecodeTxExample.java => test/java/com/cryptape/cita/tests/DecodeTxTest.java} (83%) rename tests/src/{main/java/com/cryptape/cita/tests/GroupManagerExample.java => test/java/com/cryptape/cita/tests/GroupManagerTest.java} (85%) rename tests/src/{main/java/com/cryptape/cita/tests/PermissionManagerExample.java => test/java/com/cryptape/cita/tests/PermissionManagerTest.java} (76%) rename tests/src/{main/java/com/cryptape/cita/tests/QuotaManagerExample.java => test/java/com/cryptape/cita/tests/QuotaManagerTest.java} (80%) create mode 100644 tests/src/test/java/com/cryptape/cita/tests/RpcTest.java rename tests/src/{main => test}/java/com/cryptape/cita/tests/SM2ValidationTest.java (98%) rename tests/src/{main/java/com/cryptape/cita/tests/SendTransactionSyncExample.java => test/java/com/cryptape/cita/tests/SendTransactionSyncTest.java} (52%) rename tests/src/{main/java/com/cryptape/cita/tests/SendTransactionAsyncExample.java => test/java/com/cryptape/cita/tests/SendTransactionTest.java} (72%) rename tests/src/{main/java/com/cryptape/cita/tests/SimpleDataExample.java => test/java/com/cryptape/cita/tests/SimpleDataTest.java} (92%) rename tests/src/{main/java/com/cryptape/cita/tests/StoreRecordExample.java => test/java/com/cryptape/cita/tests/StoreRecordTest.java} (85%) rename tests/src/{main/java/com/cryptape/cita/tests/SystemContractExample.java => test/java/com/cryptape/cita/tests/SystemContractTest.java} (72%) rename tests/src/{main => test}/java/com/cryptape/cita/tests/TestUtil.java (95%) rename tests/src/{main => test}/java/com/cryptape/cita/tests/Token.java (100%) rename tests/src/{main/java/com/cryptape/cita/tests/TokenAccountExample.java => test/java/com/cryptape/cita/tests/TokenAccountTest.java} (93%) rename tests/src/{main/java/com/cryptape/cita/tests/TokenCodegenExample.java => test/java/com/cryptape/cita/tests/TokenCodegenTest.java} (94%) rename tests/src/{main/java/com/cryptape/cita/tests/TokenFilterCodeGenExample.java => test/java/com/cryptape/cita/tests/TokenFilterCodeGenTest.java} (78%) rename tests/src/{main/java/com/cryptape/cita/tests/TokenFilterFlowableExample.java => test/java/com/cryptape/cita/tests/TokenFilterFlowableTest.java} (96%) rename tests/src/{main/java/com/cryptape/cita/tests/TokenFilterTransactionExample.java => test/java/com/cryptape/cita/tests/TokenFilterTransactionTest.java} (97%) rename tests/src/{main/java/com/cryptape/cita/tests/TokenTransactionExample.java => test/java/com/cryptape/cita/tests/TokenTransactionTest.java} (93%) rename tests/src/{main/java/com/cryptape/cita/tests/VerifySignatureExample.java => test/java/com/cryptape/cita/tests/VerifySignatureTest.java} (91%) rename tests/src/{main => test}/resources/Advance.abi (100%) rename tests/src/{main => test}/resources/Advance.bin (100%) rename tests/src/{main => test}/resources/Advance.sol (100%) rename tests/src/{main => test}/resources/SafeMath.sol (100%) rename tests/src/{main => test}/resources/SimpleData.abi (100%) rename tests/src/{main => test}/resources/SimpleData.bin (100%) rename tests/src/{main => test}/resources/SimpleData.sol (100%) rename tests/src/{main => test}/resources/Token.abi (100%) rename tests/src/{main => test}/resources/Token.bin (100%) rename tests/src/{main => test}/resources/Token.sol (100%) rename tests/src/{main => test}/resources/config.json (100%) rename tests/src/{main => test}/resources/config.properties.example (79%) diff --git a/.travis.yml b/.travis.yml index 4dc2bf75..c70c2666 100644 --- a/.travis.yml +++ b/.travis.yml @@ -32,6 +32,3 @@ before_script: script: bash ./scripts/run.sh -## Upload code coverage metrics -#after_success: -# - bash <(curl -s https://codecov.io/bash) diff --git a/scripts/run-unit-test.sh b/scripts/run-unit-test.sh index 8e1119f9..b7601ded 100644 --- a/scripts/run-unit-test.sh +++ b/scripts/run-unit-test.sh @@ -1,4 +1,33 @@ #!/usr/bin/env bash -../gradlew --info check jacocoRootTestReport -bash <(curl -s https://codecov.io/bash) \ No newline at end of file +# start a CITA chain for running tests, and init config +OLD_ADMIN_PRIVATE_KEY=0x5a0257a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6 +OLD_ADMIN_ADDRESS=0x827b05e4b070167a360e123fd06566eeb1a79fa5 +TEST_ADMIN_PRIVATE_KEY=0x5f0258a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6 +TEST_ADMIN_ADDRESS=0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523 +docker pull ${DOCKER_IMAGE_URL}:sha3 +docker run --rm -d -p 60702:1337 --name=test_sdk_cita ${DOCKER_IMAGE_URL}:sha3 +sleep 2m +docker ps +sed -i "s/:1337/:60702/" ./tests/src/test/resources/config.properties.example +sed -i "s/${OLD_ADMIN_ADDRESS}/${TEST_ADMIN_ADDRESS}/" ./tests/src/test/resources/config.properties.example +sed -i "s/${OLD_ADMIN_PRIVATE_KEY}/${TEST_ADMIN_PRIVATE_KEY}/" ./tests/src/test/resources/config.properties.example +cp -r ./tests/src/test/resources/config.properties.example ./tests/src/test/resources/config.properties +cat ./tests/src/test/resources/config.properties + +# run unit and integration tests +./gradlew --info check jacocoRootTestReport +UNIT_TEST_RESULT=$? +echo "UNIT_TEST_RESULT:${UNIT_TEST_RESULT}" + +# if success, upload code coverage metrics +if [ ${UNIT_TEST_RESULT} -eq 0 ]; then + echo "Upload code coverage metrics" + bash <(curl -s https://codecov.io/bash) +fi + +# remove docker container +docker rm -f test_sdk_cita + +# exit UNIT TEST CODE +exit ${UNIT_TEST_RESULT} \ No newline at end of file diff --git a/tests/build.gradle b/tests/build.gradle index b2f884a7..9211b986 100644 --- a/tests/build.gradle +++ b/tests/build.gradle @@ -1,6 +1,9 @@ description 'Several examples to use cita-sdk-java to interact with CITA' dependencies { + + testCompile group: 'com.alibaba', name: 'fastjson', version: '1.2.60' + testCompile group: 'org.hamcrest', name: 'hamcrest-core', version: '2.1' compile group: 'commons-codec', name: 'commons-codec', version: '1.11' compile project(':core'), "com.google.code.gson:gson:$gsonVersion" diff --git a/tests/src/main/java/com/cryptape/cita/tests/RpcTest.java b/tests/src/main/java/com/cryptape/cita/tests/RpcTest.java deleted file mode 100644 index 011df252..00000000 --- a/tests/src/main/java/com/cryptape/cita/tests/RpcTest.java +++ /dev/null @@ -1,331 +0,0 @@ -package com.cryptape.cita.tests; - -import java.io.IOException; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.Map; -import java.util.Set; - -import com.cryptape.cita.abi.FunctionEncoder; -import com.cryptape.cita.abi.TypeReference; -import com.cryptape.cita.abi.datatypes.Address; -import com.cryptape.cita.abi.datatypes.Function; -import com.cryptape.cita.abi.datatypes.Uint; -import com.cryptape.cita.crypto.Credentials; -import com.cryptape.cita.protocol.CITAj; -import com.cryptape.cita.protocol.core.DefaultBlockParameter; -import com.cryptape.cita.protocol.core.DefaultBlockParameterName; -import com.cryptape.cita.protocol.core.methods.request.Call; -import com.cryptape.cita.protocol.core.methods.request.Transaction; -import com.cryptape.cita.protocol.core.methods.response.*; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.Gson; - -public class RpcTest { - - private static int version; - private static BigInteger chainId; - private static CITAj service; - private static String value; - private static String privateKey; - private static long quotaToDeploy; - private static Transaction.CryptoTx cryptoTx; - - - static { - Config conf = new Config(); - conf.buildService(true); - service = conf.service; - privateKey = conf.primaryPrivKey; - quotaToDeploy = Long.parseLong(conf.defaultQuotaDeployment); - value = "0"; - version = TestUtil.getVersion(service); - chainId = TestUtil.getChainId(service); - cryptoTx = Transaction.CryptoTx.valueOf(conf.cryptoTx); - } - - public static void main(String[] args) throws Exception { - - testNetPeerCount(); - - testNetPeersInfo(); - - testGetVersion(); - - testGetBlockByNumber(BigInteger.valueOf(47)); - - testGetBalance(); - - testMetaData(); - - BigInteger validBlockNumber = testBlockNumber(); - - System.out.println(validBlockNumber.toString(10)); - - String blockByNumberHash = testAppGetBlockByNumber( - validBlockNumber, true); - - testAppGetBlockByHash(blockByNumberHash, true); - - //because unsigned transaction is not supported in cita, there is no method sendTransaction. - String code = "6060604052341561000f57600080fd5b600160a060020" - + "a033316600090815260208190526040902061271090556101" - + "df8061003b6000396000f3006060604052600436106100565" - + "763ffffffff7c010000000000000000000000000000000000" - + "000000000000000000000060003504166327e235e38114610" - + "05b578063a9059cbb1461008c578063f8b2cb4f146100c257" - + "5b600080fd5b341561006657600080fd5b61007a600160a06" - + "0020a03600435166100e1565b604051908152602001604051" - + "80910390f35b341561009757600080fd5b6100ae600160a06" - + "0020a03600435166024356100f3565b604051901515815260" - + "200160405180910390f35b34156100cd57600080fd5b61007" - + "a600160a060020a0360043516610198565b60006020819052" - + "908152604090205481565b600160a060020a0333166000908" - + "1526020819052604081205482901080159061011c57506000" - + "82115b1561018e57600160a060020a0333811660008181526" - + "0208190526040808220805487900390559286168082529083" - + "9020805486019055917fddf252ad1be2c89b69c2b068fc378" - + "daa952ba7f163c4a11628f55a4df523b3ef90859051908152" - + "60200160405180910390a3506001610192565b5060005b929" - + "15050565b600160a060020a03166000908152602081905260" - + "40902054905600a165627a7a72305820f59b7130870eee8f0" - + "44b129f4a20345ffaff662707fc0758133cd16684bc3b160029"; - - String nonce = TestUtil.getNonce(); - BigInteger validUtil = TestUtil.getValidUtilBlock(service); - - Transaction rtx = Transaction.createContractTransaction( - nonce, quotaToDeploy, validUtil.longValue(), - version, chainId, value, code); - String signedTransaction = rtx.sign(privateKey, cryptoTx, false); - String transactionHash = testAppSendRawTransaction(signedTransaction); - - System.out.println("waiting for tx into chain ..."); - Thread.sleep(8000); - - testAppGetTransactionByHash(transactionHash); - - Credentials credentials = Credentials.create(privateKey); - String validAccount = credentials.getAddress(); - testAppGetTransactionCount(validAccount, DefaultBlockParameterName.PENDING); - - String validContractAddress = ""; - String contractAddr = testAppGetTransactionReceipt(transactionHash); - if (contractAddr != null) { - validContractAddress = contractAddr; - } else { - System.out.println("Failed to get address from tx receipt"); - System.exit(1); - } - - testAppGetCode(validContractAddress, DefaultBlockParameterName.PENDING); - - String fromAddress = Credentials.create(privateKey).getAddress(); - Function getBalanceFunc = new Function( - "getBalance", - Arrays.asList(new Address(fromAddress)), - Arrays.asList(new TypeReference() { - }) - ); - String funcCallData = FunctionEncoder.encode(getBalanceFunc); - - testAppCall(fromAddress, validContractAddress, funcCallData, DefaultBlockParameterName.PENDING); - } - - - private static void testGetBlockByNumber(BigInteger number) throws IOException { - AppBlock.Block block = service.appGetBlockByNumber(DefaultBlockParameter.valueOf(number), false).send().getBlock(); - System.out.println("block " + number.toString() + " is: " + new Gson().toJson(block)); - } - - private static void testGetBalance() throws Exception { - Credentials c = Credentials.create(privateKey); - String addr = c.getAddress(); - AppGetBalance appGetbalance = service.appGetBalance( - addr, DefaultBlockParameterName.PENDING).send(); - if (appGetbalance == null) { - System.out.println("the result is null"); - } else { - BigInteger balance = appGetbalance.getBalance(); - System.out.println("Balance for address " + addr + "is " + balance); - } - } - - private static void testMetaData() throws Exception { - AppMetaData appMetaData = service.appMetaData(DefaultBlockParameterName.PENDING).send(); - System.out.println("AppMetaData: " + new Gson().toJson(appMetaData)); - } - - private static void testNetPeerCount() throws Exception { - NetPeerCount netPeerCount = service.netPeerCount().send(); - System.out.println("net_peerCount:" + netPeerCount.getQuantity()); - } - - private static void testNetPeersInfo() throws Exception { - NetPeersInfo netPeersInfo = service.netPeersInfo().send(); - Map peers = netPeersInfo.getPeersInfo().peers; - System.out.println("net_peersInfo amount:" + netPeersInfo.getPeersInfo().amount); - for (Map.Entry entry : peers.entrySet()) { - System.out.println("Address : " + entry.getKey() + " Node : " + entry.getValue()); - } - } - - private static void testGetVersion() throws Exception { - AppVersion appVersion = service.getVersion().send(); - System.out.println("version:" + appVersion.getVersion().softwareVersion); - } - - private static BigInteger testBlockNumber() throws Exception { - - AppBlockNumber appBlockNumber = service.appBlockNumber().send(); - - BigInteger validBlockNumber = BigInteger.valueOf(Long.MAX_VALUE); - - if (appBlockNumber.isEmpty()) { - System.out.println("the result is null"); - } else { - validBlockNumber = appBlockNumber.getBlockNumber(); - System.out.println("blockNumber:" + validBlockNumber); - } - return validBlockNumber; - } - - private static String testAppGetBlockByNumber( - BigInteger validBlockNumber, boolean isfullTranobj) - throws Exception { - AppBlock appBlock = service.appGetBlockByNumber( - DefaultBlockParameter.valueOf(validBlockNumber), isfullTranobj).send(); - - if (appBlock.isEmpty()) { - System.out.println("the result is null"); - return null; - } else { - AppBlock.Block block = appBlock.getBlock(); - System.out.println("Block: " + new Gson().toJson(block)); - return block.getHash(); - } - } - - private static void testAppGetBlockByHash( - String validBlockHash, boolean isfullTran) - throws Exception { - AppBlock appBlock = service - .appGetBlockByHash(validBlockHash, isfullTran).send(); - - if (appBlock.isEmpty()) { - System.out.println("the result is null"); - } else { - AppBlock.Block block = appBlock.getBlock(); - System.out.println("Block: " + new Gson().toJson(block)); - } - } - - - private static String testAppSendRawTransaction( - String rawData) throws Exception { - AppSendTransaction appSendTx = service - .appSendRawTransaction(rawData).send(); - - if (appSendTx.isEmpty()) { - System.out.println("the result is null"); - return null; - } else { - String hash = appSendTx.getSendTransactionResult().getHash(); - System.out.println("hash(Transaction):" + hash); - System.out.println("status:" - + appSendTx.getSendTransactionResult().getStatus()); - return hash; - } - } - - - private static void testAppGetTransactionByHash( - String validTransactionHash) throws Exception { - AppTransaction appTransaction = service.appGetTransactionByHash( - validTransactionHash).send(); - - if (appTransaction.getTransaction() == null) { - System.out.println("the result is null"); - } else { - com.cryptape.cita.protocol.core.methods.response.Transaction transaction - = appTransaction.getTransaction(); - System.out.println("Transaction: " + new Gson().toJson(transaction)); - } - } - - - private static void testAppGetTransactionCount( - String validAccount, DefaultBlockParameter param) throws Exception { - AppGetTransactionCount appGetTransactionCount = service.appGetTransactionCount( - validAccount, param).send(); - - if (appGetTransactionCount.isEmpty()) { - System.out.println("the result is null"); - } else { - System.out.println("TransactionCount:" - + appGetTransactionCount.getTransactionCount()); - } - } - - private static String testAppGetTransactionReceipt( - String validTransactionHash) throws Exception { - AppGetTransactionReceipt appGetTransactionReceipt = service.appGetTransactionReceipt( - validTransactionHash).send(); - - if (appGetTransactionReceipt.getTransactionReceipt() == null) { - System.out.println("the result is null"); - return null; - } else { - //is option_value is null return NoSuchElementException, else return option_value - TransactionReceipt transactionReceipt = - appGetTransactionReceipt.getTransactionReceipt(); - printTransactionReceiptInfo(transactionReceipt); - if (transactionReceipt.getErrorMessage() != null) { - System.out.println("Transaction failed."); - System.out.println("Error Message: " + transactionReceipt.getErrorMessage()); - System.exit(1); - } - return transactionReceipt.getContractAddress(); - } - - } - - private static void printTransactionReceiptInfo( - TransactionReceipt transactionReceipt) { - try { - ObjectMapper mapper = new ObjectMapper(); - String result = mapper.writeValueAsString(transactionReceipt); - System.out.println(result); - } catch (JsonProcessingException e) { - System.out.println("Failed to process object to json. Exception: " + e); - e.printStackTrace(); - System.exit(1); - } - } - - private static void testAppGetCode( - String validContractAddress, DefaultBlockParameter param) - throws Exception { - AppGetCode appGetCode = service - .appGetCode(validContractAddress, param).send(); - - if (appGetCode.isEmpty()) { - System.out.println("the result is null"); - } else { - System.out.println("contract code:" + appGetCode.getCode()); - } - } - - - private static void testAppCall( - String fromAddress, String contractAddress, String encodedFunction, - DefaultBlockParameter param) throws Exception { - AppCall appCall = service.appCall( - new Call(fromAddress, contractAddress, encodedFunction), - param).send(); - - System.out.println("call result:" + appCall.getValue()); - } - -} diff --git a/tests/src/main/java/com/cryptape/cita/tests/AdvanceTransactionTest.java b/tests/src/test/java/com/cryptape/cita/tests/AdvanceTransactionTest.java similarity index 95% rename from tests/src/main/java/com/cryptape/cita/tests/AdvanceTransactionTest.java rename to tests/src/test/java/com/cryptape/cita/tests/AdvanceTransactionTest.java index 4d2c6e71..d6024429 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/AdvanceTransactionTest.java +++ b/tests/src/test/java/com/cryptape/cita/tests/AdvanceTransactionTest.java @@ -1,11 +1,5 @@ package com.cryptape.cita.tests; -import java.math.BigInteger; -import java.text.DecimalFormat; -import java.util.Arrays; -import java.util.Collections; -import java.util.Random; - import com.cryptape.cita.abi.FunctionEncoder; import com.cryptape.cita.abi.FunctionReturnDecoder; import com.cryptape.cita.abi.TypeReference; @@ -16,6 +10,12 @@ import com.cryptape.cita.protocol.core.methods.request.Call; import com.cryptape.cita.protocol.core.methods.request.Transaction; import com.cryptape.cita.protocol.core.methods.response.TransactionReceipt; +import java.math.BigInteger; +import java.text.DecimalFormat; +import java.util.Arrays; +import java.util.Collections; +import java.util.Random; +import org.junit.Test; public class AdvanceTransactionTest { @@ -31,7 +31,7 @@ public class AdvanceTransactionTest { Config conf = new Config(); conf.buildService(false); service = conf.service; - senderPrivateKey = conf.primaryPrivKey; + senderPrivateKey = conf.adminPrivateKey; version = TestUtil.getVersion(service); chainId = TestUtil.getChainId(service); quota = Long.parseLong(conf.defaultQuotaDeployment); @@ -46,7 +46,7 @@ public class AdvanceTransactionTest { private String contractAddress; - public AdvanceTransactionTest(int sdCount, int thdCount, boolean isEd25519AndBlake2b) { + public void initAdvanceTransactionTest(int sdCount, int thdCount, boolean isEd25519AndBlake2b) { try { random = new Random(System.currentTimeMillis()); this.validUntilBlock = TestUtil.getValidUtilBlock(service, 100).longValue(); @@ -56,7 +56,7 @@ public AdvanceTransactionTest(int sdCount, int thdCount, boolean isEd25519AndBla System.out.println("Initial block height: " + TestUtil.getCurrentHeight(service)); } catch (Exception e) { e.printStackTrace(); - System.exit(1); + //System.exit(1); } } @@ -191,14 +191,14 @@ public void runContract() throws Exception { } else { System.out.println("Failed to deploy smart contract. Error: " + receipt.getErrorMessage()); - System.exit(1); + //System.exit(1); } } else { System.out.println("Waiting for contract deployment...."); Thread.sleep(3000); if (countForContractDeployment++ > 3) { System.out.println("Timeout, failed to deploy contract."); - System.exit(1); + //System.exit(1); } } } @@ -217,14 +217,14 @@ public void runContract() throws Exception { break; } else { System.out.println("Failed to reset count."); - System.exit(1); + //System.exit(1); } } else { System.out.println("Waiting to reset count...."); Thread.sleep(3000); if (countForResetFunctionCall++ > 3) { System.out.println("Timeout, failed to reset count."); - System.exit(1); + //System.exit(1); } } } @@ -247,7 +247,7 @@ public void runContract() throws Exception { } catch (Exception e) { System.out.println("Failed to call contract function."); e.printStackTrace(); - System.exit(1); + //System.exit(1); } }); t.start(); @@ -308,7 +308,9 @@ public void runContract() throws Exception { System.out.println(outStr); } - public static void main(String[] args) throws Exception { + @Test + public void testAdvanceTransaction() throws Exception { + int sendcount = 20; int threadcount = 1; boolean isEd25519AndBlake2b = false; @@ -316,9 +318,9 @@ public static void main(String[] args) throws Exception { System.out.println( "sendCount: " + sendcount + " threadCount: " + threadcount + " isEd25519AndBlake2b: " + isEd25519AndBlake2b); - AdvanceTransactionTest advanceTxTest = new AdvanceTransactionTest( - sendcount, threadcount, isEd25519AndBlake2b); - advanceTxTest.runContract(); + initAdvanceTransactionTest(sendcount, threadcount, isEd25519AndBlake2b); + runContract(); System.out.println("Performance - test case complete"); } + } diff --git a/tests/src/main/java/com/cryptape/cita/tests/BlockFilterFlowableExample.java b/tests/src/test/java/com/cryptape/cita/tests/BlockFilterFlowableTest.java similarity index 73% rename from tests/src/main/java/com/cryptape/cita/tests/BlockFilterFlowableExample.java rename to tests/src/test/java/com/cryptape/cita/tests/BlockFilterFlowableTest.java index ed4afbb0..70121ecc 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/BlockFilterFlowableExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/BlockFilterFlowableTest.java @@ -2,9 +2,10 @@ import com.cryptape.cita.protocol.CITAj; import io.reactivex.Flowable; +import org.junit.Test; -public class BlockFilterFlowableExample { - private static CITAj service; +public class BlockFilterFlowableTest { + public static CITAj service; static { Config conf = new Config(); @@ -12,7 +13,8 @@ public class BlockFilterFlowableExample { service = conf.service; } - public static void main(String[] args) { + @Test + public void testBlockFilterFlowable( ) { Flowable blockFitlerFlowable = service.appBlockHashFlowable(); blockFitlerFlowable.subscribe(block -> System.out.println(block.toString()) diff --git a/tests/src/main/java/com/cryptape/cita/tests/BlockFilterTransactionExample.java b/tests/src/test/java/com/cryptape/cita/tests/BlockFilterTransactionTest.java similarity index 72% rename from tests/src/main/java/com/cryptape/cita/tests/BlockFilterTransactionExample.java rename to tests/src/test/java/com/cryptape/cita/tests/BlockFilterTransactionTest.java index e2fa933e..9b98ecd4 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/BlockFilterTransactionExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/BlockFilterTransactionTest.java @@ -1,17 +1,21 @@ package com.cryptape.cita.tests; -import java.io.IOException; -import java.math.BigInteger; -import java.util.List; -import java.util.concurrent.TimeUnit; +import static junit.framework.TestCase.assertNotNull; +import static junit.framework.TestCase.assertNull; +import static junit.framework.TestCase.assertTrue; import com.cryptape.cita.protocol.CITAj; import com.cryptape.cita.protocol.core.Request; import com.cryptape.cita.protocol.core.methods.response.AppBlock; import com.cryptape.cita.protocol.core.methods.response.AppFilter; import com.cryptape.cita.protocol.core.methods.response.AppLog; +import java.io.IOException; +import java.math.BigInteger; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.junit.Test; -public class BlockFilterTransactionExample { +public class BlockFilterTransactionTest { private static CITAj service; static { @@ -20,7 +24,8 @@ public class BlockFilterTransactionExample { service = conf.service; } - public static void main(String[] args) throws IOException, InterruptedException { + @Test + public void testBlockFilterTransaction( ) throws IOException, InterruptedException { Request request = service.appNewBlockFilter(); AppFilter appFilter = request.send(); BigInteger filterId = appFilter.getFilterId(); @@ -38,6 +43,9 @@ public static void main(String[] args) throws IOException, InterruptedException Object s = logResult.get(); System.out.println("Block Hash" + s.toString()); AppBlock block = service.appGetBlockByHash(s.toString(), true).send(); + assertNull(block.getError()); + assertNotNull(block.getBlock().getHeader().getNumber()); + assertTrue(block.getBlock().getHash().equals(s.toString())); System.out.println("Block number: " + block.getBlock().getHeader().getNumber() + "\n"); } } diff --git a/tests/src/main/java/com/cryptape/cita/tests/Config.java b/tests/src/test/java/com/cryptape/cita/tests/Config.java similarity index 96% rename from tests/src/main/java/com/cryptape/cita/tests/Config.java rename to tests/src/test/java/com/cryptape/cita/tests/Config.java index 59b135c9..781a6a09 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/Config.java +++ b/tests/src/test/java/com/cryptape/cita/tests/Config.java @@ -1,14 +1,13 @@ package com.cryptape.cita.tests; -import java.io.FileInputStream; -import java.util.Properties; - import com.cryptape.cita.protocol.CITAj; import com.cryptape.cita.protocol.http.HttpService; +import java.io.FileInputStream; +import java.util.Properties; public class Config { - private static final String configPath = "tests/src/main/resources/config.properties"; + private static final String configPath = "src/test/resources/config.properties"; private static final String CHAIN_ID = "ChainId"; private static final String VERSION = "Version"; private static final String TEST_NET_ADDR = "TestNetIpAddr"; @@ -72,7 +71,7 @@ public static Properties load(String path) { props.load(new FileInputStream(path)); } catch (Exception e) { System.out.println("Failed to read config at path " + path); - System.exit(1); + //System.exit(1); } return props; } @@ -84,7 +83,7 @@ public static Properties load() { } catch (Exception e) { System.out.println("Failed to read config file. Error: " + e); e.printStackTrace(); - System.exit(1); + //System.exit(1); } return props; } diff --git a/tests/src/main/java/com/cryptape/cita/tests/DecodeTxExample.java b/tests/src/test/java/com/cryptape/cita/tests/DecodeTxTest.java similarity index 83% rename from tests/src/main/java/com/cryptape/cita/tests/DecodeTxExample.java rename to tests/src/test/java/com/cryptape/cita/tests/DecodeTxTest.java index 95958024..ea910d8d 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/DecodeTxExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/DecodeTxTest.java @@ -1,22 +1,25 @@ package com.cryptape.cita.tests; import static com.cryptape.cita.utils.Numeric.decodeQuantity; +import static junit.framework.TestCase.assertTrue; +import static org.hamcrest.MatcherAssert.assertThat; -import java.io.IOException; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; - +import com.alibaba.fastjson.JSONObject; import com.cryptape.cita.protobuf.ConvertStrByte; import com.cryptape.cita.protocol.CITAj; import com.cryptape.cita.protocol.core.methods.request.Transaction; import com.cryptape.cita.protocol.core.methods.response.AppTransaction; import com.google.gson.Gson; +import java.io.IOException; +import java.math.BigInteger; +import java.util.concurrent.TimeUnit; +import org.junit.Test; /* * This example shows how to decode transaction info from response. * */ -public class DecodeTxExample { +public class DecodeTxTest { private static int version; private static BigInteger chainId; private static CITAj service; @@ -29,7 +32,7 @@ public class DecodeTxExample { Config conf = new Config(); conf.buildService(false); service = conf.service; - privateKey = conf.primaryPrivKey; + privateKey = conf.adminPrivateKey; chainId = new BigInteger(conf.chainId); payeeAddr = conf.auxAddr1; quotaToDeploy = Long.parseLong(conf.defaultQuotaDeployment); @@ -51,7 +54,8 @@ private static String createSampleTransaction() throws IOException { return service.appSendRawTransaction(rawTx).send().getSendTransactionResult().getHash(); } - public static void main(String[] args) throws Exception { + @Test + public void testDecodeTx( ) throws Exception { //create a sample transaction String hash = createSampleTransaction(); System.out.println("Hash of the transaction: " + hash); @@ -62,8 +66,9 @@ public static void main(String[] args) throws Exception { //get response transaction AppTransaction appTx = service.appGetTransactionByHash(hash).send(); - com.cryptape.cita.protocol.core.methods.response.Transaction tx - = appTx.getTransaction(); + com.cryptape.cita.protocol.core.methods.response.Transaction tx = appTx.getTransaction(); + JSONObject contendJson = JSONObject.parseObject(new Gson().toJson(tx.decodeContent())); + assertTrue(payeeAddr.equals("0x"+contendJson.getString("to"))); System.out.println(new Gson().toJson(tx.decodeContent())); } } diff --git a/tests/src/main/java/com/cryptape/cita/tests/GroupManagerExample.java b/tests/src/test/java/com/cryptape/cita/tests/GroupManagerTest.java similarity index 85% rename from tests/src/main/java/com/cryptape/cita/tests/GroupManagerExample.java rename to tests/src/test/java/com/cryptape/cita/tests/GroupManagerTest.java index b5c07f67..3afdc8b1 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/GroupManagerExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/GroupManagerTest.java @@ -1,23 +1,22 @@ package com.cryptape.cita.tests; -import com.cryptape.cita.protocol.core.methods.response.Log; -import com.cryptape.cita.protocol.system.CITASystemContract; -import com.cryptape.cita.protocol.system.CITAjSystemContract; +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.assertFalse; -import java.io.IOException; +import com.cryptape.cita.protocol.system.CITAjSystemContract; import java.math.BigInteger; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; +import org.junit.Test; /** * Group and Account Management * If you want to know more about the documentation, please click on the link below. * https://docs.citahub.com/zh-CN/cita/account-permission/account */ -public class GroupManagerExample extends SystemContractExample { +public class GroupManagerTest extends SystemContractTest { static String senderAddr; static String adminPrivateKey; static int version; @@ -32,13 +31,16 @@ public class GroupManagerExample extends SystemContractExample { version = TestUtil.getVersion(service); chainId = TestUtil.getChainId(service); } - public static void main(String[] args) throws Exception { + + @Test + public void testGroupManager( ) throws Exception { CITAjSystemContract sysContract = new CITAjSystemContract(service); // New group List addresses = new ArrayList<>(); addresses.add("0x1c6eebf136ee234caff3a95e0d9d22e40c9ac4ca"); String newGroupAddr = sysContract.newGroup("vlk1", addresses, adminPrivateKey, version, chainId); + assertFalse("".equals(newGroupAddr)); if ("".equals(newGroupAddr)) { System.out.println("New group failed!"); return; @@ -48,6 +50,7 @@ public static void main(String[] args) throws Exception { // Update group name boolean updated = sysContract.updateGroupName(newGroupAddr, "TokenNew", adminPrivateKey, version, chainId); + assertTrue(updated); System.out.println("Group updated: " + updated); TimeUnit.SECONDS.sleep(10); @@ -55,16 +58,19 @@ public static void main(String[] args) throws Exception { List addressNeedBeAdded = new ArrayList<>(); addressNeedBeAdded.add("0xbac68e5cb986ead0253e0632da1131a0a96efa18"); updated = sysContract.addAccounts(newGroupAddr, addressNeedBeAdded, adminPrivateKey, version, chainId); + assertTrue(updated); System.out.println("Account is added: " + updated); TimeUnit.SECONDS.sleep(10); // Delete accounts updated = sysContract.deleteAccounts(newGroupAddr, addressNeedBeAdded, adminPrivateKey, version, chainId); + assertTrue(updated); System.out.println("Account is deleted: " + updated); TimeUnit.SECONDS.sleep(10); // Check scope updated = sysContract.checkScope(newGroupAddr, adminPrivateKey, version, chainId); + assertTrue(updated); System.out.println("Check scope: " + updated); TimeUnit.SECONDS.sleep(10); @@ -75,10 +81,12 @@ public static void main(String[] args) throws Exception { System.out.println("Group address: " + s); } } + assertTrue(res.contains(newGroupAddr)); TimeUnit.SECONDS.sleep(10); // Delete group updated = sysContract.deleteGroup(newGroupAddr, adminPrivateKey, version, chainId); + assertTrue(updated); System.out.println("Group deleted: " + updated); TimeUnit.SECONDS.sleep(10); } diff --git a/tests/src/main/java/com/cryptape/cita/tests/PermissionManagerExample.java b/tests/src/test/java/com/cryptape/cita/tests/PermissionManagerTest.java similarity index 76% rename from tests/src/main/java/com/cryptape/cita/tests/PermissionManagerExample.java rename to tests/src/test/java/com/cryptape/cita/tests/PermissionManagerTest.java index 46ebf168..19663da6 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/PermissionManagerExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/PermissionManagerTest.java @@ -1,15 +1,20 @@ package com.cryptape.cita.tests; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.concurrent.TimeUnit; +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.assertFalse; +import com.cryptape.cita.abi.FunctionEncoder; +import com.cryptape.cita.abi.datatypes.Function; import com.cryptape.cita.protocol.CITAj; import com.cryptape.cita.protocol.system.CITAjSystemContract; import com.cryptape.cita.protocol.system.entities.QueryInfoResult; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.concurrent.TimeUnit; +import org.junit.Test; -public class PermissionManagerExample { +public class PermissionManagerTest { static CITAj service; static String senderAddr; static String adminPrivateKey; @@ -34,7 +39,13 @@ private static void printQueryInfo(QueryInfoResult result) { result.funcs.forEach(System.out::println); } - public static void main(String[] args) throws Exception { + public String getEncodeOfFunc(String funcName){ + Function func = new Function(funcName, Collections.emptyList(), Collections.emptyList()); + return FunctionEncoder.encode(func).substring(2); + } + + @Test + public void testPermissionManager( ) throws Exception { CITAjSystemContract sysContract = new CITAjSystemContract(service); @@ -43,29 +54,38 @@ public static void main(String[] args) throws Exception { ArrayList funcs = new ArrayList<>(Collections.singletonList("Token")); String newPermissionAddr = sysContract.newPermission( "somePermission1", addrs, funcs, adminPrivateKey, version, chainId); + assertTrue(newPermissionAddr.contains("0x")); + assertTrue(newPermissionAddr.length()==42); System.out.println("Address for new permission: " + newPermissionAddr); TimeUnit.SECONDS.sleep(10); boolean updated = sysContract.updatePermissionName(newPermissionAddr, "TokenNew", adminPrivateKey, version, chainId); + assertTrue(updated); System.out.println("Permission updated: " + updated); TimeUnit.SECONDS.sleep(10); //check if the permission updated QueryInfoResult queryInforesult = sysContract.queryInfo(senderAddr, newPermissionAddr); + String name = queryInforesult.name; + assertTrue(queryInforesult.name.contains("TokenNew")); printQueryInfo(queryInforesult); //add a new resource addrs = new ArrayList<>(Collections.singletonList(senderAddr)); funcs = new ArrayList<>(Collections.singletonList("Token1")); + String funcEncode = getEncodeOfFunc(funcs.get(0)); boolean addResource = sysContract.addResources(addrs, funcs, newPermissionAddr, adminPrivateKey, version, chainId); + assertTrue(addResource); System.out.println("Resource is added: " + addResource); TimeUnit.SECONDS.sleep(10); //check if the resources added queryInforesult = sysContract.queryInfo(senderAddr, newPermissionAddr); + assertTrue(queryInforesult.funcs.contains(funcEncode)); printQueryInfo(queryInforesult); boolean inPermission = sysContract.inPermission(senderAddr, newPermissionAddr, senderAddr, "Token1"); + assertTrue(inPermission); System.out.println("The resource is in permission: " + inPermission); @@ -73,15 +93,18 @@ public static void main(String[] args) throws Exception { addrs = new ArrayList<>(Collections.singletonList(senderAddr)); funcs = new ArrayList<>(Collections.singletonList("Token1")); boolean deleteResource = sysContract.deleteResources(addrs, funcs, newPermissionAddr, adminPrivateKey, version, chainId); + assertTrue(deleteResource); System.out.println("Resource is deleted: " + deleteResource); TimeUnit.SECONDS.sleep(10); //check if the resources deleted queryInforesult = sysContract.queryInfo(senderAddr, newPermissionAddr); + assertFalse(queryInforesult.funcs.contains(funcEncode)); printQueryInfo(queryInforesult); //delete permission boolean deleted = sysContract.deletePermission(newPermissionAddr, adminPrivateKey, version, chainId); + assertTrue(deleted); System.out.println("Permission deleted: " + deleted); } } diff --git a/tests/src/main/java/com/cryptape/cita/tests/QuotaManagerExample.java b/tests/src/test/java/com/cryptape/cita/tests/QuotaManagerTest.java similarity index 80% rename from tests/src/main/java/com/cryptape/cita/tests/QuotaManagerExample.java rename to tests/src/test/java/com/cryptape/cita/tests/QuotaManagerTest.java index 60c1fb36..d2f02fc1 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/QuotaManagerExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/QuotaManagerTest.java @@ -1,13 +1,15 @@ package com.cryptape.cita.tests; +import com.cryptape.cita.protocol.CITAj; +import com.cryptape.cita.protocol.system.CITAjSystemContract; import java.math.BigInteger; import java.util.List; import java.util.concurrent.TimeUnit; +import org.junit.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; -import com.cryptape.cita.protocol.CITAj; -import com.cryptape.cita.protocol.system.CITAjSystemContract; - -public class QuotaManagerExample { +public class QuotaManagerTest { static CITAj service; static String senderAddr; static String adminPriavteKey; @@ -24,19 +26,22 @@ public class QuotaManagerExample { chainId = TestUtil.getChainId(service); } - public static void main(String[] args) throws Exception { + @Test + public void testQuotaManager() throws Exception { CITAjSystemContract sysContract = new CITAjSystemContract(service); int bql = sysContract.getBql(senderAddr); System.out.println("BQL(Block quota limit): " + bql + ". default one should be 1073741824"); + int setBql = bql+1; boolean bqlSuccess = sysContract.setBql( - new BigInteger("1073741825"), adminPriavteKey, version, chainId); + new BigInteger(""+setBql), adminPriavteKey, version, chainId); System.out.println("Is Bql set: " + bqlSuccess); System.out.println("Wait 3 seconds for transaction from pending to latest"); TimeUnit.SECONDS.sleep(3); bql = sysContract.getBql(senderAddr); + assertThat(bql,equalTo(setBql)); System.out.println("BQL(Block quota limit): " + bql + ". default one should be 1073741824"); int defaultAql = sysContract.getDefaultAql(senderAddr); @@ -44,8 +49,9 @@ public static void main(String[] args) throws Exception { "Default AQL(Account quota limit): " + defaultAql + ". Default one should be 268435456"); + int setAql = defaultAql+1; boolean setDefaultAqlSucces = sysContract.setDefaultAql( - new BigInteger("268435456"), adminPriavteKey, version, chainId); + new BigInteger(""+setAql), adminPriavteKey, version, chainId); System.out.println("Is default Aql set: " + setDefaultAqlSucces); @@ -53,6 +59,7 @@ public static void main(String[] args) throws Exception { TimeUnit.SECONDS.sleep(5); defaultAql = sysContract.getDefaultAql(senderAddr); + assertThat(defaultAql,equalTo(setAql)); System.out.println( "Default AQL(Account quota limit): " + defaultAql + ". Default one should be 268435456"); @@ -60,14 +67,16 @@ public static void main(String[] args) throws Exception { int aql = sysContract.getAql(senderAddr, senderAddr); System.out.println("AQL(Account quota limit) for addr " + senderAddr + " is: " + aql); + setAql = aql+1; boolean setAqlSuccess = sysContract.setAql( - senderAddr, new BigInteger("1073741824"), adminPriavteKey, version, chainId); + senderAddr, new BigInteger(""+setAql), adminPriavteKey, version, chainId); System.out.println("Is aql set: " + setAqlSuccess); System.out.println("wait 5 seconds for status from pending to latest"); TimeUnit.SECONDS.sleep(5); aql = sysContract.getAql(senderAddr, senderAddr); + assertThat(aql,equalTo(setAql)); System.out.println("AQL(Account quota limit) for addr " + senderAddr + " is: " + aql); List accounts = sysContract.getAccounts(senderAddr); diff --git a/tests/src/test/java/com/cryptape/cita/tests/RpcTest.java b/tests/src/test/java/com/cryptape/cita/tests/RpcTest.java new file mode 100644 index 00000000..e693c729 --- /dev/null +++ b/tests/src/test/java/com/cryptape/cita/tests/RpcTest.java @@ -0,0 +1,286 @@ +package com.cryptape.cita.tests; + +import static junit.framework.TestCase.assertTrue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import com.cryptape.cita.abi.FunctionEncoder; +import com.cryptape.cita.abi.TypeReference; +import com.cryptape.cita.abi.datatypes.Address; +import com.cryptape.cita.abi.datatypes.Function; +import com.cryptape.cita.abi.datatypes.Uint; +import com.cryptape.cita.crypto.Credentials; +import com.cryptape.cita.protocol.CITAj; +import com.cryptape.cita.protocol.core.DefaultBlockParameter; +import com.cryptape.cita.protocol.core.DefaultBlockParameterName; +import com.cryptape.cita.protocol.core.methods.request.Call; +import com.cryptape.cita.protocol.core.methods.request.Transaction; +import com.cryptape.cita.protocol.core.methods.response.AppBlock; +import com.cryptape.cita.protocol.core.methods.response.AppBlockNumber; +import com.cryptape.cita.protocol.core.methods.response.AppCall; +import com.cryptape.cita.protocol.core.methods.response.AppGetBalance; +import com.cryptape.cita.protocol.core.methods.response.AppGetCode; +import com.cryptape.cita.protocol.core.methods.response.AppGetTransactionCount; +import com.cryptape.cita.protocol.core.methods.response.AppGetTransactionReceipt; +import com.cryptape.cita.protocol.core.methods.response.AppMetaData; +import com.cryptape.cita.protocol.core.methods.response.AppSendTransaction; +import com.cryptape.cita.protocol.core.methods.response.AppTransaction; +import com.cryptape.cita.protocol.core.methods.response.AppVersion; +import com.cryptape.cita.protocol.core.methods.response.NetPeerCount; +import com.cryptape.cita.protocol.core.methods.response.NetPeersInfo; +import com.cryptape.cita.protocol.core.methods.response.TransactionReceipt; +import com.cryptape.cita.utils.Convert; +import com.google.gson.Gson; +import java.io.IOException; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Map; +import org.junit.BeforeClass; +import org.junit.Test; + +public class RpcTest { + + private static int version; + private static BigInteger chainId; + private static CITAj service; + private static String value; + private static String privateKey; + private static String adminPrivateKey; + private static long quotaToDeploy; + private static Transaction.CryptoTx cryptoTx; + + + //because unsigned transaction is not supported in cita, there is no method sendTransaction. + String code = "6060604052341561000f57600080fd5b600160a060020" + + "a033316600090815260208190526040902061271090556101" + + "df8061003b6000396000f3006060604052600436106100565" + + "763ffffffff7c010000000000000000000000000000000000" + + "000000000000000000000060003504166327e235e38114610" + + "05b578063a9059cbb1461008c578063f8b2cb4f146100c257" + + "5b600080fd5b341561006657600080fd5b61007a600160a06" + + "0020a03600435166100e1565b604051908152602001604051" + + "80910390f35b341561009757600080fd5b6100ae600160a06" + + "0020a03600435166024356100f3565b604051901515815260" + + "200160405180910390f35b34156100cd57600080fd5b61007" + + "a600160a060020a0360043516610198565b60006020819052" + + "908152604090205481565b600160a060020a0333166000908" + + "1526020819052604081205482901080159061011c57506000" + + "82115b1561018e57600160a060020a0333811660008181526" + + "0208190526040808220805487900390559286168082529083" + + "9020805486019055917fddf252ad1be2c89b69c2b068fc378" + + "daa952ba7f163c4a11628f55a4df523b3ef90859051908152" + + "60200160405180910390a3506001610192565b5060005b929" + + "15050565b600160a060020a03166000908152602081905260" + + "40902054905600a165627a7a72305820f59b7130870eee8f0" + + "44b129f4a20345ffaff662707fc0758133cd16684bc3b160029"; + + static { + Config conf = new Config(); + conf.buildService(true); + service = conf.service; + privateKey = conf.primaryPrivKey; + adminPrivateKey = conf.adminPrivateKey; + quotaToDeploy = Long.parseLong(conf.defaultQuotaDeployment); + value = "0"; + version = TestUtil.getVersion(service); + chainId = TestUtil.getChainId(service); + cryptoTx = Transaction.CryptoTx.valueOf(conf.cryptoTx); + } + + @Test + public void testGetBlockByNumber() throws IOException { + BigInteger number = BigInteger.valueOf(4L); + AppBlock.Block block = service.appGetBlockByNumber(DefaultBlockParameter.valueOf(number), false).send().getBlock(); + assertNotNull(block.getHash()); + assertNotNull(block.getBody()); + System.out.println("block " + number.toString() + " is: " + new Gson().toJson(block)); + } + + @Test + public void testGetBalance() throws Exception { + Credentials c = Credentials.create(privateKey); + String addr = c.getAddress(); + AppGetBalance appGetbalance = service.appGetBalance( + addr, DefaultBlockParameterName.PENDING).send(); + assertNotNull(appGetbalance.getBalance()); + } + + @Test + public void testMetaData() throws Exception { + AppMetaData appMetaData = service.appMetaData(DefaultBlockParameterName.PENDING).send(); + assertNotNull(appMetaData.getAppMetaDataResult()); + System.out.println("AppMetaData: " + new Gson().toJson(appMetaData)); + } + + @Test + public void testNetPeerCount() throws Exception { + NetPeerCount netPeerCount = service.netPeerCount().send(); + assertNotNull(netPeerCount); + System.out.println("net_peerCount:" + netPeerCount.getQuantity()); + } + + @Test + public void testNetPeersInfo() throws Exception { + NetPeersInfo netPeersInfo = service.netPeersInfo().send(); + Map peers = netPeersInfo.getPeersInfo().peers; + System.out.println("net_peersInfo amount:" + netPeersInfo.getPeersInfo().amount); + for (Map.Entry entry : peers.entrySet()) { + assertNotNull(entry.getKey()); + assertNotNull(entry.getValue()); + System.out.println("Address : " + entry.getKey() + " Node : " + entry.getValue()); + } + } + + @Test + public void testGetVersion() throws Exception { + AppVersion appVersion = service.getVersion().send(); + + if(appVersion.getError().equals(null)){ + assertNotNull(appVersion.getVersion()); + }else { + assertTrue(appVersion.getError().getCode() == -32601); + } + } + + @Test + public void testBlockNumber() throws Exception { + AppBlockNumber appBlockNumber = service.appBlockNumber().send(); + BigInteger validBlockNumber = appBlockNumber.getBlockNumber(); + assertTrue(validBlockNumber.longValue()>0); + } + + @Test + public void testAppGetBlockByNumber() + throws Exception { + BigInteger validBlockNumber = BigInteger.valueOf(4L); + boolean isfullTranobj = true; + AppBlock appBlock = service.appGetBlockByNumber( + DefaultBlockParameter.valueOf(validBlockNumber), isfullTranobj).send(); + AppBlock.Block block = appBlock.getBlock(); + assertNotNull(block.getBody()); + } + + @Test + public void testAppGetBlockByHash() + throws Exception { + BigInteger validBlockNumber = BigInteger.valueOf(4L); + AppBlock appBlock = service.appGetBlockByNumber( + DefaultBlockParameter.valueOf(validBlockNumber), true).send(); + String validBlockHash = appBlock.getBlock().getHash(); + AppBlock appFindBlock = service + .appGetBlockByHash(validBlockHash, true).send(); + String appBlockResult = new Gson().toJson(appBlock.getResult().getBody()); + String appBlockFindResult = new Gson().toJson(appFindBlock.getResult().getBody()); + assertThat(appBlockFindResult, equalTo(appBlockResult)); + } + + public AppSendTransaction appSendRawTransaction() throws IOException { + String nonce = TestUtil.getNonce(); + BigInteger validUtil = TestUtil.getValidUtilBlock(service); + Transaction rtx = Transaction.createContractTransaction( + nonce, quotaToDeploy, validUtil.longValue(), + version, chainId, value, code); + String signedTransaction = rtx.sign(adminPrivateKey, cryptoTx, false); + AppSendTransaction appSendTx = service + .appSendRawTransaction(signedTransaction).send(); + return appSendTx; + } + + @Test + public void testAppSendRawTransaction( ) throws Exception { + AppSendTransaction appSendTx = appSendRawTransaction(); + String hash = appSendTx.getSendTransactionResult().getHash(); + String status = appSendTx.getSendTransactionResult().getStatus(); + assertNotNull(hash); + assertNotNull(status); + } + + @Test + public void testAppGetTransactionByHash( ) throws Exception { + AppSendTransaction appSendTx = appSendRawTransaction(); + String hash = appSendTx.getSendTransactionResult().getHash(); + Thread.sleep(8000); + AppTransaction appTransaction = service.appGetTransactionByHash( + hash).send(); + assertNotNull(appTransaction.getTransaction()); + assertNull(appTransaction.getError()); + } + + @Test + public void testAppGetTransactionCount() throws Exception { + Credentials credentials = Credentials.create(privateKey); + String validAccount = credentials.getAddress(); + DefaultBlockParameter param = DefaultBlockParameterName.PENDING; + AppGetTransactionCount appGetTransactionCount = service.appGetTransactionCount( + validAccount, param).send(); + assertTrue(appGetTransactionCount.getTransactionCount().longValue()>=0); + } + + @Test + public void testAppGetTransactionReceipt() throws Exception { + AppSendTransaction appSendTx = appSendRawTransaction(); + String validTransactionHash = appSendTx.getSendTransactionResult().getHash(); + Thread.sleep(8000); + AppGetTransactionReceipt appGetTransactionReceipt = service.appGetTransactionReceipt( + validTransactionHash).send(); + TransactionReceipt transactionReceipt = + appGetTransactionReceipt.getTransactionReceipt(); + assertNotNull(transactionReceipt.getContractAddress()); + assertNull(transactionReceipt.getErrorMessage()); + } + + @Test + public void testAppGetCode() throws Exception { + + AppSendTransaction appSendTx = appSendRawTransaction(); + String validTransactionHash = appSendTx.getSendTransactionResult().getHash(); + Thread.sleep(8000); + AppGetTransactionReceipt appGetTransactionReceipt = service.appGetTransactionReceipt( + validTransactionHash).send(); + TransactionReceipt transactionReceipt = + appGetTransactionReceipt.getTransactionReceipt(); + String validContractAddress = transactionReceipt.getContractAddress(); + AppGetCode appGetCode = service + .appGetCode(validContractAddress, DefaultBlockParameterName.PENDING).send(); + assertThat(code,containsString(appGetCode.getCode().substring(2))); + } + + @Test + public void testAppCall() throws Exception { + // init from address + String fromAddress = Credentials.create(adminPrivateKey).getAddress(); + + // init contract address + AppSendTransaction appSendTx = appSendRawTransaction(); + String validTransactionHash = appSendTx.getSendTransactionResult().getHash(); + Thread.sleep(8000); + AppGetTransactionReceipt appGetTransactionReceipt = service.appGetTransactionReceipt( + validTransactionHash).send(); + TransactionReceipt transactionReceipt = + appGetTransactionReceipt.getTransactionReceipt(); + String contractAddress = transactionReceipt.getContractAddress(); + + // init funcCallData + Function getBalanceFunc = new Function( + "getBalance", + Arrays.asList(new Address(fromAddress)), + Arrays.asList(new TypeReference() { + }) + ); + String funcCallData = FunctionEncoder.encode(getBalanceFunc); + + // send call and check + AppCall appCall = service.appCall( + new Call(fromAddress, contractAddress, funcCallData), + DefaultBlockParameterName.PENDING).send(); + assertNotNull(appCall.getValue()); + } + + @BeforeClass + public static void initSenderBalanceBeforeClass() throws Exception { + //initSenderBalance(); + } +} diff --git a/tests/src/main/java/com/cryptape/cita/tests/SM2ValidationTest.java b/tests/src/test/java/com/cryptape/cita/tests/SM2ValidationTest.java similarity index 98% rename from tests/src/main/java/com/cryptape/cita/tests/SM2ValidationTest.java rename to tests/src/test/java/com/cryptape/cita/tests/SM2ValidationTest.java index 8becc119..cc525ee2 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/SM2ValidationTest.java +++ b/tests/src/test/java/com/cryptape/cita/tests/SM2ValidationTest.java @@ -1,12 +1,11 @@ package com.cryptape.cita.tests; -import java.math.BigInteger; - import com.cryptape.cita.crypto.sm2.SM2; import com.cryptape.cita.crypto.sm2.SM2KeyPair; import com.cryptape.cita.protocol.CITAj; import com.cryptape.cita.protocol.core.methods.request.Transaction; import com.cryptape.cita.protocol.core.methods.response.AppSendTransaction; +import java.math.BigInteger; /** * This example is to use SM2 to generate 100 pairs of keys @@ -48,11 +47,12 @@ private static String verifyTx(String contractCode, String privateKey) { return testTx.getSendTransactionResult().getHash(); } catch (Exception e) { e.printStackTrace(); - System.exit(1); + //System.exit(1); } return null; } + // need sm2 chain public static void main(String[] args) { // CHECKSTYLE:OFF String contractCode = "6060604052341561000f57600080fd5b600160a060020a033316600090815260208190526040902061271090556101df8061003b6000396000f3006060604052600436106100565763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166327e235e3811461005b578063a9059cbb1461008c578063f8b2cb4f146100c2575b600080fd5b341561006657600080fd5b61007a600160a060020a03600435166100e1565b60405190815260200160405180910390f35b341561009757600080fd5b6100ae600160a060020a03600435166024356100f3565b604051901515815260200160405180910390f35b34156100cd57600080fd5b61007a600160a060020a0360043516610198565b60006020819052908152604090205481565b600160a060020a03331660009081526020819052604081205482901080159061011c5750600082115b1561018e57600160a060020a033381166000818152602081905260408082208054879003905592861680825290839020805486019055917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9085905190815260200160405180910390a3506001610192565b5060005b92915050565b600160a060020a0316600090815260208190526040902054905600a165627a7a72305820f59b7130870eee8f044b129f4a20345ffaff662707fc0758133cd16684bc3b160029"; diff --git a/tests/src/main/java/com/cryptape/cita/tests/SendTransactionSyncExample.java b/tests/src/test/java/com/cryptape/cita/tests/SendTransactionSyncTest.java similarity index 52% rename from tests/src/main/java/com/cryptape/cita/tests/SendTransactionSyncExample.java rename to tests/src/test/java/com/cryptape/cita/tests/SendTransactionSyncTest.java index dc3fbc79..9554c688 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/SendTransactionSyncExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/SendTransactionSyncTest.java @@ -1,6 +1,8 @@ package com.cryptape.cita.tests; -import java.math.BigInteger; +import static junit.framework.TestCase.assertNull; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; import com.cryptape.cita.protocol.CITAj; import com.cryptape.cita.protocol.core.DefaultBlockParameterName; @@ -10,9 +12,14 @@ import com.cryptape.cita.protocol.core.methods.response.TransactionReceipt; import com.cryptape.cita.tx.response.PollingTransactionReceiptProcessor; import com.cryptape.cita.utils.Convert; +import java.math.BigDecimal; +import java.math.BigInteger; +import org.junit.Test; -public class SendTransactionSyncExample { +public class SendTransactionSyncTest { + private static String adminKey; + private static String adminKeyAddr; private static String payerKey; private static String payerAddr; private static String payeeAddr1; @@ -28,6 +35,8 @@ public class SendTransactionSyncExample { Config conf = new Config(); conf.buildService(false); + adminKey = conf.adminPrivateKey; + adminKeyAddr = conf.adminAddress; payerKey = conf.primaryPrivKey; payerAddr = conf.primaryAddr; payeeAddr1 = conf.auxAddr1; @@ -48,7 +57,7 @@ private static BigInteger getBalance(String address) { balance = response.getBalance(); } catch (Exception e) { System.out.println("failed to get balance."); - System.exit(1); + //System.exit(1); } return balance; } @@ -79,34 +88,47 @@ private static TransactionReceipt transferSync( return txReceipt; } - public static void main(String[] args) throws Exception { + @Test + public void testSendTransactionSync() throws Exception { - System.out.println(payerAddr + ": " - + Convert.fromWei(getBalance(payerAddr).toString(), Convert.Unit.ETHER)); - System.out.println(payeeAddr1 + ": " - + Convert.fromWei(getBalance(payeeAddr1).toString(), Convert.Unit.ETHER)); - System.out.println(payeeAddr2 + ": " - + Convert.fromWei(getBalance(payeeAddr2).toString(), Convert.Unit.ETHER)); + BigDecimal payeeBalanceEther1 = Convert.fromWei(getBalance(payeeAddr1).toString(), Convert.Unit.ETHER); + BigDecimal payeeBalanceEther2 = Convert.fromWei(getBalance(payeeAddr2).toString(), Convert.Unit.ETHER); + System.out.println(payeeAddr1 + ": " + payeeBalanceEther1); + System.out.println(payeeAddr2 + ": " + payeeBalanceEther2); String value = "1"; String valueWei = Convert.toWei(value, Convert.Unit.ETHER).toString(); + TransactionReceipt transactionReceipt1 = transferSync(adminKey, payeeAddr1, valueWei); + TransactionReceipt transactionReceipt2 = transferSync(adminKey, payeeAddr2, valueWei); + assertNull(transactionReceipt1.getErrorMessage()); + assertNull(transactionReceipt2.getErrorMessage()); + BigDecimal payeeBalanceEtherNow1 = Convert.fromWei(getBalance(payeeAddr1).toString(), Convert.Unit.ETHER); + BigDecimal payeeBalanceEtherNow2 = Convert.fromWei(getBalance(payeeAddr2).toString(), Convert.Unit.ETHER); + + System.out.println(payeeAddr1 + ": " + payeeBalanceEtherNow1); + System.out.println(payeeAddr2 + ": " + payeeBalanceEtherNow2); + assertThat(payeeBalanceEtherNow1.subtract(payeeBalanceEther1).intValue()+"", equalTo(value)); + assertThat(payeeBalanceEtherNow2.subtract(payeeBalanceEther2).intValue()+"", equalTo((value))); + } - TransactionReceipt txReceipt = transferSync(payerKey, payeeAddr1, valueWei); - if (txReceipt.getErrorMessage() == null) { - System.out.println(payerAddr + ": " - + Convert.fromWei(getBalance(payerAddr).toString(), Convert.Unit.ETHER)); - System.out.println(payeeAddr1 + ": " - + Convert.fromWei(getBalance(payeeAddr1).toString(), Convert.Unit.ETHER)); - } + public static void initSenderBalance () throws Exception { - TransactionReceipt txReceipt1 = transferSync(payerKey, payeeAddr2, valueWei); + BigDecimal adminBalanceEther = Convert.fromWei(getBalance(adminKeyAddr).toString(), Convert.Unit.ETHER); + BigDecimal payerBalanceEther = Convert.fromWei(getBalance(payerAddr).toString(), Convert.Unit.ETHER); + System.out.println(adminKeyAddr + ": " + adminBalanceEther); + System.out.println(payerAddr + ": " + payerBalanceEther); - if (txReceipt1.getErrorMessage() == null) { - System.out.println(payerAddr + ": " - + Convert.fromWei(getBalance(payerAddr).toString(), Convert.Unit.ETHER)); - System.out.println(payeeAddr2 + ": " - + Convert.fromWei(getBalance(payeeAddr2).toString(), Convert.Unit.ETHER)); - } + String value = "40"; + String valueWei = Convert.toWei(value, Convert.Unit.ETHER).toString(); + TransactionReceipt transactionReceipt1 = transferSync(adminKey, payerAddr, valueWei); + assertNull(transactionReceipt1.getErrorMessage()); + + BigDecimal payerBalanceEtherNow = Convert.fromWei(getBalance(payerAddr).toString(), Convert.Unit.ETHER); + System.out.println(payerAddr + ": " + payerBalanceEtherNow); + + String addEther = payerBalanceEtherNow.subtract(payerBalanceEther)+""; + assertThat(addEther, equalTo(value)); } + } diff --git a/tests/src/main/java/com/cryptape/cita/tests/SendTransactionAsyncExample.java b/tests/src/test/java/com/cryptape/cita/tests/SendTransactionTest.java similarity index 72% rename from tests/src/main/java/com/cryptape/cita/tests/SendTransactionAsyncExample.java rename to tests/src/test/java/com/cryptape/cita/tests/SendTransactionTest.java index 8e0471e7..41c632aa 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/SendTransactionAsyncExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/SendTransactionTest.java @@ -1,8 +1,8 @@ package com.cryptape.cita.tests; -import java.math.BigInteger; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; +import static junit.framework.TestCase.assertNull; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import com.cryptape.cita.protocol.CITAj; import com.cryptape.cita.protocol.core.DefaultBlockParameterName; @@ -13,8 +13,13 @@ import com.cryptape.cita.protocol.core.methods.response.TransactionReceipt; import com.cryptape.cita.tx.response.PollingTransactionReceiptProcessor; import com.cryptape.cita.utils.Convert; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import org.junit.Test; -public class SendTransactionAsyncExample { +public class SendTransactionTest { private static String payerKey; private static String payerAddr; private static String payeeAddr; @@ -28,8 +33,8 @@ public class SendTransactionAsyncExample { static { Config conf = new Config(); conf.buildService(false); - payerKey = conf.primaryPrivKey; - payerAddr = conf.primaryAddr; + payerKey = conf.adminPrivateKey; + payerAddr = conf.adminAddress; payeeAddr = conf.auxAddr1; quotaToTransfer = Long.parseLong(conf.defaultQuotaTransfer); service = conf.service; @@ -38,7 +43,7 @@ public class SendTransactionAsyncExample { cryptoTx = Transaction.CryptoTx.valueOf(conf.cryptoTx); } - private static BigInteger getBalance(String address) { + public static BigInteger getBalance(String address) { BigInteger balance = null; try { AppGetBalance response = service.appGetBalance( @@ -46,7 +51,7 @@ private static BigInteger getBalance(String address) { balance = response.getBalance(); } catch (Exception e) { System.out.println("failed to get balance."); - System.exit(1); + //System.exit(1); } return balance; } @@ -79,33 +84,22 @@ private static TransactionReceipt transferSync( return txReceipt; } - private static Future transferAsync( + public static Future transferAsync( String payerKey, String payeeAddr, String value) { return new RemoteCall<>( () -> transferSync(payerKey, payeeAddr, value)).sendAsync(); } - public static void main(String[] args) { - System.out.println(Convert.fromWei(getBalance(payerAddr).toString(), Convert.Unit.ETHER)); - System.out.println(Convert.fromWei(getBalance(payeeAddr).toString(), Convert.Unit.ETHER)); - + @Test + public void testSendTransaction( ) throws ExecutionException, InterruptedException { + BigDecimal payeeBalance = Convert.fromWei(getBalance(payeeAddr).toString(), Convert.Unit.ETHER); String value = "1"; String valueWei = Convert.toWei(value, Convert.Unit.ETHER).toString(); - Future receiptFuture = - transferAsync(payerKey, payeeAddr, valueWei); - try { - TransactionReceipt receipt = receiptFuture.get(); - if (receipt.getErrorMessage() == null) { - System.out.println( - Convert.fromWei(getBalance(payerAddr).toString(), Convert.Unit.ETHER)); - System.out.println( - Convert.fromWei(getBalance(payeeAddr).toString(), Convert.Unit.ETHER)); - } else { - System.out.println("Error get receipt: " + receipt.getErrorMessage()); - } - } catch (ExecutionException | InterruptedException e) { - e.printStackTrace(); - } + transferAsync(payerKey, payeeAddr, valueWei); + TransactionReceipt receipt = receiptFuture.get(); + assertNull(receipt.getErrorMessage()); + BigDecimal payeeBalanceNow = Convert.fromWei(getBalance(payeeAddr).toString(), Convert.Unit.ETHER); + assertThat(payeeBalanceNow.subtract(payeeBalance).intValue(), equalTo(Integer.parseInt(value))); } } diff --git a/tests/src/main/java/com/cryptape/cita/tests/SimpleDataExample.java b/tests/src/test/java/com/cryptape/cita/tests/SimpleDataTest.java similarity index 92% rename from tests/src/main/java/com/cryptape/cita/tests/SimpleDataExample.java rename to tests/src/test/java/com/cryptape/cita/tests/SimpleDataTest.java index 4894b405..edf7c1b9 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/SimpleDataExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/SimpleDataTest.java @@ -1,37 +1,40 @@ package com.cryptape.cita.tests; -import java.io.IOException; -import java.math.BigInteger; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import com.cryptape.cita.abi.FunctionEncoder; import com.cryptape.cita.abi.FunctionReturnDecoder; import com.cryptape.cita.abi.TypeReference; -import com.cryptape.cita.abi.datatypes.generated.Uint256; -import com.cryptape.cita.protobuf.ConvertStrByte; -import com.cryptape.cita.protocol.CITAj; -import com.cryptape.cita.protocol.core.DefaultBlockParameterName; -import com.cryptape.cita.protocol.core.methods.request.Call; -import com.cryptape.cita.protocol.core.methods.request.Transaction; -import com.cryptape.cita.protocol.core.methods.response.AppSendTransaction; import com.cryptape.cita.abi.datatypes.Address; import com.cryptape.cita.abi.datatypes.DynamicBytes; import com.cryptape.cita.abi.datatypes.Function; import com.cryptape.cita.abi.datatypes.Type; import com.cryptape.cita.abi.datatypes.Uint; import com.cryptape.cita.abi.datatypes.Utf8String; +import com.cryptape.cita.abi.datatypes.generated.Uint256; +import com.cryptape.cita.protobuf.ConvertStrByte; +import com.cryptape.cita.protocol.CITAj; +import com.cryptape.cita.protocol.core.DefaultBlockParameterName; +import com.cryptape.cita.protocol.core.methods.request.Call; +import com.cryptape.cita.protocol.core.methods.request.Transaction; import com.cryptape.cita.protocol.core.methods.response.AppGetTransactionReceipt; +import com.cryptape.cita.protocol.core.methods.response.AppSendTransaction; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.junit.Test; /* * The example shows how to deploy a contract with constructor parameters * */ -public class SimpleDataExample { +public class SimpleDataTest { private static BigInteger chainId; private static int version; private static String privateKey; @@ -48,8 +51,8 @@ public class SimpleDataExample { Config conf = new Config(); conf.buildService(false); - privateKey = conf.primaryPrivKey; - fromAddress = conf.primaryAddr; + privateKey = conf.adminPrivateKey; + fromAddress = conf.adminAddress; toAddress = conf.auxAddr1; binPath = conf.simpleBin; @@ -154,7 +157,8 @@ private static String loadContractCode(String binPath) throws Exception { return new String(Files.readAllBytes(Paths.get(binPath))); } - public static void main(String[] args) throws Exception { + @Test + public void testSimpleData() throws Exception { //deploy the contract with sample parameters String deploymentHash = deploySampleContract(1, "userName", "userDesc", toAddress); System.out.println("Hash of contract deployment: " + deploymentHash); @@ -169,5 +173,10 @@ public static void main(String[] args) throws Exception { System.out.println("user name: " + getName()); System.out.println("user desc: " + getUserDesc()); System.out.println("user addr: " + getUserAddr()); + assertThat(getUserId(),equalTo(BigInteger.valueOf(1L))); + assertThat(getName(),equalTo("userName")); + assertThat(getUserDesc(),equalTo("userDesc")); + assertThat(getUserAddr(),equalTo(toAddress)); + } } diff --git a/tests/src/main/java/com/cryptape/cita/tests/StoreRecordExample.java b/tests/src/test/java/com/cryptape/cita/tests/StoreRecordTest.java similarity index 85% rename from tests/src/main/java/com/cryptape/cita/tests/StoreRecordExample.java rename to tests/src/test/java/com/cryptape/cita/tests/StoreRecordTest.java index 459adc29..a0d71d5f 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/StoreRecordExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/StoreRecordTest.java @@ -1,8 +1,7 @@ package com.cryptape.cita.tests; -import java.io.IOException; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import com.cryptape.cita.protobuf.Blockchain; import com.cryptape.cita.protobuf.ConvertStrByte; @@ -11,8 +10,12 @@ import com.cryptape.cita.protocol.core.methods.response.AppSendTransaction; import com.cryptape.cita.protocol.system.CITAjSystemContract; import com.cryptape.cita.utils.Numeric; +import java.io.IOException; +import java.math.BigInteger; +import java.util.concurrent.TimeUnit; +import org.junit.Test; -public class StoreRecordExample { +public class StoreRecordTest { private static String payerKey; private static BigInteger chainId; @@ -26,13 +29,14 @@ public class StoreRecordExample { conf.buildService(false); service = conf.service; - payerKey = conf.primaryPrivKey; + payerKey = conf.adminPrivateKey; chainId = TestUtil.getChainId(service); version = TestUtil.getVersion(service); cryptoTx = Transaction.CryptoTx.valueOf(conf.cryptoTx); } - public static void main(String[] args) + @Test + public void testStoreRecord() throws IOException, InterruptedException { String sampleDataToStore = ConvertStrByte @@ -48,13 +52,6 @@ public static void main(String[] args) AppSendTransaction appSendTransaction = service.appSendRawTransaction(signedTx).send(); - if (appSendTransaction.getError() != null) { - System.out.println( - "Failed to get hash of transaction. Error message: " - + appSendTransaction.getError().getMessage()); - System.exit(1); - } - String hash = appSendTransaction.getSendTransactionResult().getHash(); System.out.println("Wait 6s for transaction written into block."); @@ -76,5 +73,7 @@ public static void main(String[] args) .parseFrom(byteSerializedTx); System.out.println(unverifiedTransaction); + String dataStored = unverifiedTransaction.getTransaction().getData().toStringUtf8(); + assertThat(dataStored,equalTo("SampleDataToStore")); } } diff --git a/tests/src/main/java/com/cryptape/cita/tests/SystemContractExample.java b/tests/src/test/java/com/cryptape/cita/tests/SystemContractTest.java similarity index 72% rename from tests/src/main/java/com/cryptape/cita/tests/SystemContractExample.java rename to tests/src/test/java/com/cryptape/cita/tests/SystemContractTest.java index ac95be7a..d82e56a8 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/SystemContractExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/SystemContractTest.java @@ -1,12 +1,14 @@ package com.cryptape.cita.tests; -import java.math.BigInteger; -import java.util.List; +import static org.junit.Assert.assertTrue; import com.cryptape.cita.protocol.CITAj; import com.cryptape.cita.protocol.system.CITAjSystemContract; +import java.math.BigInteger; +import java.util.List; +import org.junit.Test; -public class SystemContractExample { +public class SystemContractTest { static CITAj service; static String senderAddr; @@ -26,7 +28,8 @@ public class SystemContractExample { sysContract = new CITAjSystemContract(service); } - public static void main(String[] args) throws Exception { + @Test + public void testSystemContract() throws Exception { long quotaPrice = sysContract.getQuotaPrice(senderAddr); System.out.println("Quota price is: " + quotaPrice); @@ -49,25 +52,13 @@ public static void main(String[] args) throws Exception { //test approve node boolean approved = sysContract.approveNode( "0xe2066149012e6c1505e3549d103068bd0f2f0577", adminPriavteKey, version, chainId); - if (approved) { - System.out.println( - "Node(0xe2066149012e6c1505e3549d103068bd0f2f0577) " - + "is added as a consensus node successfully"); - } + List nodesNow = sysContract.listNode(senderAddr); + assertTrue(nodesNow.contains("0xe2066149012e6c1505e3549d103068bd0f2f0577")); //test for delete node boolean deleted = sysContract.deleteNode( "0xe2066149012e6c1505e3549d103068bd0f2f0577", adminPriavteKey, version, chainId); - if (deleted) { - System.out.println( - "Node(0xe2066149012e6c1505e3549d103068bd0f2f0577) " - + "is deleted from consensus nodes successfully."); - } + assertTrue(deleted); - /**Don't try this**/ - //boolean setStake = sysContract.setStake(senderAddr, 2, adminPrivateKey); - //if (setStake) { - // System.out.println("success"); - //} } } diff --git a/tests/src/main/java/com/cryptape/cita/tests/TestUtil.java b/tests/src/test/java/com/cryptape/cita/tests/TestUtil.java similarity index 95% rename from tests/src/main/java/com/cryptape/cita/tests/TestUtil.java rename to tests/src/test/java/com/cryptape/cita/tests/TestUtil.java index 854b96d0..4a0786d3 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/TestUtil.java +++ b/tests/src/test/java/com/cryptape/cita/tests/TestUtil.java @@ -1,13 +1,12 @@ package com.cryptape.cita.tests; -import java.math.BigInteger; -import java.util.Random; - import com.cryptape.cita.protobuf.ConvertStrByte; import com.cryptape.cita.protocol.CITAj; import com.cryptape.cita.protocol.core.DefaultBlockParameterName; -import com.cryptape.cita.utils.Numeric; import com.cryptape.cita.protocol.core.methods.response.AppMetaData; +import com.cryptape.cita.utils.Numeric; +import java.math.BigInteger; +import java.util.Random; public class TestUtil { @@ -22,7 +21,7 @@ static int getVersion(CITAj service) { appMetaData = service.appMetaData(DefaultBlockParameterName.PENDING).send(); } catch (Exception e) { e.printStackTrace(); - System.exit(1); + //System.exit(1); } return appMetaData.getAppMetaDataResult().getVersion(); } @@ -33,7 +32,7 @@ static BigInteger getChainId(CITAj service) { appMetaData = service.appMetaData(DefaultBlockParameterName.PENDING).send(); } catch (Exception e) { e.printStackTrace(); - System.exit(1); + //System.exit(1); } return appMetaData.getAppMetaDataResult().getChainId(); } @@ -60,14 +59,14 @@ private static BigInteger getCurrentHeight(CITAj service, int retry) { Thread.sleep(2000); } catch (Exception e1) { System.out.println("failed to get block number, Exception: " + e1); - System.exit(1); + //System.exit(1); } } count++; } if (height == -1) { System.out.println("Failed to get block number after " + count + " times."); - System.exit(1); + //System.exit(1); } return BigInteger.valueOf(height); } diff --git a/tests/src/main/java/com/cryptape/cita/tests/Token.java b/tests/src/test/java/com/cryptape/cita/tests/Token.java similarity index 100% rename from tests/src/main/java/com/cryptape/cita/tests/Token.java rename to tests/src/test/java/com/cryptape/cita/tests/Token.java diff --git a/tests/src/main/java/com/cryptape/cita/tests/TokenAccountExample.java b/tests/src/test/java/com/cryptape/cita/tests/TokenAccountTest.java similarity index 93% rename from tests/src/main/java/com/cryptape/cita/tests/TokenAccountExample.java rename to tests/src/test/java/com/cryptape/cita/tests/TokenAccountTest.java index 29263329..fe18d909 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/TokenAccountExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/TokenAccountTest.java @@ -1,16 +1,17 @@ package com.cryptape.cita.tests; -import java.io.File; -import java.math.BigInteger; - import com.cryptape.cita.protocol.CITAj; import com.cryptape.cita.protocol.account.Account; import com.cryptape.cita.protocol.account.CompiledContract; +import com.cryptape.cita.protocol.core.methods.response.AbiDefinition; import com.cryptape.cita.protocol.core.methods.response.AppSendTransaction; import com.cryptape.cita.protocol.core.methods.response.TransactionReceipt; -import com.cryptape.cita.protocol.core.methods.response.AbiDefinition; +import java.io.File; +import java.math.BigInteger; +import org.junit.Ignore; +import org.junit.Test; -public class TokenAccountExample { +public class TokenAccountTest { private static BigInteger chainId; private static int version; @@ -49,7 +50,7 @@ private static TransactionReceipt waitToGetReceipt( .send().getTransactionReceipt(); } - public TokenAccountExample() throws Exception { + public TokenAccountTest() throws Exception { account = new Account(privateKey, service); tokenContract = new CompiledContract(new File(solPath)); @@ -63,7 +64,7 @@ public String deployContract(String path) throws Exception { if (receipt.getErrorMessage() != null) { System.out.println("deploy contract failed because of " + receipt.getErrorMessage()); - System.exit(1); + //System.exit(1); } contractAddress = receipt.getContractAddress(); System.out.println("deploy contract success and contract address is " @@ -83,7 +84,7 @@ public void transfer(String toAddress, BigInteger amount) if (receipt.getErrorMessage() != null) { System.out.println("call transfer method failed because of " + receipt.getErrorMessage()); - System.exit(1); + //System.exit(1); } System.out.println("call transfer method success and receipt is " + receipt.getTransactionHash()); @@ -107,7 +108,7 @@ public void transferRemote(String toAddress, BigInteger amount) throws Exception if (receipt.getErrorMessage() != null) { System.out.println("call transfer method failed because of " + receipt.getErrorMessage()); - System.exit(1); + //System.exit(1); } System.out.println("call transfer method success and receipt is " + receipt.getTransactionHash()); @@ -130,7 +131,7 @@ public void storeAbiToBlockchain() throws Exception { if (receipt.getErrorMessage() != null) { System.out.println("call upload abi method failed because of " + receipt.getErrorMessage()); - System.exit(1); + //System.exit(1); } else { System.out.println("call upload abi method success. Receipt " + receipt); } @@ -144,7 +145,10 @@ public void getAbi() throws Exception { System.out.println("abi: " + abi); } - public static void main(String[] args) throws Exception { + // need solc environment + @Ignore + @Test + public void testTokenAccount() throws Exception { // deploy contract with smart contract solidity file // and call method "transfer" with generated Abi String contractAddr = deployContractAndCallMethodFromSolidity(); @@ -153,14 +157,14 @@ public static void main(String[] args) throws Exception { // and call method "transfer" callContractMethodFromRemoteAbi(contractAddr); - System.exit(0); + //System.exit(0); } //CHECKSTYLE:OFF private static String deployContractAndCallMethodFromSolidity() throws Exception { - TokenAccountExample tokenAccountExample = new TokenAccountExample(); + TokenAccountTest tokenAccountExample = new TokenAccountTest(); String contractAddr = tokenAccountExample.deployContract(solPath); tokenAccountExample.getBalance(fromAddress); tokenAccountExample.getBalance(toAddress); @@ -175,7 +179,7 @@ private static String deployContractAndCallMethodFromSolidity() private static void callContractMethodFromRemoteAbi(String contractAddress) throws Exception { - TokenAccountExample tokenAccountExample = new TokenAccountExample(); + TokenAccountTest tokenAccountExample = new TokenAccountTest(); tokenAccountExample.contractAddress = contractAddress; tokenAccountExample.transferRemote(toAddress, BigInteger.valueOf(500)); tokenAccountExample.getBalanceRemote(fromAddress); diff --git a/tests/src/main/java/com/cryptape/cita/tests/TokenCodegenExample.java b/tests/src/test/java/com/cryptape/cita/tests/TokenCodegenTest.java similarity index 94% rename from tests/src/main/java/com/cryptape/cita/tests/TokenCodegenExample.java rename to tests/src/test/java/com/cryptape/cita/tests/TokenCodegenTest.java index acfcba1c..2f0c20c4 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/TokenCodegenExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/TokenCodegenTest.java @@ -1,7 +1,11 @@ package com.cryptape.cita.tests; +import com.cryptape.cita.crypto.Credentials; +import com.cryptape.cita.protocol.CITAj; +import com.cryptape.cita.protocol.core.methods.response.TransactionReceipt; +import com.cryptape.cita.tx.RawTransactionManager; +import com.cryptape.cita.tx.TransactionManager; import java.math.BigInteger; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -12,14 +16,10 @@ import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import org.junit.Ignore; +import org.junit.Test; -import com.cryptape.cita.crypto.Credentials; -import com.cryptape.cita.protocol.CITAj; -import com.cryptape.cita.protocol.core.methods.response.TransactionReceipt; -import com.cryptape.cita.tx.RawTransactionManager; -import com.cryptape.cita.tx.TransactionManager; - -public class TokenCodegenExample { +public class TokenCodegenTest { private static Config conf; private static BigInteger chainId; private static int version; @@ -70,7 +70,7 @@ private static long getBalance(Credentials credentials) { System.out.println("Failed to get balance of account: " + credentials.getAddress()); e.printStackTrace(); - System.exit(1); + //System.exit(1); } return accountBalance; } @@ -94,7 +94,7 @@ private static void waitToGetToken() { } } catch (InterruptedException e) { System.out.println("thread is interrupted accidently"); - System.exit(1); + //System.exit(1); } } @@ -109,7 +109,7 @@ private static void waitToGetToken() { private static boolean isTokenTransferComplete() { Map accountTokens = new HashMap<>(); for (Credentials credentials : testAccounts) { - accountTokens.put(credentials, TokenCodegenExample.getBalance(credentials)); + accountTokens.put(credentials, TokenCodegenTest.getBalance(credentials)); } long totalToken = 0; for (Long token : accountTokens.values()) { @@ -137,10 +137,10 @@ private void shuffle(Credentials credentials) { | TimeoutException e) { System.out.println( "Failed to get receipt from receiptFuture. Failed to shuffle."); - System.exit(1); + //System.exit(1); } catch (Exception e) { System.out.println("Event execute failed. Failed to Shuffle"); - System.exit(1); + //System.exit(1); } } }); @@ -199,7 +199,7 @@ private void randomTransferToken() { long accountBalance = getBalance(account); System.out.println(account.getAddress() + ": " + accountBalance); }); - System.exit(1); + //System.exit(1); } if (event.tokens < shuffleThreshold) { @@ -209,7 +209,9 @@ private void randomTransferToken() { } - public static void main(String[] args) throws Exception { + @Ignore + @Test + public void testTokenCodegen() throws Exception { TransactionManager citaTxManager = new RawTransactionManager( service, creator, 5, 3000); @@ -219,7 +221,7 @@ public static void main(String[] args) throws Exception { service, citaTxManager, quotaDeployment, nonce, TestUtil.getValidUtilBlock(service).longValue(), version, value, chainId).sendAsync(); - TokenCodegenExample tokenCodegenExample = new TokenCodegenExample(); + TokenCodegenTest tokenCodegenExample = new TokenCodegenTest(); System.out.println("Wait 10s for contract to be deployed..."); Thread.sleep(10000); @@ -229,7 +231,7 @@ public static void main(String[] args) throws Exception { + token.getContractAddress()); } else { System.out.println("Failed to deploy the contract."); - System.exit(1); + //System.exit(1); } try { @@ -237,7 +239,7 @@ public static void main(String[] args) throws Exception { } catch (Exception e) { e.printStackTrace(); System.out.println("Interrupted when waiting blocks written in."); - System.exit(1); + //System.exit(1); } try { @@ -247,9 +249,9 @@ public static void main(String[] args) throws Exception { } catch (Exception e) { System.out.println("Failed to get accounts balances"); e.printStackTrace(); - System.exit(1); + //System.exit(1); } - System.exit(0); + //System.exit(0); } private class TransferEvent { diff --git a/tests/src/main/java/com/cryptape/cita/tests/TokenFilterCodeGenExample.java b/tests/src/test/java/com/cryptape/cita/tests/TokenFilterCodeGenTest.java similarity index 78% rename from tests/src/main/java/com/cryptape/cita/tests/TokenFilterCodeGenExample.java rename to tests/src/test/java/com/cryptape/cita/tests/TokenFilterCodeGenTest.java index 97b16cb7..c382403c 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/TokenFilterCodeGenExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/TokenFilterCodeGenTest.java @@ -1,9 +1,8 @@ package com.cryptape.cita.tests; -import java.math.BigInteger; -import java.util.concurrent.Future; -import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.TimeUnit; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertNotNull; import com.cryptape.cita.crypto.Credentials; import com.cryptape.cita.crypto.sm2.SM2; @@ -15,8 +14,13 @@ import com.cryptape.cita.tx.TransactionManager; import io.reactivex.Flowable; import io.reactivex.functions.Consumer; +import java.math.BigInteger; +import java.util.concurrent.Future; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import org.junit.Test; -public class TokenFilterCodeGenExample { +public class TokenFilterCodeGenTest { private static BigInteger chainId; private static int version; private static String payerPrivateKey; @@ -34,9 +38,9 @@ public class TokenFilterCodeGenExample { Config conf = new Config(); conf.buildService(false); - payerPrivateKey = conf.primaryPrivKey; + payerPrivateKey = conf.adminPrivateKey; payeePrivateKey = conf.auxPrivKey1; - payerAddr = conf.primaryAddr; + payerAddr = conf.adminAddress; payeeAddr = conf.auxAddr1; service = conf.service; quota = Long.parseLong(conf.defaultQuotaDeployment); @@ -55,7 +59,7 @@ private static long getBalance(String addr) { } catch (Exception e) { System.out.println("Failed to get balance of account: " + addr); e.printStackTrace(); - System.exit(1); + //System.exit(1); } return accountBalance; } @@ -81,7 +85,7 @@ private void randomTransferToken() { Credentials fromCredential = Credentials.create(payerPrivateKey); Credentials toCredential = Credentials.create(payeePrivateKey); - for (int i = 0; i < 20; i++) { + for (int i = 0; i < 6; i++) { System.out.println("Transfer " + i); long fromBalance = getBalance(payerAddr); long transferAmount = ThreadLocalRandom @@ -94,11 +98,14 @@ private void randomTransferToken() { } catch (Exception e) { System.out.println("Thread interrupted."); } + long fromBalanceNow = getBalance(payerAddr); + assertThat(fromBalance-fromBalanceNow,equalTo(transferAmount)); } } - public static void main(String[] args) throws Exception { + @Test + public void TokenFilterCodeGenTest() throws Exception { TransactionManager rawTransactionManager = new RawTransactionManager( service, Credentials.create(payerPrivateKey), 5, 3000); //Instantiate SM2 style rawTransactionManager @@ -115,39 +122,25 @@ public static void main(String[] args) throws Exception { service, rawTransactionManager, 1000000L, nonce, validUtilBlock, version, value, chainId).sendAsync(); - TokenFilterCodeGenExample tokenFilterCodeGenExample = new TokenFilterCodeGenExample(); + TokenFilterCodeGenTest tokenFilterCodeGenExample = new TokenFilterCodeGenTest(); System.out.println("Wait 10s for contract to be deployed..."); Thread.sleep(10000); token = tokenFuture.get(); - if (token != null) { - System.out.println("contract deployment success. Contract address: " - + token.getContractAddress()); - } else { - System.out.println("Failed to deploy the contract."); - System.exit(1); - } + assertNotNull(token.getContractAddress()); + System.out.println("contract deployment success. Contract address: " + + token.getContractAddress()); //in cita 0.20, it seems that contract is not ready even if address is returned. - try { - System.out.println("waiting for transaction in the block"); - TimeUnit.SECONDS.sleep(4); - } catch (Exception e) { - System.out.println("interrupted when waiting for transactions written into block"); - e.printStackTrace(); - System.exit(1); - } - try { - System.out.println("Contract initial state: "); - tokenFilterCodeGenExample.randomTransferToken(); - } catch (Exception e) { - System.out.println("Failed to get accounts balances" + e); - e.printStackTrace(); - System.exit(1); - } - System.exit(0); + System.out.println("waiting for transaction in the block"); + TimeUnit.SECONDS.sleep(4); + System.out.println("interrupted when waiting for transactions written into block"); + + System.out.println("Contract initial state: "); + tokenFilterCodeGenExample.randomTransferToken(); + } private class TransferEvent { @@ -162,14 +155,14 @@ private class TransferEvent { } void execute() { - Token tokenContract = TokenFilterCodeGenExample.this.token; + Token tokenContract = TokenFilterCodeGenTest.this.token; long validUtilBlock = TestUtil.getValidUtilBlock( - TokenFilterCodeGenExample.this.service).longValue(); + TokenFilterCodeGenTest.this.service).longValue(); String nonce = TestUtil.getNonce(); tokenContract.transfer( this.to, BigInteger.valueOf(tokens), - TokenFilterCodeGenExample.quota, + TokenFilterCodeGenTest.quota, nonce, validUtilBlock, version, chainId, value).sendAsync(); } diff --git a/tests/src/main/java/com/cryptape/cita/tests/TokenFilterFlowableExample.java b/tests/src/test/java/com/cryptape/cita/tests/TokenFilterFlowableTest.java similarity index 96% rename from tests/src/main/java/com/cryptape/cita/tests/TokenFilterFlowableExample.java rename to tests/src/test/java/com/cryptape/cita/tests/TokenFilterFlowableTest.java index 30616165..6f858232 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/TokenFilterFlowableExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/TokenFilterFlowableTest.java @@ -1,32 +1,33 @@ package com.cryptape.cita.tests; -import java.io.IOException; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.Collections; -import java.util.concurrent.TimeUnit; +import static com.cryptape.cita.tx.Contract.staticExtractEventParameters; +import static org.junit.Assert.assertTrue; +import com.cryptape.cita.abi.EventEncoder; +import com.cryptape.cita.abi.EventValues; +import com.cryptape.cita.abi.FunctionEncoder; +import com.cryptape.cita.abi.TypeReference; +import com.cryptape.cita.abi.datatypes.Address; +import com.cryptape.cita.abi.datatypes.Event; +import com.cryptape.cita.abi.datatypes.Function; import com.cryptape.cita.abi.datatypes.generated.Uint256; import com.cryptape.cita.protocol.CITAj; import com.cryptape.cita.protocol.core.DefaultBlockParameterName; import com.cryptape.cita.protocol.core.methods.request.AppFilter; import com.cryptape.cita.protocol.core.methods.request.Transaction; +import com.cryptape.cita.protocol.core.methods.response.AppGetTransactionReceipt; import com.cryptape.cita.protocol.core.methods.response.AppSendTransaction; import com.cryptape.cita.protocol.core.methods.response.Log; import com.cryptape.cita.protocol.core.methods.response.TransactionReceipt; import io.reactivex.Flowable; -import com.cryptape.cita.abi.EventEncoder; -import com.cryptape.cita.abi.EventValues; -import com.cryptape.cita.abi.FunctionEncoder; -import com.cryptape.cita.abi.TypeReference; -import com.cryptape.cita.abi.datatypes.Address; -import com.cryptape.cita.abi.datatypes.Event; -import com.cryptape.cita.abi.datatypes.Function; -import com.cryptape.cita.protocol.core.methods.response.AppGetTransactionReceipt; - -import static com.cryptape.cita.tx.Contract.staticExtractEventParameters; +import java.io.IOException; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Collections; +import java.util.concurrent.TimeUnit; +import org.junit.Test; -public class TokenFilterFlowableExample { +public class TokenFilterFlowableTest { private static BigInteger chainId; private static int version; private static String privateKey; @@ -40,7 +41,7 @@ public class TokenFilterFlowableExample { Config conf = new Config(); conf.buildService(false); - privateKey = conf.primaryPrivKey; + privateKey = conf.adminPrivateKey; toAddress = conf.auxAddr1; service = conf.service; quota = Long.parseLong(conf.defaultQuotaDeployment); @@ -133,7 +134,8 @@ private static String contractFunctionCall( .send().getSendTransactionResult().getHash(); } - public static void main(String[] args) { + @Test + public void testTokenFilterFlowable() { String contractCode = "6060604052341561000f57600080fd5" + "b600160a060020a03331660009081526020819052604090206127109055610" + "1df8061003b6000396000f3006060604052600436106100565763ffffffff7" @@ -152,6 +154,7 @@ public static void main(String[] args) { + "3506001610192565b5060005b92915050565b600160a060020a03166000908" + "15260208190526040902054905600a165627a7a72305820f59b7130870eee8" + "f044b129f4a20345ffaff662707fc0758133cd16684bc3b160029"; + boolean noException = true; try { String txHash = deployContract(contractCode); System.out.println("wait for 8 secs for contract deployment"); @@ -195,13 +198,14 @@ public static void main(String[] args) { transfer(contractAddr, toAddress, new BigInteger("3")); } catch (IOException e) { + noException = false; e.printStackTrace(); System.out.println("IO Exception: maybe tx is not deployed successfully"); - System.exit(1); } catch (Exception e) { + noException = false; e.printStackTrace(); - System.exit(1); } + assertTrue(noException); } public static class TransferObj { diff --git a/tests/src/main/java/com/cryptape/cita/tests/TokenFilterTransactionExample.java b/tests/src/test/java/com/cryptape/cita/tests/TokenFilterTransactionTest.java similarity index 97% rename from tests/src/main/java/com/cryptape/cita/tests/TokenFilterTransactionExample.java rename to tests/src/test/java/com/cryptape/cita/tests/TokenFilterTransactionTest.java index e281b883..3d10afab 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/TokenFilterTransactionExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/TokenFilterTransactionTest.java @@ -1,13 +1,6 @@ package com.cryptape.cita.tests; -import java.io.IOException; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Random; -import java.util.concurrent.TimeUnit; +import static org.junit.Assert.assertTrue; import com.cryptape.cita.abi.EventEncoder; import com.cryptape.cita.abi.EventValues; @@ -22,14 +15,23 @@ import com.cryptape.cita.protocol.core.Request; import com.cryptape.cita.protocol.core.methods.request.AppFilter; import com.cryptape.cita.protocol.core.methods.request.Transaction; +import com.cryptape.cita.protocol.core.methods.response.AppGetTransactionReceipt; import com.cryptape.cita.protocol.core.methods.response.AppLog; import com.cryptape.cita.protocol.core.methods.response.AppSendTransaction; import com.cryptape.cita.protocol.core.methods.response.Log; import com.cryptape.cita.protocol.core.methods.response.TransactionReceipt; import com.cryptape.cita.tx.Contract; -import com.cryptape.cita.protocol.core.methods.response.AppGetTransactionReceipt; +import java.io.IOException; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Random; +import java.util.concurrent.TimeUnit; +import org.junit.Test; -public class TokenFilterTransactionExample { +public class TokenFilterTransactionTest { private static BigInteger chainId; private static int version; private static String privateKey; @@ -44,7 +46,7 @@ public class TokenFilterTransactionExample { Config config = new Config(); config.buildService(true); - privateKey = config.primaryPrivKey; + privateKey = config.adminPrivateKey; toAddress = config.auxAddr1; service = config.service; random = new Random(System.currentTimeMillis()); @@ -184,7 +186,8 @@ private static void contractFunctionCall( service.appSendRawTransaction(rawTx).send(); } - public static void main(String[] args) { + @Test + public void TokenFilterTransactionTest() { String contractCode = "6060604052341561000f57600080fd5" + "b600160a060020a03331660009081526020819052604090206127109055610" + "1df8061003b6000396000f3006060604052600436106100565763ffffffff7" @@ -204,6 +207,7 @@ public static void main(String[] args) { + "15260208190526040902054905600a165627a7a72305820f59b7130870eee8" + "f044b129f4a20345ffaff662707fc0758133cd16684bc3b160029"; + boolean noException = true; try { String txHash = deployContract(contractCode); System.out.println("wait for 8 secs for contract deployment"); @@ -251,14 +255,14 @@ public static void main(String[] args) { } System.out.println("Filter Id " + filterId); } catch (IOException e) { + noException = false; e.printStackTrace(); System.out.println("IO Exception: maybe tx is not deployed successfully"); - System.exit(1); } catch (Exception e) { + noException = false; e.printStackTrace(); - System.exit(1); } - + assertTrue(noException); } public static class TransferEventResponse { diff --git a/tests/src/main/java/com/cryptape/cita/tests/TokenTransactionExample.java b/tests/src/test/java/com/cryptape/cita/tests/TokenTransactionTest.java similarity index 93% rename from tests/src/main/java/com/cryptape/cita/tests/TokenTransactionExample.java rename to tests/src/test/java/com/cryptape/cita/tests/TokenTransactionTest.java index 93a8c507..311d3bb1 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/TokenTransactionExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/TokenTransactionTest.java @@ -1,11 +1,8 @@ package com.cryptape.cita.tests; -import java.math.BigInteger; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertNull; import com.cryptape.cita.abi.FunctionEncoder; import com.cryptape.cita.abi.FunctionReturnDecoder; @@ -20,9 +17,16 @@ import com.cryptape.cita.protocol.core.methods.request.Call; import com.cryptape.cita.protocol.core.methods.request.Transaction; import com.cryptape.cita.protocol.core.methods.response.TransactionReceipt; +import java.math.BigInteger; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.junit.Test; -public class TokenTransactionExample { +public class TokenTransactionTest { private static BigInteger chainId; private static int version; private static String privateKey; @@ -38,8 +42,8 @@ public class TokenTransactionExample { Config conf = new Config(); conf.buildService(false); - privateKey = conf.primaryPrivKey; - fromAddress = conf.primaryAddr; + privateKey = conf.adminPrivateKey; + fromAddress = conf.adminAddress; toAddress = conf.auxAddr1; binPath = conf.tokenBin; @@ -124,7 +128,8 @@ private static String getBalance(String fromAddr, String contractAddress) throws return resultTypes.get(0).getValue().toString(); } - public static void main(String[] args) throws Exception { + @Test + public void testTokenTransaction() throws Exception { // deploy contract String contractCode = loadContractCode(binPath); System.out.println(contractCode); @@ -138,7 +143,7 @@ public static void main(String[] args) throws Exception { if (txReceipt.getErrorMessage() != null) { System.out.println("There is something wrong in deployContractTxHash. Error: " + txReceipt.getErrorMessage()); - System.exit(1); + //System.exit(1); } String contractAddress = txReceipt.getContractAddress(); System.out.println("Contract deployed successfully. Contract address: " @@ -156,10 +161,11 @@ public static void main(String[] args) throws Exception { Thread.sleep(10000); TransactionReceipt transferTxReceipt = getTransactionReceipt(transferTxHash); + assertNull(transferTxReceipt.getErrorMessage()); if (transferTxReceipt.getErrorMessage() != null) { System.out.println("Failed to call transfer method in contract. Error: " + transferTxReceipt.getErrorMessage()); - System.exit(1); + //System.exit(1); } System.out.println("call transfer method success and receipt is " + transferTxHash); @@ -169,6 +175,6 @@ public static void main(String[] args) throws Exception { System.out.println(toAddress + " has " + balanceTo + " tokens."); System.out.println("Complete"); - System.exit(0); + assertThat(balaneFrom,equalTo("9000")); } } diff --git a/tests/src/main/java/com/cryptape/cita/tests/VerifySignatureExample.java b/tests/src/test/java/com/cryptape/cita/tests/VerifySignatureTest.java similarity index 91% rename from tests/src/main/java/com/cryptape/cita/tests/VerifySignatureExample.java rename to tests/src/test/java/com/cryptape/cita/tests/VerifySignatureTest.java index e5bed23a..d8b2fbbc 100644 --- a/tests/src/main/java/com/cryptape/cita/tests/VerifySignatureExample.java +++ b/tests/src/test/java/com/cryptape/cita/tests/VerifySignatureTest.java @@ -1,8 +1,6 @@ package com.cryptape.cita.tests; -import java.io.IOException; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; +import static org.junit.Assert.assertTrue; import com.cryptape.cita.protobuf.ConvertStrByte; import com.cryptape.cita.protocol.CITAj; @@ -10,8 +8,12 @@ import com.cryptape.cita.protocol.core.methods.response.AppSendTransaction; import com.cryptape.cita.protocol.core.methods.response.AppTransaction; import com.cryptape.cita.utils.Numeric; +import java.io.IOException; +import java.math.BigInteger; +import java.util.concurrent.TimeUnit; +import org.junit.Test; -public class VerifySignatureExample { +public class VerifySignatureTest { private static String privateKey; private static String primaryAddr; private static BigInteger chainId; @@ -24,8 +26,8 @@ public class VerifySignatureExample { Config conf = new Config(); conf.buildService(false); - privateKey = conf.primaryPrivKey; - primaryAddr = conf.primaryAddr; + privateKey = conf.adminPrivateKey; + primaryAddr = conf.adminAddress; service = conf.service; chainId = TestUtil.getChainId(service); version = TestUtil.getVersion(service); @@ -64,7 +66,8 @@ private static String sendSampleTransaction(String signedTx) } } - public static void main(String[] args) throws Exception { + @Test + public void testVerifySignatureTest() throws Exception { //create a sample transaction Transaction tx = createSampleTransaction(); @@ -86,5 +89,6 @@ public static void main(String[] args) throws Exception { //verify signature in response transaction boolean valid = respTx.verifySignature(primaryAddr); System.out.println("Verification: " + valid); + assertTrue(valid); } } diff --git a/tests/src/main/resources/Advance.abi b/tests/src/test/resources/Advance.abi similarity index 100% rename from tests/src/main/resources/Advance.abi rename to tests/src/test/resources/Advance.abi diff --git a/tests/src/main/resources/Advance.bin b/tests/src/test/resources/Advance.bin similarity index 100% rename from tests/src/main/resources/Advance.bin rename to tests/src/test/resources/Advance.bin diff --git a/tests/src/main/resources/Advance.sol b/tests/src/test/resources/Advance.sol similarity index 100% rename from tests/src/main/resources/Advance.sol rename to tests/src/test/resources/Advance.sol diff --git a/tests/src/main/resources/SafeMath.sol b/tests/src/test/resources/SafeMath.sol similarity index 100% rename from tests/src/main/resources/SafeMath.sol rename to tests/src/test/resources/SafeMath.sol diff --git a/tests/src/main/resources/SimpleData.abi b/tests/src/test/resources/SimpleData.abi similarity index 100% rename from tests/src/main/resources/SimpleData.abi rename to tests/src/test/resources/SimpleData.abi diff --git a/tests/src/main/resources/SimpleData.bin b/tests/src/test/resources/SimpleData.bin similarity index 100% rename from tests/src/main/resources/SimpleData.bin rename to tests/src/test/resources/SimpleData.bin diff --git a/tests/src/main/resources/SimpleData.sol b/tests/src/test/resources/SimpleData.sol similarity index 100% rename from tests/src/main/resources/SimpleData.sol rename to tests/src/test/resources/SimpleData.sol diff --git a/tests/src/main/resources/Token.abi b/tests/src/test/resources/Token.abi similarity index 100% rename from tests/src/main/resources/Token.abi rename to tests/src/test/resources/Token.abi diff --git a/tests/src/main/resources/Token.bin b/tests/src/test/resources/Token.bin similarity index 100% rename from tests/src/main/resources/Token.bin rename to tests/src/test/resources/Token.bin diff --git a/tests/src/main/resources/Token.sol b/tests/src/test/resources/Token.sol similarity index 100% rename from tests/src/main/resources/Token.sol rename to tests/src/test/resources/Token.sol diff --git a/tests/src/main/resources/config.json b/tests/src/test/resources/config.json similarity index 100% rename from tests/src/main/resources/config.json rename to tests/src/test/resources/config.json diff --git a/tests/src/main/resources/config.properties.example b/tests/src/test/resources/config.properties.example similarity index 79% rename from tests/src/main/resources/config.properties.example rename to tests/src/test/resources/config.properties.example index 443106e2..0ae71868 100644 --- a/tests/src/main/resources/config.properties.example +++ b/tests/src/test/resources/config.properties.example @@ -7,10 +7,10 @@ TestPrivateKey1=0x02b8f18d92354b055bd02cd51449b05b7b97104931f10485d1df905e4e70fb TestAddress1=0xbac68e5cb986ead0253e0632da1131a0a96efa18 TestPrivateKey2=0xefa5668cd759045918ee7ef88d43c1beed32622f98ea76711e1a8f59ddeb0fe9 TestAddress2=0x1c6eebf136ee234caff3a95e0d9d22e40c9ac4ca -TokenSolidity=tests/src/main/resources/Token.sol -TokenBin=tests/src/main/resources/Token.bin -TokenAbi=tests/src/main/resources/Token.abi -SimpleDataBin=tests/src/main/resources/SimpleData.bin +TokenSolidity=src/test/resources/Token.sol +TokenBin=src/test/resources/Token.bin +TokenAbi=src/test/resources/Token.abi +SimpleDataBin=src/test/resources/SimpleData.bin QuotaForTransfer=21000 QuotaForDeployment=10000000 AdminPrivateKey=0x5a0257a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6 From a181d47ddfd016ef4c656bb5e36c33e07be40ee5 Mon Sep 17 00:00:00 2001 From: chenhao Date: Wed, 9 Oct 2019 10:18:16 +0800 Subject: [PATCH 5/9] fix test-result error and fix log-max errpr in travis --- .travis.yml | 4 ++-- scripts/run-system-test.sh | 2 +- scripts/run.sh | 1 + scripts/travis-upload-test-report-to-gh-pages.sh | 2 +- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index c70c2666..de975037 100644 --- a/.travis.yml +++ b/.travis.yml @@ -26,8 +26,8 @@ cache: before_script: # upgrade gradle to 5.0 - - wget http://services.gradle.org/distributions/gradle-5.0-all.zip > /dev/null - - unzip gradle-5.0-all.zip + - wget http://services.gradle.org/distributions/gradle-5.0-all.zip > debug.log + - unzip gradle-5.0-all.zip > debug.log - ./gradle-5.0/bin/gradle -v script: bash ./scripts/run.sh diff --git a/scripts/run-system-test.sh b/scripts/run-system-test.sh index ce67a282..ad2d1f04 100644 --- a/scripts/run-system-test.sh +++ b/scripts/run-system-test.sh @@ -33,7 +33,7 @@ cat pom.xml | grep -A 3 ">core<" # install cita-cli and run test rm -r target/* -make install-cita-cli +make install-cita-cli > ${DEBUG_LOG_PATH} mvn test -Dtest=com.cryptape.function.sdkcase.** MAVEN_TEST_RESULT=$? diff --git a/scripts/run.sh b/scripts/run.sh index 689b6557..532cdb83 100644 --- a/scripts/run.sh +++ b/scripts/run.sh @@ -3,6 +3,7 @@ if [ ${TEST_TYPE} == UT ]; then echo "run unit test" bash scripts/run-unit-test.sh + exit $? fi if [ ${TEST_TYPE} == ST ]; then diff --git a/scripts/travis-upload-test-report-to-gh-pages.sh b/scripts/travis-upload-test-report-to-gh-pages.sh index b5994664..52c64696 100755 --- a/scripts/travis-upload-test-report-to-gh-pages.sh +++ b/scripts/travis-upload-test-report-to-gh-pages.sh @@ -12,7 +12,7 @@ echo "Starting to update gh-pages" # gh page info owner_name=`echo $TRAVIS_REPO_SLUG|cut -d / -f 1` repo_name=`echo $TRAVIS_REPO_SLUG|cut -d / -f 2` -gh_pages_url="https://cryptape.github.io/cita-sdk-java/" +gh_pages_url="https://cryptape.github.io/cita-sdk-java" test_report_url="$gh_pages_url/reports/${TRAVIS_JOB_ID}/" test_result_mark="×" From a1047843bdd4ebd2669feb296639da6fed9667ef Mon Sep 17 00:00:00 2001 From: chenhao Date: Mon, 14 Oct 2019 11:34:44 +0800 Subject: [PATCH 6/9] to support param-having func in permission manager --- .../java/com/cryptape/cita/abi/FunctionEncoder.java | 2 +- .../java/com/cryptape/cita/protocol/system/Util.java | 12 +++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/abi/src/main/java/com/cryptape/cita/abi/FunctionEncoder.java b/abi/src/main/java/com/cryptape/cita/abi/FunctionEncoder.java index 363757b5..340a86f2 100644 --- a/abi/src/main/java/com/cryptape/cita/abi/FunctionEncoder.java +++ b/abi/src/main/java/com/cryptape/cita/abi/FunctionEncoder.java @@ -88,7 +88,7 @@ static String buildMethodSignature(String methodName, List parameters) { return result.toString(); } - static String buildMethodId(String methodSignature) { + public static String buildMethodId(String methodSignature) { byte[] input = methodSignature.getBytes(); byte[] hash = Hash.sha3(input); return Numeric.toHexString(hash).substring(0, 10); diff --git a/core/src/main/java/com/cryptape/cita/protocol/system/Util.java b/core/src/main/java/com/cryptape/cita/protocol/system/Util.java index aaa686c2..707981dd 100644 --- a/core/src/main/java/com/cryptape/cita/protocol/system/Util.java +++ b/core/src/main/java/com/cryptape/cita/protocol/system/Util.java @@ -1,5 +1,7 @@ package com.cryptape.cita.protocol.system; +import static com.cryptape.cita.abi.FunctionEncoder.buildMethodId; + import java.math.BigInteger; import java.util.Collections; import java.util.Random; @@ -68,9 +70,13 @@ static String addUpTo64Hex(String hexStr) { } - static String generateFunSig(String funcName) { - Function func = new Function(funcName, Collections.emptyList(), Collections.emptyList()); - return FunctionEncoder.encode(func); + static String generateFunSig(String funcSignature) { + if(funcSignature.contains("(") && funcSignature.contains(")")){ + return buildMethodId(funcSignature); + } else { + // compatible with old ways of using, only the func name + return buildMethodId(funcSignature+"()"); + } } static String hexToASCII(String hexValue) { From efefdd40834d149560f4c4622dd91913211a8699 Mon Sep 17 00:00:00 2001 From: chenhao Date: Mon, 14 Oct 2019 12:53:19 +0800 Subject: [PATCH 7/9] add notes for permission name param length --- .../com/cryptape/cita/protocol/system/CITAjSystemContract.java | 1 + 1 file changed, 1 insertion(+) diff --git a/core/src/main/java/com/cryptape/cita/protocol/system/CITAjSystemContract.java b/core/src/main/java/com/cryptape/cita/protocol/system/CITAjSystemContract.java index d6e267b7..442d887f 100644 --- a/core/src/main/java/com/cryptape/cita/protocol/system/CITAjSystemContract.java +++ b/core/src/main/java/com/cryptape/cita/protocol/system/CITAjSystemContract.java @@ -253,6 +253,7 @@ public List getQuotas(String from) throws IOException { return resultList; } + // the name param length, Chinese should not exceed 16 and English should not exceed 32 public String newPermission( String name, List addrs, From 6bb0861abfe0fb22b3742c602f063b8ea8871523 Mon Sep 17 00:00:00 2001 From: chenhao Date: Wed, 16 Oct 2019 18:49:46 +0800 Subject: [PATCH 8/9] fix testnet url --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 87898020..1db57727 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ gradle shadowJar ### CITA Test net Use CITA test net (recommended): -https://node.cryptape.com is provided as a test net. +https://testnet.citahub.com is provided as a test net. Or build your own CITA net: Please find more information in [CITA](https://github.com/cryptape/cita). @@ -230,7 +230,7 @@ gradle shadowJar ### CITA 测试网络 使用 CITA 测试网络(推荐): -https://node.cryptape.com +https://testnet.citahub.com 或者可以部署你自己的 CITA: 如果需要了解怎么部署 CITA 网络,请查阅[CITA](https://github.com/cryptape/cita)。 From 523bcbac96f1cc29606a066c064fc3cb272e208e Mon Sep 17 00:00:00 2001 From: chenhao Date: Fri, 25 Oct 2019 11:58:46 +0800 Subject: [PATCH 9/9] update version and changelog and readme for v1.0.0 --- CHANGELOG.md | 16 ++++++++++++++++ README.md | 8 ++++---- build.gradle | 4 ++-- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aadabd51..5ebc8483 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ All notable changes to this project will be documented in this file. +# [v1.0.0](https://github.com/cryptape/cita-sdk-java/compare/v0.25.0...v1.0.0) (2019-08-28) + +### Added + +* add group manager RPC requests +* add matrix system test in travis + +### Fixed +* fix test net url +* fix inPermission method not support function having parameters +* fix unit test in test module + +### Documented +* add introduction document + + # [v0.25.0](https://github.com/cryptape/cita-sdk-java/compare/v0.24.1...v0.25.0) (2019-08-27) ### Feature diff --git a/README.md b/README.md index 1db57727..b21a28a7 100644 --- a/README.md +++ b/README.md @@ -29,12 +29,12 @@ maven com.cryptape.cita core - 0.25.0 + 1.0.0 ``` Gradle ``` -compile 'com.cryptape.cita:core:0.25.0' +compile 'com.cryptape.cita:core:1.0.0' ``` Install manually @@ -208,12 +208,12 @@ Gradle 5.0 com.cryptape.cita core - 0.25.0 + 1.0.0 ``` Gradle ``` -compile 'com.cryptape.cita:core:0.25.0' +compile 'com.cryptape.cita:core:1.0.0' ``` 手动安装 diff --git a/build.gradle b/build.gradle index 89617197..c52b3959 100644 --- a/build.gradle +++ b/build.gradle @@ -49,7 +49,7 @@ allprojects { targetCompatibility = 1.8 group 'com.cryptape.cita' - version '0.25.0' + version '1.0.0' apply plugin: 'java' apply plugin: 'jacoco' @@ -145,7 +145,7 @@ configure(subprojects.findAll { it.name != 'integration-tests' }) { publications { mavenJava(MavenPublication) { groupId 'com.cryptape.cita' - version '0.25.0' + version '1.0.0' from components.java artifact sourcesJar {