From 47a089d6876cb1b3e1ca4e00630c1731c681bbba Mon Sep 17 00:00:00 2001 From: daxinzang1 <280474930@qq.com> Date: Fri, 26 Nov 2021 16:59:54 +0800 Subject: [PATCH 01/24] Add get witness size auto --- .../common/client/utils/HttpMethed.java | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java index b3cad3f11dd..0e2dc8f1ca1 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java @@ -47,6 +47,25 @@ public class HttpMethed { static JSONObject responseContent; static JSONObject signResponseContent; static JSONObject transactionApprovedListContent; + public static volatile Integer witnessNum; + + /** + * constructor. + */ + private static volatile String httpnode = Configuration.getByPath("testng.conf") + .getStringList("httpnode.ip.list") + .get(1); + + /** + * constructor. + */ + public static Integer getWitnessNum() { + if (null == witnessNum) { + witnessNum = parseResponseContent(listwitnesses(httpnode)).getJSONArray("witnesses").size(); + } + + return witnessNum; + } static { PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(); @@ -2318,7 +2337,8 @@ public static void waitToProduceOneBlockFromSolidity(String httpNode, String htt Integer currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); Integer nextBlockNum = 0; Integer times = 0; - while (nextBlockNum <= currentBlockNum && times++ <= 3) { + while (nextBlockNum < currentBlockNum + ((getWitnessNum() >= 27) + ? 18 : (getWitnessNum() * 70 / 100)) && times++ < getWitnessNum()) { response = HttpMethed.getNowBlockFromSolidity(httpSolidityNode); responseContent = HttpMethed.parseResponseContent(response); responseContent = HttpMethed From 1b15e7cb32ec662e23a74b72347d9387539004ed Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Wed, 1 Dec 2021 11:44:55 +0800 Subject: [PATCH 02/24] add --- .../common/client/utils/HttpMethed.java | 518 +++---- .../common/client/utils/JsonRpcBase.java | 31 +- .../common/client/utils/PublicMethed.java | 1336 +++++++++-------- .../dailybuild/jsonrpc/Accounts002.java | 373 +++++ 4 files changed, 1333 insertions(+), 925 deletions(-) create mode 100644 framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java index 0e2dc8f1ca1..b8e4b2dcf8a 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java @@ -39,9 +39,9 @@ public class HttpMethed { static HttpPost httppost; static HttpResponse response; static Integer connectionTimeout = Configuration.getByPath("testng.conf") - .getInt("defaultParameter.httpConnectionTimeout"); + .getInt("defaultParameter.httpConnectionTimeout"); static Integer soTimeout = Configuration.getByPath("testng.conf") - .getInt("defaultParameter.httpSoTimeout"); + .getInt("defaultParameter.httpSoTimeout"); static String transactionString; static String transactionSignString; static JSONObject responseContent; @@ -53,8 +53,8 @@ public class HttpMethed { * constructor. */ private static volatile String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list") - .get(1); + .getStringList("httpnode.ip.list") + .get(1); /** * constructor. @@ -79,7 +79,7 @@ public static Integer getWitnessNum() { * constructor. */ public static HttpResponse updateAccount(String httpNode, byte[] updateAccountAddress, - String accountName, String fromKey) { + String accountName, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/updateaccount"; JsonObject userBaseObj2 = new JsonObject(); @@ -103,13 +103,13 @@ public static HttpResponse updateAccount(String httpNode, byte[] updateAccountAd * constructor. */ public static HttpResponse setAccountId(String httpNode, byte[] setAccountIdAddress, - String accountId, Boolean visable, String fromKey) { + String accountId, Boolean visable, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/setaccountid"; JsonObject userBaseObj2 = new JsonObject(); userBaseObj2.addProperty("account_id", accountId); userBaseObj2.addProperty("owner_address", - Base58.encode58Check(PublicMethed.getFinalAddress(fromKey))); + Base58.encode58Check(PublicMethed.getFinalAddress(fromKey))); userBaseObj2.addProperty("visible", visable); response = createConnect(requestUrl, userBaseObj2); transactionString = EntityUtils.toString(response.getEntity()); @@ -130,7 +130,7 @@ public static HttpResponse setAccountId(String httpNode, byte[] setAccountIdAddr * constructor. */ public static HttpResponse updateWitness(String httpNode, byte[] witnessAddress, String updateUrl, - String fromKey) { + String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/updatewitness"; JsonObject userBaseObj2 = new JsonObject(); @@ -155,7 +155,7 @@ public static HttpResponse updateWitness(String httpNode, byte[] witnessAddress, * constructor. */ public static HttpResponse voteWitnessAccount(String httpNode, byte[] ownerAddress, - JsonArray voteArray, String fromKey) { + JsonArray voteArray, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/votewitnessaccount"; JsonObject userBaseObj2 = new JsonObject(); @@ -180,7 +180,7 @@ public static HttpResponse voteWitnessAccount(String httpNode, byte[] ownerAddre * constructor. */ public static HttpResponse createAccount(String httpNode, byte[] ownerAddress, - byte[] accountAddress, String fromKey) { + byte[] accountAddress, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/createaccount"; JsonObject userBaseObj2 = new JsonObject(); @@ -246,7 +246,7 @@ public static HttpResponse withdrawBalance(String httpNode, byte[] witnessAddres * constructor. */ public static HttpResponse sendCoin(String httpNode, byte[] fromAddress, byte[] toAddress, - Long amount, String fromKey) { + Long amount, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; JsonObject userBaseObj2 = new JsonObject(); @@ -269,7 +269,7 @@ public static HttpResponse sendCoin(String httpNode, byte[] fromAddress, byte[] * constructor. */ public static HttpResponse sendCoin(String httpNode, byte[] fromAddress, byte[] toAddress, - Long amount, Integer permissionId, String[] managerKeys) { + Long amount, Integer permissionId, String[] managerKeys) { try { final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; JsonObject userBaseObj2 = new JsonObject(); @@ -308,7 +308,7 @@ public static HttpResponse sendCoin(String httpNode, byte[] fromAddress, byte[] * constructor. */ public static String sendCoin(String httpNode, byte[] fromAddress, byte[] toAddress, Long amount, - String notes, String fromKey) { + String notes, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; JsonObject userBaseObj2 = new JsonObject(); @@ -333,7 +333,7 @@ public static String sendCoin(String httpNode, byte[] fromAddress, byte[] toAddr * constructor. */ public static String sendCoinGetTxid(String httpNode, byte[] fromAddress, byte[] toAddress, - Long amount, String fromKey) { + Long amount, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; JsonObject userBaseObj2 = new JsonObject(); @@ -360,7 +360,7 @@ public static String sendCoinGetTxid(String httpNode, byte[] fromAddress, byte[] * constructor. */ public static HttpResponse createProposal(String httpNode, byte[] ownerAddress, Long proposalKey, - Long proposalValue, String fromKey) { + Long proposalValue, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/proposalcreate"; JsonObject userBaseObj2 = new JsonObject(); @@ -388,7 +388,7 @@ public static HttpResponse createProposal(String httpNode, byte[] ownerAddress, * constructor. */ public static HttpResponse approvalProposal(String httpNode, byte[] ownerAddress, - Integer proposalId, Boolean isAddApproval, String fromKey) { + Integer proposalId, Boolean isAddApproval, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/proposalapprove"; JsonObject userBaseObj2 = new JsonObject(); @@ -413,7 +413,7 @@ public static HttpResponse approvalProposal(String httpNode, byte[] ownerAddress * constructor. */ public static HttpResponse deleteProposal(String httpNode, byte[] ownerAddress, - Integer proposalId, String fromKey) { + Integer proposalId, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/proposaldelete"; JsonObject userBaseObj2 = new JsonObject(); @@ -468,7 +468,7 @@ public static HttpResponse getChainParameters(String httpNode) { * constructor. */ public static HttpResponse accountPermissionUpdate(String httpNode, byte[] ownerAddress, - JsonObject ownerObject, JsonObject witnessObject, JsonObject activesObject, String fromKey) { + JsonObject ownerObject, JsonObject witnessObject, JsonObject activesObject, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/accountpermissionupdate"; JsonObject userBaseObj2 = new JsonObject(); @@ -497,8 +497,8 @@ public static HttpResponse accountPermissionUpdate(String httpNode, byte[] owner * constructor. */ public static HttpResponse exchangeCreate(String httpNode, byte[] ownerAddress, - String firstTokenId, Long firstTokenBalance, String secondTokenId, Long secondTokenBalance, - String fromKey) { + String firstTokenId, Long firstTokenBalance, String secondTokenId, Long secondTokenBalance, + String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/exchangecreate"; JsonObject userBaseObj2 = new JsonObject(); @@ -523,7 +523,7 @@ public static HttpResponse exchangeCreate(String httpNode, byte[] ownerAddress, * constructor. */ public static HttpResponse exchangeInject(String httpNode, byte[] ownerAddress, - Integer exchangeId, String tokenId, Long quant, String fromKey) { + Integer exchangeId, String tokenId, Long quant, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/exchangeinject"; JsonObject userBaseObj2 = new JsonObject(); @@ -547,7 +547,7 @@ public static HttpResponse exchangeInject(String httpNode, byte[] ownerAddress, * constructor. */ public static HttpResponse exchangeWithdraw(String httpNode, byte[] ownerAddress, - Integer exchangeId, String tokenId, Long quant, String fromKey) { + Integer exchangeId, String tokenId, Long quant, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/exchangewithdraw"; JsonObject userBaseObj2 = new JsonObject(); @@ -571,7 +571,7 @@ public static HttpResponse exchangeWithdraw(String httpNode, byte[] ownerAddress * constructor. */ public static HttpResponse exchangeTransaction(String httpNode, byte[] ownerAddress, - Integer exchangeId, String tokenId, Long quant, Long expected, String fromKey) { + Integer exchangeId, String tokenId, Long quant, Long expected, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/exchangetransaction"; JsonObject userBaseObj2 = new JsonObject(); @@ -597,9 +597,9 @@ public static HttpResponse exchangeTransaction(String httpNode, byte[] ownerAddr * constructor. */ public static HttpResponse assetIssue(String httpNode, byte[] ownerAddress, String name, - String abbr, Long totalSupply, Integer trxNum, Integer num, Long startTime, Long endTime, - Integer voteScore, Integer precision, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, String fromKey) { + String abbr, Long totalSupply, Integer trxNum, Integer num, Long startTime, Long endTime, + Integer voteScore, Integer precision, String description, String url, Long freeAssetNetLimit, + Long publicFreeAssetNetLimit, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/createassetissue"; JsonObject userBaseObj2 = new JsonObject(); @@ -633,7 +633,7 @@ public static HttpResponse assetIssue(String httpNode, byte[] ownerAddress, Stri * constructor. */ public static HttpResponse transferAsset(String httpNode, byte[] ownerAddress, byte[] toAddress, - String assetIssueById, Long amount, String fromKey) { + String assetIssueById, Long amount, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/transferasset"; JsonObject userBaseObj2 = new JsonObject(); @@ -657,9 +657,9 @@ public static HttpResponse transferAsset(String httpNode, byte[] ownerAddress, b * constructor. */ public static HttpResponse deployContract(String httpNode, String name, String abi, - String bytecode, Long bandwidthLimit, Long feeLimit, Integer consumeUserResourcePercent, - Long originEnergyLimit, Long callValue, Integer tokenId, Long tokenValue, byte[] ownerAddress, - String fromKey) { + String bytecode, Long bandwidthLimit, Long feeLimit, Integer consumeUserResourcePercent, + Long originEnergyLimit, Long callValue, Integer tokenId, Long tokenValue, byte[] ownerAddress, + String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/deploycontract"; JsonObject userBaseObj2 = new JsonObject(); @@ -693,9 +693,9 @@ public static HttpResponse deployContract(String httpNode, String name, String a * constructor. */ public static String deployContractGetTxid(String httpNode, String name, String abi, - String bytecode, Long bandwidthLimit, Long feeLimit, Integer consumeUserResourcePercent, - Long originEnergyLimit, Long callValue, Integer tokenId, Long tokenValue, byte[] ownerAddress, - String fromKey) { + String bytecode, Long bandwidthLimit, Long feeLimit, Integer consumeUserResourcePercent, + Long originEnergyLimit, Long callValue, Integer tokenId, Long tokenValue, byte[] ownerAddress, + String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/deploycontract"; JsonObject userBaseObj2 = new JsonObject(); @@ -732,9 +732,9 @@ public static String deployContractGetTxid(String httpNode, String name, String * constructor. */ public static HttpResponse deployContractGetTxidWithTooBigLong(String httpNode, String name, - String abi, String bytecode, Long bandwidthLimit, Long feeLimit, - Integer consumeUserResourcePercent, Long originEnergyLimit, Long callValue, Integer tokenId, - Long tokenValue, byte[] ownerAddress, String fromKey) { + String abi, String bytecode, Long bandwidthLimit, Long feeLimit, + Integer consumeUserResourcePercent, Long originEnergyLimit, Long callValue, Integer tokenId, + Long tokenValue, byte[] ownerAddress, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/deploycontract"; @@ -772,8 +772,8 @@ public static HttpResponse deployContractGetTxidWithTooBigLong(String httpNode, * constructor. */ public static String triggerContractGetTxid(String httpNode, byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter, Long feeLimit, - Long callValue, Integer tokenId, Long tokenValue, String fromKey) { + String contractAddress, String functionSelector, String parameter, Long feeLimit, + Long callValue, Integer tokenId, Long tokenValue, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/triggersmartcontract"; JsonObject userBaseObj2 = new JsonObject(); @@ -790,7 +790,7 @@ public static String triggerContractGetTxid(String httpNode, byte[] ownerAddress logger.info(transactionString); transactionSignString = gettransactionsign(httpNode, - parseStringContent(transactionString).getString("transaction"), fromKey); + parseStringContent(transactionString).getString("transaction"), fromKey); logger.info(transactionSignString); response = broadcastTransaction(httpNode, transactionSignString); } catch (Exception e) { @@ -807,11 +807,11 @@ public static String triggerContractGetTxid(String httpNode, byte[] ownerAddress * constructor. */ public static String triggerContractGetTxidWithVisibleTrue(String httpNode, String ownerAddress, - String contractAddress, String functionSelector, String parameter, Long feeLimit, - Long callValue, Integer tokenId, Long tokenValue, String fromKey) { + String contractAddress, String functionSelector, String parameter, Long feeLimit, + Long callValue, Integer tokenId, Long tokenValue, String fromKey) { return triggerContractGetTxidWithVisibleTrue(httpNode, "", ownerAddress, - contractAddress, functionSelector, parameter, feeLimit, callValue, tokenId, tokenValue, - fromKey); + contractAddress, functionSelector, parameter, feeLimit, callValue, tokenId, tokenValue, + fromKey); } @@ -819,10 +819,10 @@ public static String triggerContractGetTxidWithVisibleTrue(String httpNode, Stri * constructor. */ public static String triggerContractGetTxidWithVisibleTrue(String httpNode, - String anotherHttpNode, - String ownerAddress, - String contractAddress, String functionSelector, String parameter, Long feeLimit, - Long callValue, Integer tokenId, Long tokenValue, String fromKey) { + String anotherHttpNode, + String ownerAddress, + String contractAddress, String functionSelector, String parameter, Long feeLimit, + Long callValue, Integer tokenId, Long tokenValue, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/triggersmartcontract"; JsonObject userBaseObj2 = new JsonObject(); @@ -840,7 +840,7 @@ public static String triggerContractGetTxidWithVisibleTrue(String httpNode, logger.info(transactionString); transactionSignString = gettransactionsign(httpNode, - parseStringContent(transactionString).getString("transaction"), fromKey); + parseStringContent(transactionString).getString("transaction"), fromKey); logger.info(transactionSignString); response = broadcastTransaction(httpNode, transactionSignString); if (!anotherHttpNode.isEmpty()) { @@ -860,8 +860,8 @@ public static String triggerContractGetTxidWithVisibleTrue(String httpNode, * constructor. */ public static HttpResponse triggerConstantContract(String httpNode, byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter, Long feeLimit, - String fromKey) { + String contractAddress, String functionSelector, String parameter, Long feeLimit, + String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/triggerconstantcontract"; JsonObject userBaseObj2 = new JsonObject(); @@ -885,7 +885,7 @@ public static HttpResponse triggerConstantContract(String httpNode, byte[] owner * constructor. */ public static HttpResponse triggerConstantContract(String httpNode, byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter) { + String contractAddress, String functionSelector, String parameter) { try { final String requestUrl = "http://" + httpNode + "/wallet/triggerconstantcontract"; JsonObject userBaseObj2 = new JsonObject(); @@ -906,11 +906,11 @@ public static HttpResponse triggerConstantContract(String httpNode, byte[] owner * constructor. */ public static HttpResponse triggerConstantContractFromSolidity(String httSoliditypNode, - byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter) { + byte[] ownerAddress, + String contractAddress, String functionSelector, String parameter) { try { final String requestUrl = - "http://" + httSoliditypNode + "/walletsolidity/triggerconstantcontract"; + "http://" + httSoliditypNode + "/walletsolidity/triggerconstantcontract"; JsonObject userBaseObj2 = new JsonObject(); userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); userBaseObj2.addProperty("contract_address", contractAddress); @@ -929,8 +929,8 @@ public static HttpResponse triggerConstantContractFromSolidity(String httSolidit * constructor. */ public static HttpResponse triggerConstantContractFromPbft(String httpPbftNode, - byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter) { + byte[] ownerAddress, + String contractAddress, String functionSelector, String parameter) { try { final String requestUrl = "http://" + httpPbftNode + "/walletpbft/triggerconstantcontract"; JsonObject userBaseObj2 = new JsonObject(); @@ -951,7 +951,7 @@ public static HttpResponse triggerConstantContractFromPbft(String httpPbftNode, * constructor. */ public static HttpResponse participateAssetIssue(String httpNode, byte[] toAddress, - byte[] ownerAddress, String assetIssueById, Long amount, String fromKey) { + byte[] ownerAddress, String assetIssueById, Long amount, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/participateassetissue"; JsonObject userBaseObj2 = new JsonObject(); @@ -977,7 +977,7 @@ public static HttpResponse participateAssetIssue(String httpNode, byte[] toAddre * constructor. */ public static HttpResponse updateAssetIssue(String httpNode, byte[] ownerAddress, - String description, String url, Long newLimit, Long newPublicLimit, String fromKey) { + String description, String url, Long newLimit, Long newPublicLimit, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/updateasset"; JsonObject userBaseObj2 = new JsonObject(); @@ -1018,16 +1018,16 @@ public static Boolean verificationResult(HttpResponse response) { * constructor. */ public static HttpResponse freezeBalance(String httpNode, byte[] ownerAddress, Long frozenBalance, - Integer frozenDuration, Integer resourceCode, String fromKey) { + Integer frozenDuration, Integer resourceCode, String fromKey) { return freezeBalance(httpNode, ownerAddress, frozenBalance, frozenDuration, resourceCode, null, - fromKey); + fromKey); } /** * constructor. */ public static HttpResponse freezeBalance(String httpNode, byte[] ownerAddress, Long frozenBalance, - Integer frozenDuration, Integer resourceCode, byte[] receiverAddress, String fromKey) { + Integer frozenDuration, Integer resourceCode, byte[] receiverAddress, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/freezebalance"; JsonObject userBaseObj2 = new JsonObject(); @@ -1062,7 +1062,7 @@ public static HttpResponse freezeBalance(String httpNode, byte[] ownerAddress, L * constructor. */ public static HttpResponse unFreezeBalance(String httpNode, byte[] ownerAddress, - Integer resourceCode, String fromKey) { + Integer resourceCode, String fromKey) { return unFreezeBalance(httpNode, ownerAddress, resourceCode, null, fromKey); } @@ -1070,7 +1070,7 @@ public static HttpResponse unFreezeBalance(String httpNode, byte[] ownerAddress, * constructor. */ public static HttpResponse unFreezeBalance(String httpNode, byte[] ownerAddress, - Integer resourceCode, byte[] receiverAddress, String fromKey) { + Integer resourceCode, byte[] receiverAddress, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/unfreezebalance"; JsonObject userBaseObj2 = new JsonObject(); @@ -1103,7 +1103,7 @@ public static HttpResponse unFreezeBalance(String httpNode, byte[] ownerAddress, * constructor. */ public static String gettransactionsign(String httpNode, String transactionString, - String privateKey) { + String privateKey) { try { String requestUrl = "http://" + httpNode + "/wallet/gettransactionsign"; JsonObject userBaseObj2 = new JsonObject(); @@ -1126,7 +1126,7 @@ public static HttpResponse broadcastTransaction(String httpNode, String transact try { String requestUrl = "http://" + httpNode + "/wallet/broadcasttransaction"; httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); httppost = new HttpPost(requestUrl); httppost.setHeader("Content-type", "application/json; charset=utf-8"); @@ -1148,7 +1148,7 @@ public static HttpResponse broadcastTransaction(String httpNode, String transact Integer times = 0; while (times++ <= 10 && responseContent.getString("code") != null && responseContent - .getString("code").equalsIgnoreCase("SERVER_BUSY")) { + .getString("code").equalsIgnoreCase("SERVER_BUSY")) { logger.info("retry num are " + times); try { response = httpClient.execute(httppost); @@ -1208,7 +1208,7 @@ public static HttpResponse getAccountById(String httpNode, String accountId, Boo * constructor. */ public static HttpResponse getAccountByIdFromSolidity(String httpSolidityNode, String accountId, - Boolean visable) { + Boolean visable) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getaccountbyid"; JsonObject userBaseObj2 = new JsonObject(); @@ -1227,7 +1227,7 @@ public static HttpResponse getAccountByIdFromSolidity(String httpSolidityNode, S * constructor. */ public static HttpResponse getAccountByIdFromPbft(String httpSolidityNode, String accountId, - Boolean visable) { + Boolean visable) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getaccountbyid"; JsonObject userBaseObj2 = new JsonObject(); @@ -1336,7 +1336,7 @@ public static HttpResponse getSignWeight(String httpNode, String transactionSign try { String requestUrl = "http://" + httpNode + "/wallet/getsignweight"; httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); httppost = new HttpPost(requestUrl); httppost.setHeader("Content-type", "application/json; charset=utf-8"); @@ -1361,11 +1361,11 @@ public static HttpResponse getSignWeight(String httpNode, String transactionSign * constructor. */ public static HttpResponse getTransactionApprovedList(String httpNode, - String transactionSignString) { + String transactionSignString) { try { String requestUrl = "http://" + httpNode + "/wallet/getapprovedlist"; httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); httppost = new HttpPost(requestUrl); httppost.setHeader("Content-type", "application/json; charset=utf-8"); @@ -1592,7 +1592,7 @@ public static HttpResponse getExchangeById(String httpNode, Integer exchangeId) * constructor. */ public static HttpResponse getExchangeByIdFromSolidity(String httpSolidityNode, - Integer exchangeId) { + Integer exchangeId) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getexchangebyid"; JsonObject userBaseObj2 = new JsonObject(); @@ -1662,7 +1662,7 @@ public static HttpResponse getAssetIssueListByName(String httpNode, String name) * constructor. */ public static HttpResponse getAssetIssueListByNameFromSolidity(String httpSolidityNode, - String name) { + String name) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuelistbyname"; JsonObject userBaseObj2 = new JsonObject(); @@ -1680,7 +1680,7 @@ public static HttpResponse getAssetIssueListByNameFromSolidity(String httpSolidi * constructor. */ public static HttpResponse getAssetIssueListByNameFromPbft(String httpPbftNode, - String name) { + String name) { try { String requestUrl = "http://" + httpPbftNode + "/walletpbft/getassetissuelistbyname"; JsonObject userBaseObj2 = new JsonObject(); @@ -1715,7 +1715,7 @@ public static HttpResponse getAssetIssueById(String httpNode, String assetIssueI * constructor. */ public static HttpResponse getAssetIssueByIdFromSolidity(String httpSolidityNode, - String assetIssueId) { + String assetIssueId) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuebyid"; JsonObject userBaseObj2 = new JsonObject(); @@ -1733,7 +1733,7 @@ public static HttpResponse getAssetIssueByIdFromSolidity(String httpSolidityNode * constructor. */ public static HttpResponse getAssetIssueByIdFromPbft(String httpSolidityNode, - String assetIssueId) { + String assetIssueId) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getassetissuebyid"; JsonObject userBaseObj2 = new JsonObject(); @@ -1848,7 +1848,7 @@ public static HttpResponse getTransactionInfoById(String httpNode, String txid, * constructor. */ public static HttpResponse getTransactionInfoByIdFromSolidity(String httpSolidityNode, - String txid) { + String txid) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/gettransactioninfobyid"; JsonObject userBaseObj2 = new JsonObject(); @@ -1900,10 +1900,10 @@ public static HttpResponse getTransactionInfoByBlocknum(String httpNode, long bl * constructor. */ public static HttpResponse getTransactionInfoByBlocknumFromSolidity(String httpSolidityNode, - long blocknum) { + long blocknum) { try { String requestUrl = - "http://" + httpSolidityNode + "/walletsolidity/gettransactioninfobyblocknum"; + "http://" + httpSolidityNode + "/walletsolidity/gettransactioninfobyblocknum"; JsonObject userBaseObj2 = new JsonObject(); userBaseObj2.addProperty("num", blocknum); response = createConnect(requestUrl, userBaseObj2); @@ -1919,10 +1919,10 @@ public static HttpResponse getTransactionInfoByBlocknumFromSolidity(String httpS * constructor. */ public static HttpResponse getTransactionCountByBlocknumFromSolidity(String httpSolidityNode, - long blocknum) { + long blocknum) { try { String requestUrl = - "http://" + httpSolidityNode + "/walletsolidity/gettransactioncountbyblocknum"; + "http://" + httpSolidityNode + "/walletsolidity/gettransactioncountbyblocknum"; JsonObject userBaseObj2 = new JsonObject(); userBaseObj2.addProperty("num", blocknum); response = createConnect(requestUrl, userBaseObj2); @@ -1938,10 +1938,10 @@ public static HttpResponse getTransactionCountByBlocknumFromSolidity(String http * constructor. */ public static HttpResponse getTransactionCountByBlocknumFromPbft(String httpSolidityNode, - long blocknum) { + long blocknum) { try { String requestUrl = - "http://" + httpSolidityNode + "/walletpbft/gettransactioncountbyblocknum"; + "http://" + httpSolidityNode + "/walletpbft/gettransactioncountbyblocknum"; JsonObject userBaseObj2 = new JsonObject(); userBaseObj2.addProperty("num", blocknum); response = createConnect(requestUrl, userBaseObj2); @@ -1958,7 +1958,7 @@ public static HttpResponse getTransactionCountByBlocknumFromPbft(String httpSoli * constructor. */ public static HttpResponse getTransactionsFromThisFromSolidity(String httpSolidityNode, - byte[] fromAddress, long offset, long limit) { + byte[] fromAddress, long offset, long limit) { try { Map map1 = new HashMap(); Map map = new HashMap(); @@ -1982,7 +1982,7 @@ public static HttpResponse getTransactionsFromThisFromSolidity(String httpSolidi * constructor. */ public static HttpResponse getTransactionsToThisFromSolidity(String httpSolidityNode, - byte[] toAddress, long offset, long limit) { + byte[] toAddress, long offset, long limit) { try { Map map1 = new HashMap(); Map map = new HashMap(); @@ -2117,7 +2117,7 @@ public static HttpResponse getAccountReource(String httpNode, byte[] queryAddres * constructor. */ public static HttpResponse getAccountBalance(String httpNode, - byte[] queryAddress, Integer blockNum, String blockHash) { + byte[] queryAddress, Integer blockNum, String blockHash) { try { final String requestUrl = "http://" + httpNode + "/wallet/getaccountbalance"; JsonObject addressObj = new JsonObject(); @@ -2249,7 +2249,7 @@ public static Long getNowBlockNum(String httpNode) { return null; } return parseResponseContent(response).getJSONObject("block_header").getJSONObject("raw_data") - .getLong("number"); + .getLong("number"); } /** @@ -2265,7 +2265,7 @@ public static Long getNowBlockNumOnSolidity(String httpNode) { return null; } return parseResponseContent(response).getJSONObject("block_header").getJSONObject("raw_data") - .getLong("number"); + .getLong("number"); } @@ -2315,7 +2315,7 @@ public static void waitToProduceOneBlock(String httpNode) { response = HttpMethed.getNowBlock(httpNode); responseContent = HttpMethed.parseResponseContent(response); responseContent = HttpMethed - .parseStringContent(responseContent.get("block_header").toString()); + .parseStringContent(responseContent.get("block_header").toString()); responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); try { @@ -2337,14 +2337,16 @@ public static void waitToProduceOneBlockFromSolidity(String httpNode, String htt Integer currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); Integer nextBlockNum = 0; Integer times = 0; - while (nextBlockNum < currentBlockNum + ((getWitnessNum() >= 27) - ? 18 : (getWitnessNum() * 70 / 100)) && times++ < getWitnessNum()) { + while (nextBlockNum <= currentBlockNum && times++ < ((getWitnessNum() >= 27) + ? 18 : (getWitnessNum() * 70 / 100))) { response = HttpMethed.getNowBlockFromSolidity(httpSolidityNode); responseContent = HttpMethed.parseResponseContent(response); responseContent = HttpMethed - .parseStringContent(responseContent.get("block_header").toString()); + .parseStringContent(responseContent.get("block_header").toString()); responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); + logger.info("currentBlockNum1:"+currentBlockNum); + logger.info("nextBlockNum:"+nextBlockNum); try { Thread.sleep(3500); } catch (InterruptedException e) { @@ -2368,7 +2370,7 @@ public static void waitToProduceOneBlockFromPbft(String httpNode, String httpSol response = HttpMethed.getNowBlockFromPbft(httpSolidityNode); responseContent = HttpMethed.parseResponseContent(response); responseContent = HttpMethed - .parseStringContent(responseContent.get("block_header").toString()); + .parseStringContent(responseContent.get("block_header").toString()); responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); try { @@ -2462,7 +2464,7 @@ public static HttpResponse getBlockByNumFromPbft(String httpSolidityNode, Intege * constructor. */ public static HttpResponse getBlockByLimitNext(String httpNode, Integer startNum, - Integer endNum) { + Integer endNum) { try { String requestUrl = "http://" + httpNode + "/wallet/getblockbylimitnext"; JsonObject userBaseObj2 = new JsonObject(); @@ -2481,7 +2483,7 @@ public static HttpResponse getBlockByLimitNext(String httpNode, Integer startNum * constructor. */ public static HttpResponse getBlockByLimitNextFromSolidity(String httpNode, Integer startNum, - Integer endNum) { + Integer endNum) { try { String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbylimitnext"; JsonObject userBaseObj2 = new JsonObject(); @@ -2500,7 +2502,7 @@ public static HttpResponse getBlockByLimitNextFromSolidity(String httpNode, Inte * constructor. */ public static HttpResponse getBlockByLimitNextFromPbft(String httpNode, Integer startNum, - Integer endNum) { + Integer endNum) { try { String requestUrl = "http://" + httpNode + "/walletpbft/getblockbylimitnext"; JsonObject userBaseObj2 = new JsonObject(); @@ -2640,7 +2642,7 @@ public static HttpResponse getBlockByIdFromPbft(String httpNode, String blockId) * constructor. */ public static HttpResponse getDelegatedResource(String httpNode, byte[] fromAddress, - byte[] toAddress) { + byte[] toAddress) { try { String requestUrl = "http://" + httpNode + "/wallet/getdelegatedresource"; JsonObject userBaseObj2 = new JsonObject(); @@ -2659,7 +2661,7 @@ public static HttpResponse getDelegatedResource(String httpNode, byte[] fromAddr * constructor. */ public static HttpResponse getDelegatedResourceFromSolidity(String httpSolidityNode, - byte[] fromAddress, byte[] toAddress) { + byte[] fromAddress, byte[] toAddress) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getdelegatedresource"; JsonObject userBaseObj2 = new JsonObject(); @@ -2678,7 +2680,7 @@ public static HttpResponse getDelegatedResourceFromSolidity(String httpSolidityN * constructor. */ public static HttpResponse getDelegatedResourceFromPbft(String httpSolidityNode, - byte[] fromAddress, byte[] toAddress) { + byte[] fromAddress, byte[] toAddress) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getdelegatedresource"; JsonObject userBaseObj2 = new JsonObject(); @@ -2698,7 +2700,7 @@ public static HttpResponse getDelegatedResourceFromPbft(String httpSolidityNode, * constructor. */ public static HttpResponse getDelegatedResourceAccountIndex(String httpNode, - byte[] queryAddress) { + byte[] queryAddress) { try { String requestUrl = "http://" + httpNode + "/wallet/getdelegatedresourceaccountindex"; JsonObject userBaseObj2 = new JsonObject(); @@ -2716,10 +2718,10 @@ public static HttpResponse getDelegatedResourceAccountIndex(String httpNode, * constructor. */ public static HttpResponse getDelegatedResourceAccountIndexFromSolidity(String httpSolidityNode, - byte[] queryAddress) { + byte[] queryAddress) { try { String requestUrl = - "http://" + httpSolidityNode + "/walletsolidity/getdelegatedresourceaccountindex"; + "http://" + httpSolidityNode + "/walletsolidity/getdelegatedresourceaccountindex"; JsonObject userBaseObj2 = new JsonObject(); userBaseObj2.addProperty("value", ByteArray.toHexString(queryAddress)); response = createConnect(requestUrl, userBaseObj2); @@ -2735,10 +2737,10 @@ public static HttpResponse getDelegatedResourceAccountIndexFromSolidity(String h * constructor. */ public static HttpResponse getDelegatedResourceAccountIndexFromPbft(String httpSolidityNode, - byte[] queryAddress) { + byte[] queryAddress) { try { String requestUrl = - "http://" + httpSolidityNode + "/walletpbft/getdelegatedresourceaccountindex"; + "http://" + httpSolidityNode + "/walletpbft/getdelegatedresourceaccountindex"; JsonObject userBaseObj2 = new JsonObject(); userBaseObj2.addProperty("value", ByteArray.toHexString(queryAddress)); response = createConnect(requestUrl, userBaseObj2); @@ -2764,7 +2766,7 @@ public static HttpResponse createConnect(String url) { public static HttpResponse createConnect(String url, JsonObject requestBody) { try { httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); httppost = new HttpPost(url); httppost.setHeader("Content-type", "application/json; charset=utf-8"); @@ -2816,7 +2818,7 @@ public static HttpResponse createConnectForGet(String url) { public static HttpResponse createConnectForShieldTrc20(String url, JSONObject requestBody) { try { httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); httppost = new HttpPost(url); httppost.setHeader("Content-type", "application/json; charset=utf-8"); @@ -2848,7 +2850,7 @@ public static Long createConnectForResponse(String url, JsonObject requestBody, Long duration = 0L; while (times-- > 0) { httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); httppost = new HttpPost(url); httppost.setHeader("Content-type", "application/json; charset=utf-8"); @@ -2883,10 +2885,10 @@ public static Long createConnectForResponse(String url, JsonObject requestBody, public static HttpResponse createConnect1(String url, JSONObject requestBody) { try { httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout * 10000); + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout * 10000); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout * 10000); httppost = new HttpPost(url); httppost.setHeader("Content-type", "application/json; charset=utf-8"); @@ -2926,7 +2928,7 @@ public static HttpResponse getAssetissueList(String httpNode) { * constructor. */ public static Long getAssetIssueValue(String httpNode, byte[] accountAddress, - String assetIssueId) { + String assetIssueId) { response = HttpMethed.getAccount(httpNode, accountAddress); responseContent = HttpMethed.parseResponseContent(response); JSONArray assetV2 = responseContent.getJSONArray("assetV2"); @@ -2978,7 +2980,7 @@ public static HttpResponse getAssetIssueListFromPbft(String httpSolidityNode) { * constructor. */ public static HttpResponse getPaginatedAssetissueList(String httpNode, Integer offset, - Integer limit) { + Integer limit) { try { final String requestUrl = "http://" + httpNode + "/wallet/getpaginatedassetissuelist"; JsonObject userBaseObj2 = new JsonObject(); @@ -2998,10 +3000,10 @@ public static HttpResponse getPaginatedAssetissueList(String httpNode, Integer o * constructor. */ public static HttpResponse getPaginatedAssetissueListFromSolidity(String httpSolidityNode, - Integer offset, Integer limit) { + Integer offset, Integer limit) { try { String requestUrl = - "http://" + httpSolidityNode + "/walletsolidity/getpaginatedassetissuelist"; + "http://" + httpSolidityNode + "/walletsolidity/getpaginatedassetissuelist"; JsonObject userBaseObj2 = new JsonObject(); userBaseObj2.addProperty("offset", offset); userBaseObj2.addProperty("limit", limit); @@ -3018,7 +3020,7 @@ public static HttpResponse getPaginatedAssetissueListFromSolidity(String httpSol * constructor. */ public static HttpResponse getPaginatedAssetissueListFromPbft(String httpSolidityNode, - Integer offset, Integer limit) { + Integer offset, Integer limit) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getpaginatedassetissuelist"; JsonObject userBaseObj2 = new JsonObject(); @@ -3038,7 +3040,7 @@ public static HttpResponse getPaginatedAssetissueListFromPbft(String httpSolidit * constructor. */ public static HttpResponse getPaginatedProposalList(String httpNode, Integer offset, - Integer limit) { + Integer limit) { try { String requestUrl = "http://" + httpNode + "/wallet/getpaginatedproposallist"; JsonObject userBaseObj2 = new JsonObject(); @@ -3058,7 +3060,7 @@ public static HttpResponse getPaginatedProposalList(String httpNode, Integer off * constructor. */ public static HttpResponse getPaginatedExchangeList(String httpNode, Integer offset, - Integer limit) { + Integer limit) { try { String requestUrl = "http://" + httpNode + "/wallet/getpaginatedexchangelist"; JsonObject userBaseObj2 = new JsonObject(); @@ -3078,7 +3080,7 @@ public static HttpResponse getPaginatedExchangeList(String httpNode, Integer off * constructor. */ public static HttpResponse updateSetting(String httpNode, byte[] ownerAddress, - String contractAddress, Integer consumeUserResourcePercent, String fromKey) { + String contractAddress, Integer consumeUserResourcePercent, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/updatesetting"; JsonObject userBaseObj2 = new JsonObject(); @@ -3105,7 +3107,7 @@ public static HttpResponse updateSetting(String httpNode, byte[] ownerAddress, * constructor. */ public static HttpResponse updateEnergyLimit(String httpNode, byte[] ownerAddress, - String contractAddress, Integer originEnergyLimit, String fromKey) { + String contractAddress, Integer originEnergyLimit, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/updateenergylimit"; JsonObject userBaseObj2 = new JsonObject(); @@ -3167,7 +3169,7 @@ public static HttpResponse generateAddress(String httpNode) { public static HttpResponse getTransactionCountByBlocknum(String httpNode, long blocknum) { try { String requestUrl = - "http://" + httpNode + "/wallet/gettransactioncountbyblocknum"; + "http://" + httpNode + "/wallet/gettransactioncountbyblocknum"; JsonObject userBaseObj2 = new JsonObject(); userBaseObj2.addProperty("num", blocknum); response = createConnect(requestUrl, userBaseObj2); @@ -3202,7 +3204,7 @@ public static HttpResponse validateAddress(String httpNode, String address) { * constructor. */ public static HttpResponse easyTransfer(String httpNode, String value, byte[] toAddress, - Long amount) { + Long amount) { try { final String requestUrl = "http://" + httpNode + "/wallet/easytransfer"; JsonObject userBaseObj2 = new JsonObject(); @@ -3225,7 +3227,7 @@ public static HttpResponse easyTransfer(String httpNode, String value, byte[] to * constructor. */ public static HttpResponse easyTransferByPrivate(String httpNode, String privateKey, - byte[] toAddress, Long amount) { + byte[] toAddress, Long amount) { try { final String requestUrl = "http://" + httpNode + "/wallet/easytransferbyprivate"; JsonObject userBaseObj2 = new JsonObject(); @@ -3248,7 +3250,7 @@ public static HttpResponse easyTransferByPrivate(String httpNode, String private * constructor. */ public static HttpResponse easyTransferAsset(String httpNode, String value, byte[] toAddress, - Long amount, String assetId) { + Long amount, String assetId) { try { final String requestUrl = "http://" + httpNode + "/wallet/easytransferasset"; JsonObject userBaseObj2 = new JsonObject(); @@ -3272,7 +3274,7 @@ public static HttpResponse easyTransferAsset(String httpNode, String value, byte * constructor. */ public static HttpResponse easyTransferAssetByPrivate(String httpNode, String privateKey, - byte[] toAddress, Long amount, String assetId) { + byte[] toAddress, Long amount, String assetId) { try { final String requestUrl = "http://" + httpNode + "/wallet/easytransferassetbyprivate"; JsonObject userBaseObj2 = new JsonObject(); @@ -3402,7 +3404,7 @@ public static String str2hex(String str) { * constructor. */ public static HttpResponse clearABiGetTxid(String httpNode, byte[] ownerAddress, - String contractAddress, String fromKey) { + String contractAddress, String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/clearabi"; JsonObject userBaseObj2 = new JsonObject(); @@ -3492,8 +3494,8 @@ public static Optional generateShieldAddress(String httpnode) * constructor. */ public static List addShieldOutputList(String httpNode, - List shieldOutList, String shieldToAddress, String toAmountString, - String menoString) { + List shieldOutList, String shieldToAddress, String toAmountString, + String menoString) { String shieldAddress = shieldToAddress; String amountString = toAmountString; if (menoString.equals("null")) { @@ -3671,13 +3673,13 @@ public static HttpResponse getZenPaymentAddress(String httpNode, String ivk, Str * constructor. */ public static HttpResponse getMerkleTreeVoucherInfo(String httpNode, String hash, Integer index, - int blockNum) { + int blockNum) { try { String requestUrl = "http://" + httpNode + "/wallet/getmerkletreevoucherinfo"; JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); jsonObjectWarp.put("out_points", - Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) - .put("block_num", blockNum); + Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) + .put("block_num", blockNum); String jsonStr = jsonObjectWarp.toJSONString(); JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); logger.info("jsonObj:" + jsonObj.toString()); @@ -3694,13 +3696,13 @@ public static HttpResponse getMerkleTreeVoucherInfo(String httpNode, String hash * constructor. */ public static HttpResponse getMerkleTreeVoucherInfoFromSolidity(String httpSolidityNode, - String hash, Integer index, int blockNum) { + String hash, Integer index, int blockNum) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmerkletreevoucherinfo"; JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); jsonObjectWarp.put("out_points", - Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) - .put("block_num", blockNum); + Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) + .put("block_num", blockNum); String jsonStr = jsonObjectWarp.toJSONString(); JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); logger.info("jsonObj:" + jsonObj.toString()); @@ -3717,13 +3719,13 @@ public static HttpResponse getMerkleTreeVoucherInfoFromSolidity(String httpSolid * constructor. */ public static HttpResponse getMerkleTreeVoucherInfoFromPbft(String httpSolidityNode, String hash, - Integer index, int blockNum) { + Integer index, int blockNum) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getmerkletreevoucherinfo"; JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); jsonObjectWarp.put("out_points", - Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) - .put("block_num", blockNum); + Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) + .put("block_num", blockNum); String jsonStr = jsonObjectWarp.toJSONString(); JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); logger.info("jsonObj:" + jsonObj.toString()); @@ -3741,9 +3743,9 @@ public static HttpResponse getMerkleTreeVoucherInfoFromPbft(String httpSolidityN * constructor. */ public static HttpResponse sendShieldCoin(String httpNode, byte[] publicZenTokenOwnerAddress, - long fromAmount, ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx, - List shieldOutputList, byte[] publicZenTokenToAddress, long toAmount, - String zenTokenOwnerKey) { + long fromAmount, ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx, + List shieldOutputList, byte[] publicZenTokenToAddress, long toAmount, + String zenTokenOwnerKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/createshieldedtransaction"; @@ -3754,7 +3756,7 @@ public static HttpResponse sendShieldCoin(String httpNode, byte[] publicZenToken } if (shieldAddressInfo != null) { HttpResponse expandedSpendingKey = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.getSk())); + .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.getSk())); responseContent = HttpMethed.parseResponseContent(expandedSpendingKey); HttpMethed.printJsonContent(responseContent); String ovk = responseContent.getString("ovk"); @@ -3763,18 +3765,18 @@ public static HttpResponse sendShieldCoin(String httpNode, byte[] publicZenToken map.put("ovk", ovk); response = HttpMethed - .getMerkleTreeVoucherInfo(httpNode, noteTx.getTrxId(), noteTx.getIndex(), 1); + .getMerkleTreeVoucherInfo(httpNode, noteTx.getTrxId(), noteTx.getIndex(), 1); responseContent = HttpMethed.parseResponseContent(response); JSONArray vouchers = responseContent.getJSONArray("vouchers"); JSONArray paths = responseContent.getJSONArray("paths"); List shieldedSpends = Lists.newArrayList(new JSONObjectWarp().put("note", - new JSONObjectWarp().put("value", noteTx.getValue()) - .put("payment_address", noteTx.getPaymentAddress()) - .put("rcm", ByteArray.toHexString(noteTx.getR())) - .put("memo", ByteArray.toHexString(noteTx.getMemo()))) - .put("alpha", ByteArray.toHexString(org.tron.core.zen.note.Note.generateR())) - .put("voucher", Lists.newArrayList(vouchers)).put("path", Lists.newArrayList(paths))); + new JSONObjectWarp().put("value", noteTx.getValue()) + .put("payment_address", noteTx.getPaymentAddress()) + .put("rcm", ByteArray.toHexString(noteTx.getR())) + .put("memo", ByteArray.toHexString(noteTx.getMemo()))) + .put("alpha", ByteArray.toHexString(org.tron.core.zen.note.Note.generateR())) + .put("voucher", Lists.newArrayList(vouchers)).put("path", Lists.newArrayList(paths))); map.put("shielded_spends", shieldedSpends); } else { @@ -3795,7 +3797,7 @@ public static HttpResponse sendShieldCoin(String httpNode, byte[] publicZenToken noteInfo.put("payment_address", shieldOutputList.get(i).getPaymentAddress()); noteInfo.put("rcm", shieldOutputList.get(i).getRcm().toStringUtf8()); noteInfo.put("memo", - ByteArray.toHexString(shieldOutputList.get(i).getMemo().toStringUtf8().getBytes())); + ByteArray.toHexString(shieldOutputList.get(i).getMemo().toStringUtf8().getBytes())); final Map note = new HashMap(); note.put("note", noteInfo); noteList.add(note); @@ -3828,12 +3830,12 @@ public static HttpResponse sendShieldCoin(String httpNode, byte[] publicZenToken * constructor. */ public static Boolean getSpendResult(String httpNode, ShieldAddressInfo shieldAddressInfo, - ShieldNoteInfo noteTx) { + ShieldNoteInfo noteTx) { try { final String requestUrl = "http://" + httpNode + "/wallet/isspend"; response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); responseContent = HttpMethed.parseResponseContent(response); String ask = responseContent.getString("ask"); response = HttpMethed.getAkFromAsk(httpNode, ask); @@ -3847,9 +3849,9 @@ public static Boolean getSpendResult(String httpNode, ShieldAddressInfo shieldAd jsonObjectWarp.put("nk", responseContent.getString("value")); jsonObjectWarp.put("note", new JSONObjectWarp().put("value", noteTx.getValue()) - .put("payment_address", noteTx.getPaymentAddress()) - .put("rcm", ByteArray.toHexString(noteTx.getR())) - .put("memo", ByteArray.toHexString(noteTx.getMemo()))).put("txid", noteTx.getTrxId()); + .put("payment_address", noteTx.getPaymentAddress()) + .put("rcm", ByteArray.toHexString(noteTx.getR())) + .put("memo", ByteArray.toHexString(noteTx.getMemo()))).put("txid", noteTx.getTrxId()); String jsonStr = jsonObjectWarp.toJSONString(); JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); @@ -3860,7 +3862,7 @@ public static Boolean getSpendResult(String httpNode, ShieldAddressInfo shieldAd HttpMethed.printJsonContent(responseContent); String jsonString = responseContent.toJSONString(); if (jsonString.contains("result") && (responseContent.getString("result").equals("true") - && responseContent.getString("message").equals("Input note has been spent"))) { + && responseContent.getString("message").equals("Input note has been spent"))) { return Boolean.TRUE; } else { return Boolean.FALSE; @@ -3876,12 +3878,12 @@ public static Boolean getSpendResult(String httpNode, ShieldAddressInfo shieldAd * constructor. */ public static Boolean getSpendResultFromSolidity(String httpNode, String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx) { + ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx) { try { final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/isspend"; response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); responseContent = HttpMethed.parseResponseContent(response); String ask = responseContent.getString("ask"); response = HttpMethed.getAkFromAsk(httpNode, ask); @@ -3895,9 +3897,9 @@ public static Boolean getSpendResultFromSolidity(String httpNode, String httpSol jsonObjectWarp.put("nk", responseContent.getString("value")); jsonObjectWarp.put("note", new JSONObjectWarp().put("value", noteTx.getValue()) - .put("payment_address", noteTx.getPaymentAddress()) - .put("rcm", ByteArray.toHexString(noteTx.getR())) - .put("memo", ByteArray.toHexString(noteTx.getMemo()))).put("txid", noteTx.getTrxId()); + .put("payment_address", noteTx.getPaymentAddress()) + .put("rcm", ByteArray.toHexString(noteTx.getR())) + .put("memo", ByteArray.toHexString(noteTx.getMemo()))).put("txid", noteTx.getTrxId()); String jsonStr = jsonObjectWarp.toJSONString(); JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); @@ -3908,7 +3910,7 @@ public static Boolean getSpendResultFromSolidity(String httpNode, String httpSol HttpMethed.printJsonContent(responseContent); String jsonString = responseContent.toJSONString(); if (jsonString.contains("result") && (responseContent.getString("result").equals("true") - && responseContent.getString("message").equals("Input note has been spent"))) { + && responseContent.getString("message").equals("Input note has been spent"))) { return Boolean.TRUE; } else { return Boolean.FALSE; @@ -3924,13 +3926,13 @@ public static Boolean getSpendResultFromSolidity(String httpNode, String httpSol * constructor. */ public static Boolean getSpendResultFromPbft(String httpNode, String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx) { + ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx) { try { final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/isspend"; final JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); responseContent = HttpMethed.parseResponseContent(response); String ask = responseContent.getString("ask"); final String nsk = responseContent.getString("nsk"); @@ -3941,9 +3943,9 @@ public static Boolean getSpendResultFromPbft(String httpNode, String httpSolidit responseContent = HttpMethed.parseResponseContent(response); jsonObjectWarp.put("nk", responseContent.getString("value")); jsonObjectWarp.put("note", new JSONObjectWarp().put("value", noteTx.getValue()) - .put("payment_address", noteTx.getPaymentAddress()) - .put("rcm", ByteArray.toHexString(noteTx.getR())) - .put("memo", ByteArray.toHexString(noteTx.getMemo()))).put("txid", noteTx.getTrxId()); + .put("payment_address", noteTx.getPaymentAddress()) + .put("rcm", ByteArray.toHexString(noteTx.getR())) + .put("memo", ByteArray.toHexString(noteTx.getMemo()))).put("txid", noteTx.getTrxId()); String jsonStr = jsonObjectWarp.toJSONString(); JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); logger.info("jsonObj:" + jsonObj.toString()); @@ -3952,7 +3954,7 @@ public static Boolean getSpendResultFromPbft(String httpNode, String httpSolidit HttpMethed.printJsonContent(responseContent); String jsonString = responseContent.toJSONString(); if (jsonString.contains("result") && (responseContent.getString("result").equals("true") - && responseContent.getString("message").equals("Input note has been spent"))) { + && responseContent.getString("message").equals("Input note has been spent"))) { return Boolean.TRUE; } else { return Boolean.FALSE; @@ -3968,14 +3970,14 @@ public static Boolean getSpendResultFromPbft(String httpNode, String httpSolidit * constructor. */ public static List scanNoteByOvkFromPbft(String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo) { + ShieldAddressInfo shieldAddressInfo) { try { response = HttpMethed.getNowBlockFromPbft(httpSolidityNode); responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); String blockHeaderString = responseContent.getString("block_header"); String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); + .toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -3999,11 +4001,11 @@ public static List scanNoteByOvkFromPbft(String httpSolidityNode String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); + HttpMethed.parseStringContent(noteString).getString("payment_address")); noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); shieldNoteInfoList.add(noteTx); @@ -4021,14 +4023,14 @@ public static List scanNoteByOvkFromPbft(String httpSolidityNode * constructor. */ public static List scanNoteByIvk(String httpNode, - ShieldAddressInfo shieldAddressInfo) { + ShieldAddressInfo shieldAddressInfo) { try { response = HttpMethed.getNowBlock(httpNode); responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); String blockHeaderString = responseContent.getString("block_header"); String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); + .toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -4054,11 +4056,11 @@ public static List scanNoteByIvk(String httpNode, String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); + HttpMethed.parseStringContent(noteString).getString("payment_address")); noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); shieldNoteInfoList.add(noteTx); @@ -4076,14 +4078,14 @@ public static List scanNoteByIvk(String httpNode, * constructor. */ public static List scanNoteByIvkFromSolidity(String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo) { + ShieldAddressInfo shieldAddressInfo) { try { response = HttpMethed.getNowBlockFromSolidity(httpSolidityNode); responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); String blockHeaderString = responseContent.getString("block_header"); String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); + .toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -4108,11 +4110,11 @@ public static List scanNoteByIvkFromSolidity(String httpSolidity String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); + HttpMethed.parseStringContent(noteString).getString("payment_address")); noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); shieldNoteInfoList.add(noteTx); @@ -4129,14 +4131,14 @@ public static List scanNoteByIvkFromSolidity(String httpSolidity * constructor. */ public static List scanNoteByIvkFromPbft(String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo) { + ShieldAddressInfo shieldAddressInfo) { try { response = HttpMethed.getNowBlockFromPbft(httpSolidityNode); responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); String blockHeaderString = responseContent.getString("block_header"); String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); + .toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -4160,11 +4162,11 @@ public static List scanNoteByIvkFromPbft(String httpSolidityNode String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); + HttpMethed.parseStringContent(noteString).getString("payment_address")); noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); shieldNoteInfoList.add(noteTx); @@ -4182,10 +4184,10 @@ public static List scanNoteByIvkFromPbft(String httpSolidityNode * constructor. */ public static List scanAndMarkNoteByIvk(String httpNode, - ShieldAddressInfo shieldAddressInfo) { + ShieldAddressInfo shieldAddressInfo) { try { response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); responseContent = HttpMethed.parseResponseContent(response); String ask = responseContent.getString("ask"); String nsk = responseContent.getString("nsk"); @@ -4202,7 +4204,7 @@ public static List scanAndMarkNoteByIvk(String httpNode, HttpMethed.printJsonContent(responseContent); String blockHeaderString = responseContent.getString("block_header"); String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); + .toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -4230,11 +4232,11 @@ public static List scanAndMarkNoteByIvk(String httpNode, String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); + HttpMethed.parseStringContent(noteString).getString("payment_address")); noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); noteTx.setIsSpend(HttpMethed.parseStringContent(noteTxs).getBoolean("is_spend")); noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); @@ -4252,10 +4254,10 @@ public static List scanAndMarkNoteByIvk(String httpNode, * constructor. */ public static List scanAndMarkNoteByIvkFromSolidity(String httpNode, - String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { + String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { try { response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); responseContent = HttpMethed.parseResponseContent(response); String ask = responseContent.getString("ask"); String nsk = responseContent.getString("nsk"); @@ -4272,7 +4274,7 @@ public static List scanAndMarkNoteByIvkFromSolidity(String httpN HttpMethed.printJsonContent(responseContent); String blockHeaderString = responseContent.getString("block_header"); String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); + .toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -4280,7 +4282,7 @@ public static List scanAndMarkNoteByIvkFromSolidity(String httpN } final String requestUrl = - "http://" + httpSolidityNode + "/walletsolidity/scanandmarknotebyivk"; + "http://" + httpSolidityNode + "/walletsolidity/scanandmarknotebyivk"; JsonObject userBaseObj2 = new JsonObject(); userBaseObj2.addProperty("start_block_index", startBlockNum); userBaseObj2.addProperty("end_block_index", currentBlockNum); @@ -4301,11 +4303,11 @@ public static List scanAndMarkNoteByIvkFromSolidity(String httpN String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); + HttpMethed.parseStringContent(noteString).getString("payment_address")); noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); noteTx.setIsSpend(HttpMethed.parseStringContent(noteTxs).getBoolean("is_spend")); noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); @@ -4323,10 +4325,10 @@ public static List scanAndMarkNoteByIvkFromSolidity(String httpN * constructor. */ public static List scanAndMarkNoteByIvkFromPbft(String httpNode, - String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { + String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { try { response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); responseContent = HttpMethed.parseResponseContent(response); String ask = responseContent.getString("ask"); String nsk = responseContent.getString("nsk"); @@ -4343,7 +4345,7 @@ public static List scanAndMarkNoteByIvkFromPbft(String httpNode, HttpMethed.printJsonContent(responseContent); String blockHeaderString = responseContent.getString("block_header"); String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); + .toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -4369,11 +4371,11 @@ public static List scanAndMarkNoteByIvkFromPbft(String httpNode, String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); + HttpMethed.parseStringContent(noteString).getString("payment_address")); noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); noteTx.setIsSpend(HttpMethed.parseStringContent(noteTxs).getBoolean("is_spend")); noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); @@ -4392,14 +4394,14 @@ public static List scanAndMarkNoteByIvkFromPbft(String httpNode, * constructor. */ public static List scanNoteByOvk(String httpNode, - ShieldAddressInfo shieldAddressInfo) { + ShieldAddressInfo shieldAddressInfo) { try { response = HttpMethed.getNowBlock(httpNode); responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); String blockHeaderString = responseContent.getString("block_header"); String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); + .toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -4424,11 +4426,11 @@ public static List scanNoteByOvk(String httpNode, String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); + HttpMethed.parseStringContent(noteString).getString("payment_address")); noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); shieldNoteInfoList.add(noteTx); @@ -4445,14 +4447,14 @@ public static List scanNoteByOvk(String httpNode, * constructor. */ public static List scanNoteByOvkFromSolidity(String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo) { + ShieldAddressInfo shieldAddressInfo) { try { response = HttpMethed.getNowBlockFromSolidity(httpSolidityNode); responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); String blockHeaderString = responseContent.getString("block_header"); String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); + .toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -4477,11 +4479,11 @@ public static List scanNoteByOvkFromSolidity(String httpSolidity String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); + HttpMethed.parseStringContent(noteString).getString("payment_address")); noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); shieldNoteInfoList.add(noteTx); @@ -4498,13 +4500,13 @@ public static List scanNoteByOvkFromSolidity(String httpSolidity * constructor. */ public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String httpSolidityNode, - String httpPbftNode, byte[] publicZenTokenOwnerAddress, long fromAmount, - ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx, - List shieldOutputList, byte[] publicZenTokenToAddress, long toAmount, - String zenTokenOwnerKey) { + String httpPbftNode, byte[] publicZenTokenOwnerAddress, long fromAmount, + ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx, + List shieldOutputList, byte[] publicZenTokenToAddress, long toAmount, + String zenTokenOwnerKey) { try { final String requestUrl = - "http://" + httpNode + "/wallet/createshieldedtransactionwithoutspendauthsig"; + "http://" + httpNode + "/wallet/createshieldedtransactionwithoutspendauthsig"; Map map = new HashMap(); if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { @@ -4515,7 +4517,7 @@ public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String http byte[] alpha = null; if (shieldAddressInfo != null) { HttpResponse expandedSpendingKey = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.getSk())); + .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.getSk())); responseContent = HttpMethed.parseResponseContent(expandedSpendingKey); HttpMethed.printJsonContent(responseContent); map.put("nsk", responseContent.getString("nsk")); @@ -4528,16 +4530,16 @@ public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String http logger.info("noteTx.getTrxId():" + noteTx.getTrxId()); HttpMethed.response = HttpMethed - .getMerkleTreeVoucherInfoFromSolidity(httpSolidityNode, noteTx.getTrxId(), - noteTx.getIndex(), 1); + .getMerkleTreeVoucherInfoFromSolidity(httpSolidityNode, noteTx.getTrxId(), + noteTx.getIndex(), 1); HttpMethed.responseContent = HttpMethed.parseResponseContent(HttpMethed.response); HttpMethed.printJsonContent(responseContent); final JSONArray vouchers = HttpMethed.responseContent.getJSONArray("vouchers"); final JSONArray paths = HttpMethed.responseContent.getJSONArray("paths"); HttpMethed.response = HttpMethed - .getMerkleTreeVoucherInfoFromPbft(httpPbftNode, noteTx.getTrxId(), noteTx.getIndex(), - 1); + .getMerkleTreeVoucherInfoFromPbft(httpPbftNode, noteTx.getTrxId(), noteTx.getIndex(), + 1); HttpMethed.responseContent = HttpMethed.parseResponseContent(HttpMethed.response); HttpMethed.printJsonContent(responseContent); JSONArray vouchersPbft = HttpMethed.responseContent.getJSONArray("vouchers"); @@ -4546,12 +4548,12 @@ public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String http alpha = org.tron.core.zen.note.Note.generateR(); List shieldedSpends = Lists.newArrayList(new JSONObjectWarp().put("note", - new JSONObjectWarp().put("value", noteTx.getValue()) - .put("payment_address", noteTx.getPaymentAddress()) - .put("rcm", ByteArray.toHexString(noteTx.getR())) - .put("memo", ByteArray.toHexString(noteTx.getMemo()))) - .put("alpha", ByteArray.toHexString(alpha)).put("voucher", Lists.newArrayList(vouchers)) - .put("path", Lists.newArrayList(paths))); + new JSONObjectWarp().put("value", noteTx.getValue()) + .put("payment_address", noteTx.getPaymentAddress()) + .put("rcm", ByteArray.toHexString(noteTx.getR())) + .put("memo", ByteArray.toHexString(noteTx.getMemo()))) + .put("alpha", ByteArray.toHexString(alpha)).put("voucher", Lists.newArrayList(vouchers)) + .put("path", Lists.newArrayList(paths))); map.put("shielded_spends", shieldedSpends); } else { @@ -4571,7 +4573,7 @@ public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String http noteInfo.put("payment_address", shieldOutputList.get(i).getPaymentAddress()); noteInfo.put("rcm", shieldOutputList.get(i).getRcm().toStringUtf8()); noteInfo.put("memo", - ByteArray.toHexString(shieldOutputList.get(i).getMemo().toStringUtf8().getBytes())); + ByteArray.toHexString(shieldOutputList.get(i).getMemo().toStringUtf8().getBytes())); final Map note = new HashMap(); note.put("note", noteInfo); noteList.add(note); @@ -4597,7 +4599,7 @@ public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String http String spendauthsigUrl = "http://" + httpNode + "/wallet/createspendauthsig"; JSONObjectWarp spendauthsigJson = new JSONObjectWarp().put("ask", ask) - .put("alpha", ByteArray.toHexString(alpha)).put("tx_hash", hash); + .put("alpha", ByteArray.toHexString(alpha)).put("tx_hash", hash); String spendauthsigStr = spendauthsigJson.toJSONString(); JsonObject spendauthsigObj = new JsonParser().parse(spendauthsigStr).getAsJsonObject(); logger.info("spendauthsigObj:" + spendauthsigObj.toString()); @@ -4608,8 +4610,8 @@ public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String http JSONObject jsonObject = HttpMethed.parseStringContent(transactionString); jsonObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0) - .getJSONObject("parameter").getJSONObject("value").getJSONArray("spend_description") - .getJSONObject(0).put("spend_authority_signature", spendauthsig); + .getJSONObject("parameter").getJSONObject("value").getJSONArray("spend_description") + .getJSONObject(0).put("spend_authority_signature", spendauthsig); transactionString = jsonObject.toString(); logger.info("transactionString2:" + transactionString); } @@ -4633,7 +4635,7 @@ public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String http * constructor. */ public static void freedResource(String httpNode, byte[] fromAddress, byte[] toAddress, - String fromKey) { + String fromKey) { long balance = HttpMethed.getBalance(httpNode, fromAddress); //System.out.println("剩余资源:" + balance); sendCoin(httpNode, fromAddress, toAddress, balance - 50000, fromKey); @@ -4645,7 +4647,7 @@ public static void freedResource(String httpNode, byte[] fromAddress, byte[] toA * constructor. */ public static HttpResponse updateBrokerage(String httpNode, byte[] ownerAddress, Long brokerage, - String fromKey) { + String fromKey) { try { final String requestUrl = "http://" + httpNode + "/wallet/updateBrokerage"; JsonObject userBaseObj2 = new JsonObject(); @@ -4668,7 +4670,7 @@ public static HttpResponse updateBrokerage(String httpNode, byte[] ownerAddress, * constructor. */ public static HttpResponse updateBrokerageOnVisible(String httpNode, byte[] ownerAddress, - Long brokerage, String fromKey, String visible) { + Long brokerage, String fromKey, String visible) { try { final String requestUrl = "http://" + httpNode + "/wallet/updateBrokerage"; JsonObject userBaseObj2 = new JsonObject(); @@ -4810,7 +4812,7 @@ public static HttpResponse getRewardOnVisible(String httpNode, byte[] address, S * constructor. */ public static HttpResponse getRewardFromSolidityOnVisible(String httpSolidityNode, byte[] address, - String visible) { + String visible) { try { final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getReward"; JsonObject userBaseObj2 = new JsonObject(); @@ -4834,7 +4836,7 @@ public static HttpResponse getRewardFromSolidityOnVisible(String httpSolidityNod * constructor. */ public static HttpResponse getBrokerageOnVisible(String httpNode, byte[] address, - String visible) { + String visible) { try { final String requestUrl = "http://" + httpNode + "/wallet/getBrokerage"; JsonObject userBaseObj2 = new JsonObject(); @@ -4858,7 +4860,7 @@ public static HttpResponse getBrokerageOnVisible(String httpNode, byte[] address * constructor. */ public static HttpResponse getBrokerageFromSolidityOnVisible(String httpSolidityNode, - byte[] address, String visible) { + byte[] address, String visible) { try { final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getBrokerage"; JsonObject userBaseObj2 = new JsonObject(); @@ -4899,9 +4901,9 @@ public static HttpResponse getBrokerageFromPbft(String httpSolidityNode, byte[] * constructor. */ public static String marketSellAssetGetTxId(String httpNode, byte[] ownerAddress, - String sellTokenId, - Long sellTokenQuantity, String buyTokenId, Long buyTokenQuantity, String fromKey, - String visible) { + String sellTokenId, + Long sellTokenQuantity, String buyTokenId, Long buyTokenQuantity, String fromKey, + String visible) { try { final String requestUrl = "http://" + httpNode + "/wallet/marketsellasset"; JsonObject userBaseObj2 = new JsonObject(); @@ -4954,7 +4956,7 @@ public static HttpResponse getMarketOrderById(String httpNode, String orderId, S * constructor. */ public static HttpResponse getMarketOrderByIdFromSolidity(String httpSolidityNode, String orderId, - String visible) { + String visible) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderbyid"; JsonObject userBaseObj2 = new JsonObject(); @@ -4973,7 +4975,7 @@ public static HttpResponse getMarketOrderByIdFromSolidity(String httpSolidityNod * constructor. */ public static HttpResponse getMarketOrderByIdFromPbft(String httpPbftNode, String orderId, - String visible) { + String visible) { try { String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderbyid"; JsonObject userBaseObj2 = new JsonObject(); @@ -4992,7 +4994,7 @@ public static HttpResponse getMarketOrderByIdFromPbft(String httpPbftNode, Strin * constructor. */ public static String marketCancelOrder(String httpNode, byte[] ownerAddress, String orderId, - String fromKey, String visible) { + String fromKey, String visible) { try { final String requestUrl = "http://" + httpNode + "/wallet/marketcancelorder"; JsonObject userBaseObj2 = new JsonObject(); @@ -5022,7 +5024,7 @@ public static String marketCancelOrder(String httpNode, byte[] ownerAddress, Str * constructor. */ public static HttpResponse getMarketOrderByAccount(String httpNode, byte[] ownerAddress, - String visible) { + String visible) { try { String requestUrl = "http://" + httpNode + "/wallet/getmarketorderbyaccount"; JsonObject userBaseObj2 = new JsonObject(); @@ -5045,7 +5047,7 @@ public static HttpResponse getMarketOrderByAccount(String httpNode, byte[] owner * constructor. */ public static HttpResponse getMarketOrderByAccountFromSolidity(String httpSolidityNode, - byte[] ownerAddress, String visible) { + byte[] ownerAddress, String visible) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderbyaccount"; JsonObject userBaseObj2 = new JsonObject(); @@ -5068,7 +5070,7 @@ public static HttpResponse getMarketOrderByAccountFromSolidity(String httpSolidi * constructor. */ public static HttpResponse getMarketOrderByAccountFromPbft(String httpPbftNode, - byte[] ownerAddress, String visible) { + byte[] ownerAddress, String visible) { try { String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderbyaccount"; JsonObject userBaseObj2 = new JsonObject(); @@ -5108,7 +5110,7 @@ public static HttpResponse getMarketPairList(String httpNode, String visible) { * constructor. */ public static HttpResponse getMarketPairListFromSolidity(String httpSolidityNode, - String visible) { + String visible) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketpairlist"; JsonObject userBaseObj2 = new JsonObject(); @@ -5143,7 +5145,7 @@ public static HttpResponse getMarketPairListFromPbft(String httpPbftNode, String * constructor. */ public static HttpResponse getMarketOrderListByPair(String httpNode, String sellTokenId, - String buyTokenId, String visible) { + String buyTokenId, String visible) { try { String requestUrl = "http://" + httpNode + "/wallet/getmarketorderlistbypair"; JsonObject userBaseObj2 = new JsonObject(); @@ -5168,8 +5170,8 @@ public static HttpResponse getMarketOrderListByPair(String httpNode, String sell * constructor. */ public static HttpResponse getMarketOrderListByPairFromSolidity(String httpSolidityNode, - String sellTokenId, - String buyTokenId, String visible) { + String sellTokenId, + String buyTokenId, String visible) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderlistbypair"; JsonObject userBaseObj2 = new JsonObject(); @@ -5194,7 +5196,7 @@ public static HttpResponse getMarketOrderListByPairFromSolidity(String httpSolid * constructor. */ public static HttpResponse getMarketOrderListByPairFromPbft(String httpPbftNode, - String sellTokenId, String buyTokenId, String visible) { + String sellTokenId, String buyTokenId, String visible) { try { String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderlistbypair"; JsonObject userBaseObj2 = new JsonObject(); @@ -5219,7 +5221,7 @@ public static HttpResponse getMarketOrderListByPairFromPbft(String httpPbftNode, * constructor. */ public static HttpResponse getMarketPriceByPair(String httpNode, String sellTokenId, - String buyTokenId, String visible) { + String buyTokenId, String visible) { try { String requestUrl = "http://" + httpNode + "/wallet/getmarketpricebypair"; JsonObject userBaseObj2 = new JsonObject(); @@ -5244,8 +5246,8 @@ public static HttpResponse getMarketPriceByPair(String httpNode, String sellToke * constructor. */ public static HttpResponse getMarketPriceByPairFromSolidity(String httpSolidityNode, - String sellTokenId, - String buyTokenId, String visible) { + String sellTokenId, + String buyTokenId, String visible) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketpricebypair"; JsonObject userBaseObj2 = new JsonObject(); @@ -5270,7 +5272,7 @@ public static HttpResponse getMarketPriceByPairFromSolidity(String httpSolidityN * constructor. */ public static HttpResponse getMarketPriceByPairFromPbft(String httpPbftNode, - String sellTokenId, String buyTokenId, String visible) { + String sellTokenId, String buyTokenId, String visible) { try { String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketpricebypair"; JsonObject userBaseObj2 = new JsonObject(); diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java index 55ede39790c..109459aade2 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java @@ -20,6 +20,7 @@ import org.bouncycastle.util.encoders.Hex; import org.testng.Assert; import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; import org.tron.api.GrpcAPI; import org.tron.api.GrpcAPI.BytesMessage; import org.tron.api.GrpcAPI.EmptyMessage; @@ -52,11 +53,12 @@ public class JsonRpcBase { public static final byte[] jsonRpcOwnerAddress = PublicMethed.getFinalAddress(jsonRpcOwnerKey); public static final String jsonRpcOwnerAddressString = PublicMethed.getAddressString(jsonRpcOwnerKey); - public static String jsonRpcNode = Configuration.getByPath("testng.conf").getStringList("jsonRpcNode.ip.list").get(0); public static String httpFullNode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(0); + public static String solidityNode = + Configuration.getByPath("testng.conf").getStringList("solidityNode.ip.list").get(0); public static String ethHttpsNode = Configuration.getByPath("testng.conf").getStringList("ethHttpsNode.host.list").get(0); @@ -64,6 +66,8 @@ public class JsonRpcBase { public WalletGrpc.WalletBlockingStub blockingStubFull = null; public ManagedChannel channelSolidity = null; public ManagedChannel channelPbft = null; + public String data = null; + public String paramString = null; public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; @@ -75,6 +79,7 @@ public class JsonRpcBase { public static String trc20AddressByteString; public static String trc20AddressHex; public static String contractAddressFrom58; + public static String contractTrc20AddressFrom58; public static String contractAddressFromHex; public static ByteString shieldAddressByteString; public static byte[] shieldAddressByte; @@ -172,7 +177,9 @@ public void deployContract() throws Exception { HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); String code = retMap.get("byteCode").toString(); + System.out.println("CODE:" + code); String abi = retMap.get("abI").toString(); + System.out.println("abi:" + abi); param.addProperty("abi", abi); param.addProperty("data", code); @@ -192,7 +199,6 @@ public void deployContract() throws Exception { responseContent = HttpMethed.parseStringContent(transactionString); final String txid = responseContent.getString("txID"); - response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); @@ -203,12 +209,12 @@ public void deployContract() throws Exception { org.junit.Assert.assertEquals(beforeTokenBalance - afterTokenBalance, 1L); - logger.info(txid); response = HttpMethed.getTransactionById(httpFullNode, txid); responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); org.junit.Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); contractAddressFrom58 = responseContent.getString("contract_address"); + logger.info("contractAddressFrom58:" + contractAddressFrom58); } /** constructor. */ @@ -230,10 +236,13 @@ public void triggerContract() throws Exception { + Integer.toHexString(Integer.valueOf(jsonRpcAssetId)); String tokenValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; - String paramString = addressParam + tokenIdParam + tokenValueParam; + paramString = addressParam + tokenIdParam + tokenValueParam; + logger.info("paramString:" + paramString); String selector = "TransferTokenTo(address,trcToken,uint256)"; + // exit(1); param.addProperty("data", "0x" + Util.parseMethod(selector, paramString)); + data = "0x" + Util.parseMethod(selector, paramString); param.addProperty("gas", "0x245498"); param.addProperty("value", "0x1389"); param.addProperty("tokenId", Long.valueOf(jsonRpcAssetId)); @@ -247,9 +256,10 @@ public void triggerContract() throws Exception { logger.info("transactionString : " + transactionString); String transactionSignString = HttpMethed.gettransactionsign(httpFullNode, transactionString, jsonRpcOwnerKey); - + logger.info("transactionSignString:" + transactionSignString); responseContent = HttpMethed.parseStringContent(transactionString); txid = responseContent.getString("txID"); + logger.info("triggerTxid:" + txid); response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); logger.info("response:" + response); @@ -301,7 +311,16 @@ public void deployTrc20Contract() throws InterruptedException { blockingStubFull); PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(deployTrc20Txid); + logger.info("deployTrc20Txid:" + deployTrc20Txid); + response = HttpMethed.getTransactionById(httpFullNode, deployTrc20Txid); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + org.junit.Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); + contractTrc20AddressFrom58 = responseContent.getString("contract_address"); + logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); + + // NewFilterId = createNewFilterId(); + Optional infoById = PublicMethed.getTransactionInfoById(deployTrc20Txid, blockingStubFull); diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java index fe7ceda6758..19c53eba3a5 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java @@ -149,16 +149,28 @@ public class PublicMethed { private static List walletFile = new ArrayList<>(); private static ShieldWrapper shieldWrapper = new ShieldWrapper(); Wallet wallet = new Wallet(); + public static volatile Integer witnessNum; /** * constructor. */ + + + public static Integer getWitnessNum(WalletGrpc.WalletBlockingStub blockingStubFull) { + if (null == witnessNum) { + witnessNum =PublicMethed.listWitnesses(blockingStubFull) + .get().getWitnessesList().size(); + } + + return witnessNum; + } + public static String createAssetIssueGetTxid(byte[] address, String name, String abbreviation, - Long totalSupply, Integer trxNum, Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + Long totalSupply, Integer trxNum, Integer icoNum, Long startTime, Long endTime, + Integer voteScore, String description, String url, Long freeAssetNetLimit, + Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -184,7 +196,7 @@ public static String createAssetIssueGetTxid(byte[] address, String name, String builder.setFreeAssetNetLimit(freeAssetNetLimit); builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); + .newBuilder(); frozenBuilder.setFrozenAmount(fronzenAmount); frozenBuilder.setFrozenDays(frozenDay); builder.addFrozenSupply(0, frozenBuilder); @@ -199,8 +211,8 @@ public static String createAssetIssueGetTxid(byte[] address, String name, String GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } catch (Exception ex) { ex.printStackTrace(); return null; @@ -212,10 +224,10 @@ public static String createAssetIssueGetTxid(byte[] address, String name, String * constructor. */ public static Boolean createAssetIssue(byte[] address, String name, Long totalSupply, - Integer trxNum, Integer icoNum, Long startTime, Long endTime, Integer voteScore, - String description, String url, Long freeAssetNetLimit, Long publicFreeAssetNetLimit, - Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + Integer trxNum, Integer icoNum, Long startTime, Long endTime, Integer voteScore, + String description, String url, Long freeAssetNetLimit, Long publicFreeAssetNetLimit, + Long fronzenAmount, Long frozenDay, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -240,7 +252,7 @@ public static Boolean createAssetIssue(byte[] address, String name, Long totalSu builder.setFreeAssetNetLimit(freeAssetNetLimit); builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); + .newBuilder(); frozenBuilder.setFrozenAmount(fronzenAmount); frozenBuilder.setFrozenDays(frozenDay); builder.addFrozenSupply(0, frozenBuilder); @@ -266,10 +278,10 @@ public static Boolean createAssetIssue(byte[] address, String name, Long totalSu */ public static Boolean createAssetIssue(byte[] address, String name, String abbreviation, - Long totalSupply, Integer trxNum, Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + Long totalSupply, Integer trxNum, Integer icoNum, Long startTime, Long endTime, + Integer voteScore, String description, String url, Long freeAssetNetLimit, + Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -295,7 +307,7 @@ public static Boolean createAssetIssue(byte[] address, String name, String abbre builder.setFreeAssetNetLimit(freeAssetNetLimit); builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); + .newBuilder(); frozenBuilder.setFrozenAmount(fronzenAmount); frozenBuilder.setFrozenDays(frozenDay); builder.addFrozenSupply(0, frozenBuilder); @@ -321,10 +333,10 @@ public static Boolean createAssetIssue(byte[] address, String name, String abbre */ public static Boolean createAssetIssue(byte[] address, String name, Long totalSupply, - Integer trxNum, Integer icoNum, int precision, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + Integer trxNum, Integer icoNum, int precision, Long startTime, Long endTime, + Integer voteScore, String description, String url, Long freeAssetNetLimit, + Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -350,7 +362,7 @@ public static Boolean createAssetIssue(byte[] address, String name, Long totalSu builder.setFreeAssetNetLimit(freeAssetNetLimit); builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); + .newBuilder(); frozenBuilder.setFrozenAmount(fronzenAmount); frozenBuilder.setFrozenDays(frozenDay); builder.addFrozenSupply(0, frozenBuilder); @@ -376,10 +388,10 @@ public static Boolean createAssetIssue(byte[] address, String name, Long totalSu */ public static Return createAssetIssue2(byte[] address, String name, Long totalSupply, - Integer trxNum, Integer icoNum, Long startTime, Long endTime, Integer voteScore, - String description, String url, Long freeAssetNetLimit, Long publicFreeAssetNetLimit, - Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + Integer trxNum, Integer icoNum, Long startTime, Long endTime, Integer voteScore, + String description, String url, Long freeAssetNetLimit, Long publicFreeAssetNetLimit, + Long fronzenAmount, Long frozenDay, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -407,13 +419,13 @@ public static Return createAssetIssue2(byte[] address, String name, Long totalSu //builder.setPublicFreeAssetNetUsage(); //builder.setPublicLatestFreeNetTime(); AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); + .newBuilder(); frozenBuilder.setFrozenAmount(fronzenAmount); frozenBuilder.setFrozenDays(frozenDay); builder.addFrozenSupply(0, frozenBuilder); TransactionExtention transactionExtention = blockingStubFull - .createAssetIssue2(builder.build()); + .createAssetIssue2(builder.build()); if (transactionExtention == null) { return transactionExtention.getResult(); @@ -433,7 +445,7 @@ public static Return createAssetIssue2(byte[] address, String name, Long totalSu return transactionExtention.getResult(); } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); @@ -459,7 +471,7 @@ public static Return createAssetIssue2(byte[] address, String name, Long totalSu */ public static Account queryAccountByAddress(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString addressBs = ByteString.copyFrom(address); Account request = Account.newBuilder().setAddress(addressBs).build(); @@ -471,7 +483,7 @@ public static Account queryAccountByAddress(byte[] address, */ public static Account queryAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString addressBs = ByteString.copyFrom(address); Account request = Account.newBuilder().setAddress(addressBs).build(); @@ -484,7 +496,7 @@ public static Account queryAccount(byte[] address, */ public static Protocol.Account queryAccount(String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); byte[] address; ECKey temKey = null; @@ -512,7 +524,7 @@ public static Protocol.Account queryAccount(String priKey, * constructor. */ public static Account queryAccount(byte[] address, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString addressBs = ByteString.copyFrom(address); Account request = Account.newBuilder().setAddress(addressBs).build(); @@ -524,7 +536,7 @@ public static Account queryAccount(byte[] address, */ public static Account getAccountById(String accountId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString bsAccountId = ByteString.copyFromUtf8(accountId); Account request = Account.newBuilder().setAccountId(bsAccountId).build(); @@ -536,7 +548,7 @@ public static Account getAccountById(String accountId, */ public static Account getAccountByIdFromSolidity(String accountId, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString bsAccountId = ByteString.copyFromUtf8(accountId); Account request = Account.newBuilder().setAccountId(bsAccountId).build(); @@ -567,7 +579,7 @@ public static byte[] getAddress(ECKey ecKey) { */ public static Protocol.Account grpcQueryAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString addressBs = ByteString.copyFrom(address); Protocol.Account request = Protocol.Account.newBuilder().setAddress(addressBs).build(); @@ -579,7 +591,7 @@ public static Protocol.Account grpcQueryAccount(byte[] address, */ public static Protocol.Block getBlock(long blockNum, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); builder.setNum(blockNum); @@ -591,7 +603,7 @@ public static Protocol.Block getBlock(long blockNum, */ public static BlockExtention getBlock2(long blockNum, - WalletBlockingStub blockingStubFull) { + WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); builder.setNum(blockNum); @@ -603,7 +615,7 @@ public static BlockExtention getBlock2(long blockNum, */ public static Protocol.Transaction signTransaction(ECKey ecKey, - Protocol.Transaction transaction) { + Protocol.Transaction transaction) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); if (ecKey == null || ecKey.getPrivKey() == null) { //logger.warn("Warning: Can't sign,there is no private key !!"); @@ -611,8 +623,8 @@ public static Protocol.Transaction signTransaction(ECKey ecKey, } transaction = TransactionUtils.setTimestamp(transaction); logger.info("Txid in sign is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); return TransactionUtils.sign(transaction, ecKey); } @@ -621,15 +633,15 @@ public static Protocol.Transaction signTransaction(ECKey ecKey, */ public static Protocol.Transaction signTransactionForShield(ECKey ecKey, - Protocol.Transaction transaction) { + Protocol.Transaction transaction) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); if (ecKey == null || ecKey.getPrivKey() == null) { //logger.warn("Warning: Can't sign,there is no private key !!"); return null; } logger.info("Txid in sign is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); return TransactionUtils.sign(transaction, ecKey); } @@ -639,7 +651,7 @@ public static Protocol.Transaction signTransactionForShield(ECKey ecKey, */ public static boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, - byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -670,7 +682,7 @@ public static boolean participateAssetIssue(byte[] to, byte[] assertName, long a */ public static Return participateAssetIssue2(byte[] to, byte[] assertName, long amount, - byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -707,7 +719,7 @@ public static Return participateAssetIssue2(byte[] to, byte[] assertName, long a return transactionExtention.getResult(); } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); //Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); @@ -725,7 +737,7 @@ public static Return participateAssetIssue2(byte[] to, byte[] assertName, long a */ public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); byte[] address = addRess; long frozenBalance = freezeBalance; @@ -740,7 +752,7 @@ public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long fre } final ECKey ecKey = temKey; Protocol.Block currentBlock = blockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); Protocol.Account beforeFronzen = queryAccount(priKey, blockingStubFull); Long beforeFrozenBalance = 0L; @@ -756,7 +768,7 @@ public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long fre ByteString byteAddreess = ByteString.copyFrom(address); builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); + .setFrozenDuration(frozenDuration); FreezeBalanceContract contract = builder.build(); Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); @@ -792,7 +804,7 @@ public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long fre */ public static Return freezeBalance2(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); byte[] address = addRess; long frozenBalance = freezeBalance; @@ -807,7 +819,7 @@ public static Return freezeBalance2(byte[] addRess, long freezeBalance, long fre } final ECKey ecKey = temKey; Protocol.Block currentBlock = blockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); Protocol.Account beforeFronzen = queryAccount(priKey, blockingStubFull); Long beforeFrozenBalance = 0L; @@ -823,7 +835,7 @@ public static Return freezeBalance2(byte[] addRess, long freezeBalance, long fre ByteString byteAddreess = ByteString.copyFrom(address); builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); + .setFrozenDuration(frozenDuration); FreezeBalanceContract contract = builder.build(); @@ -846,7 +858,7 @@ public static Return freezeBalance2(byte[] addRess, long freezeBalance, long fre return transactionExtention.getResult(); } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = TransactionUtils.setTimestamp(transaction); transaction = TransactionUtils.sign(transaction, ecKey); @@ -860,7 +872,7 @@ public static Return freezeBalance2(byte[] addRess, long freezeBalance, long fre while (afterBlockNum < beforeBlockNum) { Protocol.Block currentBlock1 = blockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); } @@ -868,8 +880,8 @@ public static Return freezeBalance2(byte[] addRess, long freezeBalance, long fre Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); logger.info( - "beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" + afterFrozenBalance - .toString()); + "beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" + afterFrozenBalance + .toString()); Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); return ret; } @@ -879,7 +891,7 @@ public static Return freezeBalance2(byte[] addRess, long freezeBalance, long fre */ public static Boolean unFreezeBalance(byte[] address, String priKey, int resourceCode, - byte[] receiverAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + byte[] receiverAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -910,7 +922,7 @@ public static Boolean unFreezeBalance(byte[] address, String priKey, int resourc */ public static Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); //String priKey = testKey002; ECKey temKey = null; @@ -950,7 +962,7 @@ public static Boolean sendcoin(byte[] to, long amount, byte[] owner, String priK */ public static String sendcoinGetTransactionHex(byte[] to, long amount, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -978,7 +990,7 @@ public static String sendcoinGetTransactionHex(byte[] to, long amount, byte[] ow } transaction = signTransaction(ecKey, transaction); logger.info("HEX transaction is : " + "transaction hex string is " + ByteArray - .toHexString(transaction.toByteArray())); + .toHexString(transaction.toByteArray())); return ByteArray.toHexString(transaction.toByteArray()); } @@ -988,7 +1000,7 @@ public static String sendcoinGetTransactionHex(byte[] to, long amount, byte[] ow */ public static Boolean cancelDeferredTransactionById(String txid, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1039,7 +1051,7 @@ public static Boolean cancelDeferredTransactionById(String txid, byte[] owner, S */ public static String cancelDeferredTransactionByIdGetTxid(String txid, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1058,7 +1070,7 @@ public static String cancelDeferredTransactionByIdGetTxid(String txid, byte[] ow */ public static Boolean sendcoinDelayed(byte[] to, long amount, long delaySeconds, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1087,8 +1099,8 @@ public static Boolean sendcoinDelayed(byte[] to, long amount, long delaySeconds, } transaction = signTransaction(ecKey, transaction); logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response.getResult(); } @@ -1098,8 +1110,8 @@ public static Boolean sendcoinDelayed(byte[] to, long amount, long delaySeconds, */ public static boolean transferAssetDelay(byte[] to, byte[] assertName, long amount, - long delaySeconds, byte[] address, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + long delaySeconds, byte[] address, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1133,8 +1145,8 @@ public static boolean transferAssetDelay(byte[] to, byte[] assertName, long amou } transaction = signTransaction(ecKey, transaction); logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response.getResult(); } @@ -1144,7 +1156,7 @@ public static boolean transferAssetDelay(byte[] to, byte[] assertName, long amou */ public static String createAccountDelayGetTxid(byte[] ownerAddress, byte[] newAddress, - Long delaySeconds, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Long delaySeconds, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1167,12 +1179,12 @@ public static String createAccountDelayGetTxid(byte[] ownerAddress, byte[] newAd } transaction = signTransaction(ecKey, transaction); logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } /** @@ -1180,7 +1192,7 @@ public static String createAccountDelayGetTxid(byte[] ownerAddress, byte[] newAd */ public static String updateAccountDelayGetTxid(byte[] addressBytes, byte[] accountNameBytes, - Long delaySeconds, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Long delaySeconds, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1207,12 +1219,12 @@ public static String updateAccountDelayGetTxid(byte[] addressBytes, byte[] accou } transaction = signTransaction(ecKey, transaction); logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } /** @@ -1220,7 +1232,7 @@ public static String updateAccountDelayGetTxid(byte[] addressBytes, byte[] accou */ public static String unfreezeAssetDelayGetTxid(byte[] address, Long delaySeconds, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1244,12 +1256,12 @@ public static String unfreezeAssetDelayGetTxid(byte[] address, Long delaySeconds } transaction = signTransaction(ecKey, transaction); logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } @@ -1258,8 +1270,8 @@ public static String unfreezeAssetDelayGetTxid(byte[] address, Long delaySeconds */ public static String transferAssetDelayGetTxid(byte[] to, byte[] assertName, long amount, - long delaySeconds, byte[] address, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + long delaySeconds, byte[] address, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1293,12 +1305,12 @@ public static String transferAssetDelayGetTxid(byte[] to, byte[] assertName, lon } transaction = signTransaction(ecKey, transaction); logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } @@ -1307,7 +1319,7 @@ public static String transferAssetDelayGetTxid(byte[] to, byte[] assertName, lon */ public static String sendcoinDelayedGetTxid(byte[] to, long amount, long delaySeconds, - byte[] owner, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + byte[] owner, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1336,12 +1348,12 @@ public static String sendcoinDelayedGetTxid(byte[] to, long amount, long delaySe } transaction = signTransaction(ecKey, transaction); logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } /** @@ -1349,7 +1361,7 @@ public static String sendcoinDelayedGetTxid(byte[] to, long amount, long delaySe */ public static String setAccountIdDelayGetTxid(byte[] accountIdBytes, long delaySeconds, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1376,12 +1388,12 @@ public static String setAccountIdDelayGetTxid(byte[] accountIdBytes, long delayS transaction = signTransaction(ecKey, transaction); logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } @@ -1390,8 +1402,8 @@ public static String setAccountIdDelayGetTxid(byte[] accountIdBytes, long delayS */ public static String updateAssetDelay(byte[] address, byte[] description, byte[] url, - long newLimit, long newPublicLimit, long delaySeconds, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + long newLimit, long newPublicLimit, long delaySeconds, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1418,12 +1430,12 @@ public static String updateAssetDelay(byte[] address, byte[] description, byte[] transaction = signTransaction(ecKey, transaction); logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } @@ -1432,7 +1444,7 @@ public static String updateAssetDelay(byte[] address, byte[] description, byte[] */ public static Return sendcoin2(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1473,7 +1485,7 @@ public static Return sendcoin2(byte[] to, long amount, byte[] owner, String priK return transactionExtention.getResult(); } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); @@ -1489,7 +1501,7 @@ public static Return sendcoin2(byte[] to, long amount, byte[] owner, String priK */ public static String sendcoinGetTransactionId(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); //String priKey = testKey002; ECKey temKey = null; @@ -1529,8 +1541,8 @@ public static String sendcoinGetTransactionId(byte[] to, long amount, byte[] own return null; } else { return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } } @@ -1539,7 +1551,7 @@ public static String sendcoinGetTransactionId(byte[] to, long amount, byte[] own */ public static Optional getTransactionById(String txId, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); Transaction transaction = blockingStubFull.getTransactionById(request); @@ -1552,7 +1564,7 @@ public static Optional getTransactionById(String txId, */ public static Optional getTransactionById(String txId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); Transaction transaction = blockingStubFull.getTransactionById(request); @@ -1563,7 +1575,7 @@ public static Optional getTransactionById(String txId, * constructor. */ public static Long getAssetBalanceByAssetId(ByteString assetId, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Account assetOwnerAccount = queryAccount(priKey, blockingStubFull); Long assetOwnerAssetBalance = 0L; for (String id : assetOwnerAccount.getAssetV2Map().keySet()) { @@ -1595,7 +1607,7 @@ public static Optional getDeferredTransactionById(String tx */ public static Optional getTransactionByIdSolidity(String txId, - WalletGrpc.WalletBlockingStub blockingStubSolidity) { + WalletGrpc.WalletBlockingStub blockingStubSolidity) { ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); Transaction transaction = blockingStubSolidity.getTransactionById(request); @@ -1611,13 +1623,13 @@ public static String printTransaction(Transaction transaction) { result += "hash: "; result += "\n"; result += ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.toByteArray())); result += "\n"; result += "txid: "; result += "\n"; result += ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); result += "\n"; if (transaction.getRawData() != null) { @@ -1648,7 +1660,7 @@ public static long printTransactionRow(Transaction.raw raw) { */ public static boolean updateAsset(byte[] address, byte[] description, byte[] url, long newLimit, - long newPublicLimit, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + long newPublicLimit, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1683,7 +1695,7 @@ public static boolean updateAsset(byte[] address, byte[] description, byte[] url */ public static Return updateAsset2(byte[] address, byte[] description, byte[] url, long newLimit, - long newPublicLimit, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + long newPublicLimit, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1722,7 +1734,7 @@ public static Return updateAsset2(byte[] address, byte[] description, byte[] url return transactionExtention.getResult(); } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); @@ -1738,7 +1750,7 @@ public static Return updateAsset2(byte[] address, byte[] description, byte[] url */ public static boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1781,7 +1793,7 @@ public static boolean transferAsset(byte[] to, byte[] assertName, long amount, b */ public static boolean updateAccount(byte[] addressBytes, byte[] accountNameBytes, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1816,25 +1828,27 @@ public static boolean updateAccount(byte[] addressBytes, byte[] accountNameBytes */ public static boolean waitSolidityNodeSynFullNodeData( - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + WalletGrpc.WalletBlockingStub blockingStubFull, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); Block solidityCurrentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); Integer wait = 0; logger.info("Fullnode block num is " + currentBlock.getBlockHeader().getRawData().getNumber()); + while (solidityCurrentBlock.getBlockHeader().getRawData().getNumber() - < currentBlock.getBlockHeader().getRawData().getNumber() + 1 && wait <= 24) { + < currentBlock.getBlockHeader().getRawData().getNumber() + 1 && wait <((getWitnessNum(blockingStubFull) >= 27) + ? 18 : (getWitnessNum(blockingStubFull) * 70 / 100)) ) { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } logger.info("Soliditynode num is " + solidityCurrentBlock.getBlockHeader().getRawData() - .getNumber()); + .getNumber()); solidityCurrentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); if (wait == 24) { logger.info("Didn't syn,skip to next case."); return false; @@ -1858,7 +1872,7 @@ public static boolean waitProduceNextBlock(WalletGrpc.WalletBlockingStub blockin Integer wait = 0; logger.info( - "Block num is " + currentBlock.getBlockHeader().getRawData().getNumber()); + "Block num is " + currentBlock.getBlockHeader().getRawData().getNumber()); while (nextNum <= currentNum + 1 && wait <= 45) { try { Thread.sleep(1000); @@ -1883,7 +1897,7 @@ public static boolean waitProduceNextBlock(WalletGrpc.WalletBlockingStub blockin */ public static AccountNetMessage getAccountNet(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString addressBs = ByteString.copyFrom(address); Account request = Account.newBuilder().setAddress(addressBs).build(); @@ -1927,7 +1941,7 @@ public static byte[] getFinalAddress(String priKey) { */ public static String createAccountGetTxid(byte[] ownerAddress, byte[] newAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1954,8 +1968,8 @@ public static String createAccountGetTxid(byte[] ownerAddress, byte[] newAddress } else { //logger.info("brodacast succesfully"); return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } } @@ -1964,7 +1978,7 @@ public static String createAccountGetTxid(byte[] ownerAddress, byte[] newAddress */ public static boolean createAccount(byte[] ownerAddress, byte[] newAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -1994,7 +2008,7 @@ public static boolean createAccount(byte[] ownerAddress, byte[] newAddress, Stri */ public static Return createAccount2(byte[] ownerAddress, byte[] newAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -2031,7 +2045,7 @@ public static Return createAccount2(byte[] ownerAddress, byte[] newAddress, Stri return transactionExtention.getResult(); } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); @@ -2047,7 +2061,7 @@ public static Return createAccount2(byte[] ownerAddress, byte[] newAddress, Stri */ public static boolean voteWitness(byte[] ownerAddress, String priKey, - HashMap witnessMap, WalletGrpc.WalletBlockingStub blockingStubFull) { + HashMap witnessMap, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -2086,7 +2100,7 @@ public static boolean voteWitness(byte[] ownerAddress, String priKey, return false; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); @@ -2099,7 +2113,7 @@ public static boolean voteWitness(byte[] ownerAddress, String priKey, */ public static boolean createProposal(byte[] ownerAddress, String priKey, - HashMap parametersMap, WalletGrpc.WalletBlockingStub blockingStubFull) { + HashMap parametersMap, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -2132,7 +2146,7 @@ public static boolean createProposal(byte[] ownerAddress, String priKey, return false; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); @@ -2144,7 +2158,7 @@ public static boolean createProposal(byte[] ownerAddress, String priKey, */ public static boolean approveProposal(byte[] ownerAddress, String priKey, long id, - boolean isAddApproval, WalletGrpc.WalletBlockingStub blockingStubFull) { + boolean isAddApproval, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -2177,7 +2191,7 @@ public static boolean approveProposal(byte[] ownerAddress, String priKey, long i return false; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response.getResult(); @@ -2188,7 +2202,7 @@ public static boolean approveProposal(byte[] ownerAddress, String priKey, long i */ public static boolean deleteProposal(byte[] ownerAddress, String priKey, long id, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -2221,7 +2235,7 @@ public static boolean deleteProposal(byte[] ownerAddress, String priKey, long id return false; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response.getResult(); @@ -2267,7 +2281,7 @@ public static ArrayList getAddressInfo(String key) { */ public static boolean setAccountId(byte[] accountIdBytes, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -2299,10 +2313,10 @@ public static boolean setAccountId(byte[] accountIdBytes, byte[] ownerAddress, S */ public static Boolean freezeBalanceGetTronPower(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, ByteString receiverAddress,String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + long freezeDuration, int resourceCode, ByteString receiverAddress,String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { return freezeBalanceForReceiver(addRess,freezeBalance, - freezeDuration,resourceCode,receiverAddress,priKey,blockingStubFull); + freezeDuration,resourceCode,receiverAddress,priKey,blockingStubFull); } /** @@ -2310,8 +2324,8 @@ public static Boolean freezeBalanceGetTronPower(byte[] addRess, long freezeBalan */ public static Boolean freezeBalanceGetEnergy(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + long freezeDuration, int resourceCode, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); byte[] address = addRess; long frozenBalance = freezeBalance; @@ -2329,7 +2343,7 @@ public static Boolean freezeBalanceGetEnergy(byte[] addRess, long freezeBalance, ByteString byteAddreess = ByteString.copyFrom(address); builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); + .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); FreezeBalanceContract contract = builder.build(); Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); @@ -2348,7 +2362,7 @@ public static Boolean freezeBalanceGetEnergy(byte[] addRess, long freezeBalance, * constructor. */ public static AccountResourceMessage getAccountResource(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString addressBs = ByteString.copyFrom(address); Account request = Account.newBuilder().setAddress(addressBs).build(); @@ -2360,7 +2374,7 @@ public static AccountResourceMessage getAccountResource(byte[] address, */ public static boolean buyStorage(long quantity, byte[] address, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -2391,7 +2405,7 @@ public static boolean buyStorage(long quantity, byte[] address, String priKey, return false; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response.getResult(); @@ -2401,7 +2415,7 @@ public static boolean buyStorage(long quantity, byte[] address, String priKey, * constructor. */ public static boolean sellStorage(long quantity, byte[] address, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -2432,7 +2446,7 @@ public static boolean sellStorage(long quantity, byte[] address, String priKey, return false; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response.getResult(); @@ -2442,10 +2456,10 @@ public static boolean sellStorage(long quantity, byte[] address, String priKey, * constructor. */ public static byte[] deployContractFallbackReceive(String contractName, String abiString, - String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, - byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + String code, + String data, Long feeLimit, long value, long consumeUserResourcePercent, + long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, + byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -2488,16 +2502,16 @@ public static byte[] deployContractFallbackReceive(String contractName, String a contractBuilder.setCallTokenValue(tokenValue); contractBuilder.setTokenId(Long.parseLong(tokenId)); CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + .build(); TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); + .deployContract(contractDeployContract); if (transactionExtention == null || !transactionExtention.getResult().getResult()) { System.out.println("RPC create trx failed!"); if (transactionExtention != null) { System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); } return null; } @@ -2505,7 +2519,7 @@ public static byte[] deployContractFallbackReceive(String contractName, String a final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); Transaction.Builder transBuilder = Transaction.newBuilder(); Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); + .toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -2523,7 +2537,7 @@ public static byte[] deployContractFallbackReceive(String contractName, String a byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); if (transactionExtention == null) { return null; } @@ -2540,11 +2554,11 @@ public static byte[] deployContractFallbackReceive(String contractName, String a } transaction = signTransaction(ecKey, transaction); System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); contractAddress = generateContractAddress(transaction, owner); System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); if (response.getResult() == false) { @@ -2559,9 +2573,9 @@ public static byte[] deployContractFallbackReceive(String contractName, String a * constructor. */ public static byte[] deployContract(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, - byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + String data, Long feeLimit, long value, long consumeUserResourcePercent, + long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, + byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -2604,16 +2618,16 @@ public static byte[] deployContract(String contractName, String abiString, Strin contractBuilder.setCallTokenValue(tokenValue); contractBuilder.setTokenId(Long.parseLong(tokenId)); CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + .build(); TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); + .deployContract(contractDeployContract); if (transactionExtention == null || !transactionExtention.getResult().getResult()) { System.out.println("RPC create trx failed!"); if (transactionExtention != null) { System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); } return null; } @@ -2621,7 +2635,7 @@ public static byte[] deployContract(String contractName, String abiString, Strin final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); Transaction.Builder transBuilder = Transaction.newBuilder(); Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); + .toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -2639,7 +2653,7 @@ public static byte[] deployContract(String contractName, String abiString, Strin byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); if (transactionExtention == null) { return null; } @@ -2656,11 +2670,11 @@ public static byte[] deployContract(String contractName, String abiString, Strin } transaction = signTransaction(ecKey, transaction); System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); contractAddress = generateContractAddress(transaction, owner); System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); if (response.getResult() == false) { @@ -2675,24 +2689,24 @@ public static byte[] deployContract(String contractName, String abiString, Strin * constructor. */ public static byte[] deployContract(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { + String data, Long feeLimit, long value, long consumeUserResourcePercent, + String libraryAddress, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { return deployContract(contractName, abiString, code, data, feeLimit, value, - consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, - blockingStubFull); + consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, + blockingStubFull); } /** * constructor. */ public static byte[] deployContractFallback(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { + String data, Long feeLimit, long value, long consumeUserResourcePercent, + String libraryAddress, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { return deployContractFallbackReceive(contractName, abiString, code, data, feeLimit, value, - consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, - blockingStubFull); + consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, + blockingStubFull); } /** @@ -2700,9 +2714,9 @@ public static byte[] deployContractFallback(String contractName, String abiStrin */ public static byte[] deployContractForLibrary(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - String libraryAddress, String priKey, byte[] ownerAddress, String compilerVersion, - WalletGrpc.WalletBlockingStub blockingStubFull) { + String data, Long feeLimit, long value, long consumeUserResourcePercent, + String libraryAddress, String priKey, byte[] ownerAddress, String compilerVersion, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -2751,16 +2765,16 @@ public static byte[] deployContractForLibrary(String contractName, String abiStr contractBuilder.setCallTokenValue(0); contractBuilder.setTokenId(Long.parseLong("0")); CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + .build(); TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); + .deployContract(contractDeployContract); if (transactionExtention == null || !transactionExtention.getResult().getResult()) { System.out.println("RPC create trx failed!"); if (transactionExtention != null) { System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); } return null; } @@ -2768,7 +2782,7 @@ public static byte[] deployContractForLibrary(String contractName, String abiStr final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); Transaction.Builder transBuilder = Transaction.newBuilder(); Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); + .toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -2786,7 +2800,7 @@ public static byte[] deployContractForLibrary(String contractName, String abiStr byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); if (transactionExtention == null) { return null; } @@ -2803,11 +2817,11 @@ public static byte[] deployContractForLibrary(String contractName, String abiStr } transaction = signTransaction(ecKey, transaction); System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); contractAddress = generateContractAddress(transaction, owner); System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); if (response.getResult() == false) { @@ -2824,12 +2838,12 @@ public static byte[] deployContractForLibrary(String contractName, String abiStr */ public static String deployContractAndGetTransactionInfoById(String contractName, - String abiString, String code, String data, Long feeLimit, long value, - long consumeUserResourcePercent, String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { + String abiString, String code, String data, Long feeLimit, long value, + long consumeUserResourcePercent, String libraryAddress, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { return deployContractAndGetTransactionInfoById(contractName, abiString, code, data, feeLimit, - value, consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, - blockingStubFull); + value, consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, + blockingStubFull); } /** @@ -2837,10 +2851,10 @@ public static String deployContractAndGetTransactionInfoById(String contractName */ public static String deployContractAndGetTransactionInfoById(String contractName, - String abiString, String code, String data, Long feeLimit, long value, - long consumeUserResourcePercent, long originEnergyLimit, String tokenId, long tokenValue, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { + String abiString, String code, String data, Long feeLimit, long value, + long consumeUserResourcePercent, long originEnergyLimit, String tokenId, long tokenValue, + String libraryAddress, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -2883,16 +2897,16 @@ public static String deployContractAndGetTransactionInfoById(String contractName contractBuilder.setCallTokenValue(tokenValue); contractBuilder.setTokenId(Long.parseLong(tokenId)); CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + .build(); TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); + .deployContract(contractDeployContract); if (transactionExtention == null || !transactionExtention.getResult().getResult()) { System.out.println("RPC create trx failed!"); if (transactionExtention != null) { System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); } return null; } @@ -2900,7 +2914,7 @@ public static String deployContractAndGetTransactionInfoById(String contractName final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); Transaction.Builder transBuilder = Transaction.newBuilder(); Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); + .toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -2932,19 +2946,19 @@ public static String deployContractAndGetTransactionInfoById(String contractName } transaction = signTransaction(ecKey, transaction); System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); byte[] contractAddress = generateContractAddress(transaction, owner); System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); if (response.getResult() == false) { return null; } else { //logger.info("brodacast succesfully"); return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } } @@ -2964,29 +2978,29 @@ public static SmartContract.ABI jsonStr2Abi(String jsonStr) { for (int index = 0; index < jsonRoot.size(); index++) { JsonElement abiItem = jsonRoot.get(index); boolean anonymous = - abiItem.getAsJsonObject().get("anonymous") != null && abiItem.getAsJsonObject() - .get("anonymous").getAsBoolean(); + abiItem.getAsJsonObject().get("anonymous") != null && abiItem.getAsJsonObject() + .get("anonymous").getAsBoolean(); final boolean constant = - abiItem.getAsJsonObject().get("constant") != null && abiItem.getAsJsonObject() - .get("constant").getAsBoolean(); + abiItem.getAsJsonObject().get("constant") != null && abiItem.getAsJsonObject() + .get("constant").getAsBoolean(); final String name = - abiItem.getAsJsonObject().get("name") != null ? abiItem.getAsJsonObject().get("name") - .getAsString() : null; + abiItem.getAsJsonObject().get("name") != null ? abiItem.getAsJsonObject().get("name") + .getAsString() : null; JsonArray inputs = - abiItem.getAsJsonObject().get("inputs") != null ? abiItem.getAsJsonObject().get("inputs") - .getAsJsonArray() : null; + abiItem.getAsJsonObject().get("inputs") != null ? abiItem.getAsJsonObject().get("inputs") + .getAsJsonArray() : null; final JsonArray outputs = - abiItem.getAsJsonObject().get("outputs") != null ? abiItem.getAsJsonObject() - .get("outputs").getAsJsonArray() : null; + abiItem.getAsJsonObject().get("outputs") != null ? abiItem.getAsJsonObject() + .get("outputs").getAsJsonArray() : null; String type = - abiItem.getAsJsonObject().get("type") != null ? abiItem.getAsJsonObject().get("type") - .getAsString() : null; + abiItem.getAsJsonObject().get("type") != null ? abiItem.getAsJsonObject().get("type") + .getAsString() : null; final boolean payable = - abiItem.getAsJsonObject().get("payable") != null && abiItem.getAsJsonObject() - .get("payable").getAsBoolean(); + abiItem.getAsJsonObject().get("payable") != null && abiItem.getAsJsonObject() + .get("payable").getAsBoolean(); final String stateMutability = - abiItem.getAsJsonObject().get("stateMutability") != null ? abiItem.getAsJsonObject() - .get("stateMutability").getAsString() : null; + abiItem.getAsJsonObject().get("stateMutability") != null ? abiItem.getAsJsonObject() + .get("stateMutability").getAsString() : null; if (type == null) { logger.error("No type!"); return null; @@ -3008,7 +3022,7 @@ public static SmartContract.ABI jsonStr2Abi(String jsonStr) { for (int j = 0; j < inputs.size(); j++) { JsonElement inputItem = inputs.get(j); if (inputItem.getAsJsonObject().get("name") == null - || inputItem.getAsJsonObject().get("type") == null) { + || inputItem.getAsJsonObject().get("type") == null) { logger.error("Input argument invalid due to no name or no type!"); return null; } @@ -3029,14 +3043,14 @@ public static SmartContract.ABI jsonStr2Abi(String jsonStr) { for (int k = 0; k < outputs.size(); k++) { JsonElement outputItem = outputs.get(k); if (outputItem.getAsJsonObject().get("name") == null - || outputItem.getAsJsonObject().get("type") == null) { + || outputItem.getAsJsonObject().get("type") == null) { logger.error("Output argument invalid due to no name or no type!"); return null; } String outputName = outputItem.getAsJsonObject().get("name").getAsString(); String outputType = outputItem.getAsJsonObject().get("type").getAsString(); SmartContract.ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param - .newBuilder(); + .newBuilder(); JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); @@ -3074,35 +3088,35 @@ public static SmartContract.ABI jsonStr2Abi2(String jsonStr) { for (int index = 0; index < jsonRoot.size(); index++) { JsonElement abiItem = jsonRoot.get(index); boolean anonymous = - abiItem.getAsJsonObject().get("anonymous") != null && abiItem.getAsJsonObject() - .get("anonymous").getAsBoolean(); + abiItem.getAsJsonObject().get("anonymous") != null && abiItem.getAsJsonObject() + .get("anonymous").getAsBoolean(); final boolean constant = - abiItem.getAsJsonObject().get("constant") != null && abiItem.getAsJsonObject() - .get("constant").getAsBoolean(); + abiItem.getAsJsonObject().get("constant") != null && abiItem.getAsJsonObject() + .get("constant").getAsBoolean(); final String name = - abiItem.getAsJsonObject().get("name") != null ? abiItem.getAsJsonObject().get("name") - .getAsString() : null; + abiItem.getAsJsonObject().get("name") != null ? abiItem.getAsJsonObject().get("name") + .getAsString() : null; JsonArray inputs = - abiItem.getAsJsonObject().get("inputs") != null ? abiItem.getAsJsonObject().get("inputs") - .getAsJsonArray() : null; + abiItem.getAsJsonObject().get("inputs") != null ? abiItem.getAsJsonObject().get("inputs") + .getAsJsonArray() : null; final JsonArray outputs = - abiItem.getAsJsonObject().get("outputs") != null ? abiItem.getAsJsonObject() - .get("outputs").getAsJsonArray() : null; + abiItem.getAsJsonObject().get("outputs") != null ? abiItem.getAsJsonObject() + .get("outputs").getAsJsonArray() : null; String type = - abiItem.getAsJsonObject().get("type") != null ? abiItem.getAsJsonObject().get("type") - .getAsString() : null; + abiItem.getAsJsonObject().get("type") != null ? abiItem.getAsJsonObject().get("type") + .getAsString() : null; final boolean payable = - abiItem.getAsJsonObject().get("payable") != null && abiItem.getAsJsonObject() - .get("payable").getAsBoolean(); + abiItem.getAsJsonObject().get("payable") != null && abiItem.getAsJsonObject() + .get("payable").getAsBoolean(); final String stateMutability = - abiItem.getAsJsonObject().get("stateMutability") != null ? abiItem.getAsJsonObject() - .get("stateMutability").getAsString() : null; + abiItem.getAsJsonObject().get("stateMutability") != null ? abiItem.getAsJsonObject() + .get("stateMutability").getAsString() : null; if (type == null) { logger.error("No type!"); return null; } if (!type.equalsIgnoreCase("fallback") && !type.equalsIgnoreCase("receive") - && null == inputs) { + && null == inputs) { logger.error("No inputs!"); return null; } @@ -3119,7 +3133,7 @@ public static SmartContract.ABI jsonStr2Abi2(String jsonStr) { for (int j = 0; j < inputs.size(); j++) { JsonElement inputItem = inputs.get(j); if (inputItem.getAsJsonObject().get("name") == null - || inputItem.getAsJsonObject().get("type") == null) { + || inputItem.getAsJsonObject().get("type") == null) { logger.error("Input argument invalid due to no name or no type!"); return null; } @@ -3140,14 +3154,14 @@ public static SmartContract.ABI jsonStr2Abi2(String jsonStr) { for (int k = 0; k < outputs.size(); k++) { JsonElement outputItem = outputs.get(k); if (outputItem.getAsJsonObject().get("name") == null - || outputItem.getAsJsonObject().get("type") == null) { + || outputItem.getAsJsonObject().get("type") == null) { logger.error("Output argument invalid due to no name or no type!"); return null; } String outputName = outputItem.getAsJsonObject().get("name").getAsString(); String outputType = outputItem.getAsJsonObject().get("type").getAsString(); SmartContract.ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param - .newBuilder(); + .newBuilder(); JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); @@ -3215,7 +3229,7 @@ public static SmartContract.ABI.Entry.EntryType getEntryType2(String type) { */ public static SmartContract.ABI.Entry.StateMutabilityType getStateMutability( - String stateMutability) { + String stateMutability) { switch (stateMutability) { case "pure": return SmartContract.ABI.Entry.StateMutabilityType.Pure; @@ -3242,8 +3256,8 @@ public static byte[] generateContractAddress(Transaction trx, byte[] owneraddres // get tx hash byte[] txRawDataHash = Sha256Hash - .of(CommonParameter.getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()) - .getBytes(); + .of(CommonParameter.getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()) + .getBytes(); // combine byte[] combined = new byte[txRawDataHash.length + ownerAddress.length]; @@ -3259,7 +3273,7 @@ public static byte[] generateContractAddress(Transaction trx, byte[] owneraddres */ public static SmartContract getContract(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString byteString = ByteString.copyFrom(address); BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(byteString).build(); @@ -3273,13 +3287,13 @@ public static SmartContract getContract(byte[] address, */ public static SmartContractDataWrapper getContractInfo(byte[] address, - WalletBlockingStub blockingStubFull) { + WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString byteString = ByteString.copyFrom(address); BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(byteString).build(); logger.info( - "contract name is " + blockingStubFull.getContractInfo(bytesMessage).getSmartContract() - .getName()); + "contract name is " + blockingStubFull.getContractInfo(bytesMessage).getSmartContract() + .getName()); logger.info("contract address is " + WalletClient.encode58Check(address)); return blockingStubFull.getContractInfo(bytesMessage); } @@ -3298,7 +3312,7 @@ private static byte[] replaceLibraryAddress(String code, String libraryAddressPa String libraryName = cur.substring(0, lastPosition); String addr = cur.substring(lastPosition + 1); String libraryAddressHex = ByteArray.toHexString(Commons.decodeFromBase58Check(addr)) - .substring(2); + .substring(2); String repeated = new String(new char[40 - libraryName.length() - 2]).replace("\0", "_"); String beReplaced = "__" + libraryName + repeated; @@ -3319,7 +3333,7 @@ private static byte[] replaceLibraryAddress_1(String code, byte[] libraryAddress } private static byte[] replaceLibraryAddresscompilerVersion(String code, String libraryAddressPair, - String compilerVersion) { + String compilerVersion) { String[] libraryAddressList = libraryAddressPair.split("[,]"); @@ -3334,7 +3348,7 @@ private static byte[] replaceLibraryAddresscompilerVersion(String code, String l String addr = cur.substring(lastPosition + 1); String libraryAddressHex; libraryAddressHex = (new String(Hex.encode(Commons.decodeFromBase58Check(addr)), - StandardCharsets.US_ASCII)).substring(2); + StandardCharsets.US_ASCII)).substring(2); String beReplaced; if (compilerVersion == null) { @@ -3344,7 +3358,7 @@ private static byte[] replaceLibraryAddresscompilerVersion(String code, String l } else if (compilerVersion.equalsIgnoreCase("v5")) { //0.5.4 version String libraryNameKeccak256 = ByteArray.toHexString(sha3(ByteArray.fromString(libraryName))) - .substring(0, 34); + .substring(0, 34); beReplaced = "__\\$" + libraryNameKeccak256 + "\\$__"; } else { throw new RuntimeException("unknown compiler version."); @@ -3362,7 +3376,7 @@ private static byte[] replaceLibraryAddresscompilerVersion(String code, String l */ public static boolean updateSetting(byte[] contractAddress, long consumeUserResourcePercent, - String priKey, byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + String priKey, byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -3381,13 +3395,13 @@ public static boolean updateSetting(byte[] contractAddress, long consumeUserReso UpdateSettingContract updateSettingContract = builder.build(); TransactionExtention transactionExtention = blockingStubFull - .updateSetting(updateSettingContract); + .updateSetting(updateSettingContract); if (transactionExtention == null || !transactionExtention.getResult().getResult()) { System.out.println("RPC create trx failed!"); if (transactionExtention != null) { System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); } return false; } @@ -3406,7 +3420,7 @@ public static boolean updateSetting(byte[] contractAddress, long consumeUserReso return false; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response.getResult(); @@ -3417,8 +3431,8 @@ public static boolean updateSetting(byte[] contractAddress, long consumeUserReso */ public static boolean updateSettingDelay(byte[] contractAddress, long consumeUserResourcePercent, - long delaySeconds, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { + long delaySeconds, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -3437,13 +3451,13 @@ public static boolean updateSettingDelay(byte[] contractAddress, long consumeUse UpdateSettingContract updateSettingContract = builder.build(); TransactionExtention transactionExtention = blockingStubFull - .updateSetting(updateSettingContract); + .updateSetting(updateSettingContract); if (transactionExtention == null || !transactionExtention.getResult().getResult()) { System.out.println("RPC create trx failed!"); if (transactionExtention != null) { System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); } return false; } @@ -3476,8 +3490,8 @@ public static boolean updateSettingDelay(byte[] contractAddress, long consumeUse */ public static String updateSettingDelayGetTxid(byte[] contractAddress, - long consumeUserResourcePercent, long delaySeconds, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { + long consumeUserResourcePercent, long delaySeconds, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -3496,13 +3510,13 @@ public static String updateSettingDelayGetTxid(byte[] contractAddress, UpdateSettingContract updateSettingContract = builder.build(); TransactionExtention transactionExtention = blockingStubFull - .updateSetting(updateSettingContract); + .updateSetting(updateSettingContract); if (transactionExtention == null || !transactionExtention.getResult().getResult()) { System.out.println("RPC create trx failed!"); if (transactionExtention != null) { System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); } return null; } @@ -3513,8 +3527,8 @@ public static String updateSettingDelayGetTxid(byte[] contractAddress, * constructor. */ public static String updateEnergyLimitDelayGetTxid(byte[] contractAddress, long originEnergyLimit, - long delaySeconds, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { + long delaySeconds, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -3533,13 +3547,13 @@ public static String updateEnergyLimitDelayGetTxid(byte[] contractAddress, long UpdateEnergyLimitContract updateEnergyLimitContract = builder.build(); TransactionExtention transactionExtention = blockingStubFull - .updateEnergyLimit(updateEnergyLimitContract); + .updateEnergyLimit(updateEnergyLimitContract); if (transactionExtention == null || !transactionExtention.getResult().getResult()) { System.out.println("RPC create trx failed!"); if (transactionExtention != null) { System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); } return null; } @@ -3560,12 +3574,12 @@ public static String updateEnergyLimitDelayGetTxid(byte[] contractAddress, long return null; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } @@ -3574,7 +3588,7 @@ public static String updateEnergyLimitDelayGetTxid(byte[] contractAddress, long */ public static Optional getTransactionInfoById(String txId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); TransactionInfo transactionInfo; @@ -3586,7 +3600,7 @@ public static Optional getTransactionInfoById(String txId, * 61 constructor. */ public static Optional getTransactionInfoByIdFromSolidity(String txId, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); TransactionInfo transactionInfo; @@ -3599,7 +3613,7 @@ public static Optional getTransactionInfoByIdFromSolidity(Strin * constructor. */ public static Optional getTransactionInfoByBlockNum(long blockNum, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { NumberMessage.Builder builder = NumberMessage.newBuilder(); builder.setNum(blockNum); TransactionInfoList transactionInfoList; @@ -3611,7 +3625,7 @@ public static Optional getTransactionInfoByBlockNum(long bl * constructor. */ public static Optional getTransactionInfoByBlockNumFromSolidity( - long blockNum, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + long blockNum, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { NumberMessage.Builder builder = NumberMessage.newBuilder(); builder.setNum(blockNum); TransactionInfoList transactionInfoList; @@ -3623,10 +3637,10 @@ public static Optional getTransactionInfoByBlockNumFromSoli * constructor. */ public static String triggerContract(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + Boolean isHex, long callValue, long feeLimit, byte[] ownerAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { return triggerContract(contractAddress, method, argsStr, isHex, callValue, feeLimit, "0", 0, - ownerAddress, priKey, blockingStubFull); + ownerAddress, priKey, blockingStubFull); } /** @@ -3634,8 +3648,8 @@ public static String triggerContract(byte[] contractAddress, String method, Stri */ public static String triggerContract(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, + byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -3670,16 +3684,16 @@ public static String triggerContract(byte[] contractAddress, String method, Stri System.out.println("RPC create call trx failed!"); System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); return null; } Transaction transaction = transactionExtention.getTransaction(); if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { + && transactionExtention.getResult() != null) { byte[] result = transactionExtention.getConstantResult(0).toByteArray(); System.out.println("message:" + transaction.getRet(0).getRet()); System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); System.out.println("Result:" + Hex.toHexString(result)); return null; } @@ -3687,7 +3701,7 @@ public static String triggerContract(byte[] contractAddress, String method, Stri final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); Transaction.Builder transBuilder = Transaction.newBuilder(); Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); + .toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); @@ -3720,15 +3734,15 @@ public static String triggerContract(byte[] contractAddress, String method, Stri } transaction = signTransaction(ecKey, transaction); System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); if (response.getResult() == false) { return null; } else { return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } } @@ -3737,11 +3751,11 @@ public static String triggerContract(byte[] contractAddress, String method, Stri * constructor. */ public static String triggerContractBoth(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletGrpc.WalletBlockingStub blockingStubFull1) { + Boolean isHex, long callValue, long feeLimit, byte[] ownerAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull, + WalletGrpc.WalletBlockingStub blockingStubFull1) { return triggerContractBoth(contractAddress, method, argsStr, isHex, callValue, feeLimit, "0", 0, - ownerAddress, priKey, blockingStubFull, blockingStubFull1); + ownerAddress, priKey, blockingStubFull, blockingStubFull1); } /** @@ -3749,9 +3763,9 @@ public static String triggerContractBoth(byte[] contractAddress, String method, */ public static String triggerContractBoth(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - WalletGrpc.WalletBlockingStub blockingStubFull1) { + Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, + byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, + WalletGrpc.WalletBlockingStub blockingStubFull1) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -3783,16 +3797,16 @@ public static String triggerContractBoth(byte[] contractAddress, String method, System.out.println("RPC create call trx failed!"); System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); return null; } Transaction transaction = transactionExtention.getTransaction(); if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { + && transactionExtention.getResult() != null) { byte[] result = transactionExtention.getConstantResult(0).toByteArray(); System.out.println("message:" + transaction.getRet(0).getRet()); System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); System.out.println("Result:" + Hex.toHexString(result)); return null; } @@ -3800,7 +3814,7 @@ public static String triggerContractBoth(byte[] contractAddress, String method, final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); Transaction.Builder transBuilder = Transaction.newBuilder(); Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); + .toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -3831,16 +3845,16 @@ public static String triggerContractBoth(byte[] contractAddress, String method, } transaction = signTransaction(ecKey, transaction); System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransactionBoth(transaction, blockingStubFull, - blockingStubFull1); + blockingStubFull1); if (response.getResult() == false) { return null; } else { return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } } @@ -3850,9 +3864,9 @@ public static String triggerContractBoth(byte[] contractAddress, String method, */ public static String triggerParamListContract(byte[] contractAddress, String method, - List params, Boolean isHex, long callValue, long feeLimit, String tokenId, - long tokenValue, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + List params, Boolean isHex, long callValue, long feeLimit, String tokenId, + long tokenValue, byte[] ownerAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; @@ -3881,16 +3895,16 @@ public static String triggerParamListContract(byte[] contractAddress, String met System.out.println("RPC create call trx failed!"); System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); return null; } Transaction transaction = transactionExtention.getTransaction(); if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { + && transactionExtention.getResult() != null) { byte[] result = transactionExtention.getConstantResult(0).toByteArray(); System.out.println("message:" + transaction.getRet(0).getRet()); System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); System.out.println("Result:" + Hex.toHexString(result)); return null; } @@ -3898,7 +3912,7 @@ public static String triggerParamListContract(byte[] contractAddress, String met final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); Transaction.Builder transBuilder = Transaction.newBuilder(); Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); + .toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -3929,15 +3943,15 @@ public static String triggerParamListContract(byte[] contractAddress, String met } transaction = signTransaction(ecKey, transaction); System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); if (response.getResult() == false) { return null; } else { return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } @@ -3948,8 +3962,8 @@ public static String triggerParamListContract(byte[] contractAddress, String met */ public static Boolean exchangeCreate(byte[] firstTokenId, long firstTokenBalance, - byte[] secondTokenId, long secondTokenBalance, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + byte[] secondTokenId, long secondTokenBalance, byte[] ownerAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -3964,9 +3978,9 @@ public static Boolean exchangeCreate(byte[] firstTokenId, long firstTokenBalance ExchangeCreateContract.Builder builder = ExchangeCreateContract.newBuilder(); builder.setOwnerAddress(ByteString.copyFrom(owner)) - .setFirstTokenId(ByteString.copyFrom(firstTokenId)).setFirstTokenBalance(firstTokenBalance) - .setSecondTokenId(ByteString.copyFrom(secondTokenId)) - .setSecondTokenBalance(secondTokenBalance); + .setFirstTokenId(ByteString.copyFrom(firstTokenId)).setFirstTokenBalance(firstTokenBalance) + .setSecondTokenId(ByteString.copyFrom(secondTokenId)) + .setSecondTokenBalance(secondTokenBalance); ExchangeCreateContract contract = builder.build(); TransactionExtention transactionExtention = blockingStubFull.exchangeCreate(contract); if (transactionExtention == null) { @@ -3984,11 +3998,11 @@ public static Boolean exchangeCreate(byte[] firstTokenId, long firstTokenBalance return false; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); @@ -4000,7 +4014,7 @@ public static Boolean exchangeCreate(byte[] firstTokenId, long firstTokenBalance */ public static Boolean injectExchange(long exchangeId, byte[] tokenId, long quant, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -4015,7 +4029,7 @@ public static Boolean injectExchange(long exchangeId, byte[] tokenId, long quant ExchangeInjectContract.Builder builder = ExchangeInjectContract.newBuilder(); builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); + .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); ExchangeInjectContract contract = builder.build(); TransactionExtention transactionExtention = blockingStubFull.exchangeInject(contract); if (transactionExtention == null) { @@ -4033,18 +4047,18 @@ public static Boolean injectExchange(long exchangeId, byte[] tokenId, long quant return false; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response.getResult(); } public static Optional getExchangeList( - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { ExchangeList exchangeList = blockingStubFull.listExchanges(EmptyMessage.newBuilder().build()); return Optional.ofNullable(exchangeList); } @@ -4054,9 +4068,9 @@ public static Optional getExchangeList( */ public static Optional getExchangeList( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { ExchangeList exchangeList = blockingStubSolidity - .listExchanges(EmptyMessage.newBuilder().build()); + .listExchanges(EmptyMessage.newBuilder().build()); return Optional.ofNullable(exchangeList); } @@ -4066,9 +4080,9 @@ public static Optional getExchangeList( */ public static Optional getExchange(String id, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { BytesMessage request = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))).build(); + .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))).build(); Exchange exchange = blockingStubSolidity.getExchangeById(request); return Optional.ofNullable(exchange); } @@ -4078,9 +4092,9 @@ public static Optional getExchange(String id, */ public static Optional getExchange(String id, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { BytesMessage request = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))).build(); + .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))).build(); Exchange exchange = blockingStubFull.getExchangeById(request); return Optional.ofNullable(exchange); } @@ -4090,7 +4104,7 @@ public static Optional getExchange(String id, */ public static boolean exchangeWithdraw(long exchangeId, byte[] tokenId, long quant, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -4104,7 +4118,7 @@ public static boolean exchangeWithdraw(long exchangeId, byte[] tokenId, long qua ExchangeWithdrawContract.Builder builder = ExchangeWithdrawContract.newBuilder(); builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); + .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); ExchangeWithdrawContract contract = builder.build(); TransactionExtention transactionExtention = blockingStubFull.exchangeWithdraw(contract); if (transactionExtention == null) { @@ -4122,11 +4136,11 @@ public static boolean exchangeWithdraw(long exchangeId, byte[] tokenId, long qua return false; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response.getResult(); @@ -4137,8 +4151,8 @@ public static boolean exchangeWithdraw(long exchangeId, byte[] tokenId, long qua */ public static boolean exchangeTransaction(long exchangeId, byte[] tokenId, long quant, - long expected, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + long expected, byte[] ownerAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -4152,7 +4166,7 @@ public static boolean exchangeTransaction(long exchangeId, byte[] tokenId, long ExchangeTransactionContract.Builder builder = ExchangeTransactionContract.newBuilder(); builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant).setExpected(expected); + .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant).setExpected(expected); ExchangeTransactionContract contract = builder.build(); TransactionExtention transactionExtention = blockingStubFull.exchangeTransaction(contract); if (transactionExtention == null) { @@ -4170,11 +4184,11 @@ public static boolean exchangeTransaction(long exchangeId, byte[] tokenId, long return false; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response.getResult(); @@ -4185,12 +4199,12 @@ public static boolean exchangeTransaction(long exchangeId, byte[] tokenId, long */ public static String deployContractWithConstantParame(String contractName, String abiString, - String code, String constructorStr, String argsStr, String data, Long feeLimit, long value, - long consumeUserResourcePercent, String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { + String code, String constructorStr, String argsStr, String data, Long feeLimit, long value, + long consumeUserResourcePercent, String libraryAddress, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { return deployContractWithConstantParame(contractName, abiString, code, constructorStr, argsStr, - data, feeLimit, value, consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, - ownerAddress, blockingStubFull); + data, feeLimit, value, consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, + ownerAddress, blockingStubFull); } /** @@ -4198,10 +4212,10 @@ public static String deployContractWithConstantParame(String contractName, Strin */ public static String deployContractWithConstantParame(String contractName, String abiString, - String code, String constructorStr, String argsStr, String data, Long feeLimit, long value, - long consumeUserResourcePercent, long originEnergyLimit, String tokenId, long tokenValue, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { + String code, String constructorStr, String argsStr, String data, Long feeLimit, long value, + long consumeUserResourcePercent, long originEnergyLimit, String tokenId, long tokenValue, + String libraryAddress, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -4245,16 +4259,16 @@ public static String deployContractWithConstantParame(String contractName, Strin contractBuilder.setCallTokenValue(tokenValue); contractBuilder.setTokenId(Long.parseLong(tokenId)); CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + .build(); TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); + .deployContract(contractDeployContract); if (transactionExtention == null || !transactionExtention.getResult().getResult()) { System.out.println("RPC create trx failed!"); if (transactionExtention != null) { System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); } return null; } @@ -4262,7 +4276,7 @@ public static String deployContractWithConstantParame(String contractName, Strin final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); Transaction.Builder transBuilder = Transaction.newBuilder(); Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); + .toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -4294,19 +4308,19 @@ public static String deployContractWithConstantParame(String contractName, Strin } transaction = signTransaction(ecKey, transaction); System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); byte[] contractAddress = generateContractAddress(transaction, owner); System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); if (response.getResult() == false) { return null; } else { //logger.info("brodacast succesfully"); return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } } @@ -4315,8 +4329,8 @@ public static String deployContractWithConstantParame(String contractName, Strin */ public static Boolean freezeBalanceForReceiver(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, ByteString receiverAddressBytes, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + long freezeDuration, int resourceCode, ByteString receiverAddressBytes, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); byte[] address = addRess; long frozenBalance = freezeBalance; @@ -4334,7 +4348,7 @@ public static Boolean freezeBalanceForReceiver(byte[] addRess, long freezeBalanc ByteString byteAddreess = ByteString.copyFrom(address); builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); + .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); if (receiverAddressBytes != null) { builder.setReceiverAddress(receiverAddressBytes); } @@ -4357,13 +4371,13 @@ public static Boolean freezeBalanceForReceiver(byte[] addRess, long freezeBalanc */ public static Optional getDelegatedResource(byte[] fromAddress, - byte[] toAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + byte[] toAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString fromAddressBs = ByteString.copyFrom(fromAddress); ByteString toAddressBs = ByteString.copyFrom(toAddress); DelegatedResourceMessage request = DelegatedResourceMessage.newBuilder() - .setFromAddress(fromAddressBs).setToAddress(toAddressBs).build(); + .setFromAddress(fromAddressBs).setToAddress(toAddressBs).build(); DelegatedResourceList delegatedResource = blockingStubFull.getDelegatedResource(request); return Optional.ofNullable(delegatedResource); } @@ -4372,13 +4386,13 @@ public static Optional getDelegatedResource(byte[] fromAd * constructor. */ public static Optional getDelegatedResourceFromSolidity(byte[] fromAddress, - byte[] toAddress, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + byte[] toAddress, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString fromAddressBs = ByteString.copyFrom(fromAddress); ByteString toAddressBs = ByteString.copyFrom(toAddress); DelegatedResourceMessage request = DelegatedResourceMessage.newBuilder() - .setFromAddress(fromAddressBs).setToAddress(toAddressBs).build(); + .setFromAddress(fromAddressBs).setToAddress(toAddressBs).build(); DelegatedResourceList delegatedResource = blockingStubFull.getDelegatedResource(request); return Optional.ofNullable(delegatedResource); } @@ -4389,7 +4403,7 @@ public static Optional getDelegatedResourceFromSolidity(b */ public static Optional getDelegatedResourceAccountIndex( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { + byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString addressBs = ByteString.copyFrom(address); @@ -4397,7 +4411,7 @@ public static Optional getDelegatedResourceAccoun BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(addressBs).build(); DelegatedResourceAccountIndex accountIndex = blockingStubFull - .getDelegatedResourceAccountIndex(bytesMessage); + .getDelegatedResourceAccountIndex(bytesMessage); return Optional.ofNullable(accountIndex); } @@ -4406,8 +4420,8 @@ public static Optional getDelegatedResourceAccoun * constructor. */ public static Optional - getDelegatedResourceAccountIndexFromSolidity(byte[] address, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + getDelegatedResourceAccountIndexFromSolidity(byte[] address, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString addressBs = ByteString.copyFrom(address); @@ -4415,7 +4429,7 @@ public static Optional getDelegatedResourceAccoun BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(addressBs).build(); DelegatedResourceAccountIndex accountIndex = blockingStubFull - .getDelegatedResourceAccountIndex(bytesMessage); + .getDelegatedResourceAccountIndex(bytesMessage); return Optional.ofNullable(accountIndex); } @@ -4425,7 +4439,7 @@ public static Optional getDelegatedResourceAccoun */ public static AssetIssueContract getAssetIssueByName(String assetName, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); @@ -4436,7 +4450,7 @@ public static AssetIssueContract getAssetIssueByName(String assetName, * constructor. */ public static AssetIssueContract getAssetIssueByNameFromSolidity(String assetName, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); @@ -4449,7 +4463,7 @@ public static AssetIssueContract getAssetIssueByNameFromSolidity(String assetNam */ public static Optional getAssetIssueListByName(String assetName, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); @@ -4461,7 +4475,7 @@ public static Optional getAssetIssueListByName(String assetName, * constructor. */ public static Optional getAssetIssueListByNameFromSolidity(String assetName, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); @@ -4473,9 +4487,9 @@ public static Optional getAssetIssueListByNameFromSolidity(Strin * constructor. */ public static Optional listAssetIssueFromSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { GrpcAPI.AssetIssueList assetIssueList = blockingStubFull - .getAssetIssueList(EmptyMessage.newBuilder().build()); + .getAssetIssueList(EmptyMessage.newBuilder().build()); return Optional.ofNullable(assetIssueList); } @@ -4483,12 +4497,12 @@ public static Optional listAssetIssueFromSolidity( * constructor. */ public static Optional listAssetIssuepaginatedFromSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull, Long offset, Long limit) { + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull, Long offset, Long limit) { GrpcAPI.PaginatedMessage.Builder pageMessageBuilder = GrpcAPI.PaginatedMessage.newBuilder(); pageMessageBuilder.setOffset(offset); pageMessageBuilder.setLimit(limit); AssetIssueList assetIssueList = blockingStubFull - .getPaginatedAssetIssueList(pageMessageBuilder.build()); + .getPaginatedAssetIssueList(pageMessageBuilder.build()); return Optional.ofNullable(assetIssueList); } @@ -4497,9 +4511,9 @@ public static Optional listAssetIssuepaginatedFromSolidi * constructor. */ public static Optional listWitnesses( - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { GrpcAPI.WitnessList witnessList = blockingStubFull - .listWitnesses(EmptyMessage.newBuilder().build()); + .listWitnesses(EmptyMessage.newBuilder().build()); return Optional.ofNullable(witnessList); } @@ -4507,9 +4521,9 @@ public static Optional listWitnesses( * constructor. */ public static Optional listWitnessesFromSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { GrpcAPI.WitnessList witnessList = blockingStubFull - .listWitnesses(EmptyMessage.newBuilder().build()); + .listWitnesses(EmptyMessage.newBuilder().build()); return Optional.ofNullable(witnessList); } @@ -4519,7 +4533,7 @@ public static Optional listWitnessesFromSolidity( */ public static AssetIssueContract getAssetIssueById(String assetId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString assetIdBs = ByteString.copyFrom(assetId.getBytes()); BytesMessage request = BytesMessage.newBuilder().setValue(assetIdBs).build(); @@ -4530,7 +4544,7 @@ public static AssetIssueContract getAssetIssueById(String assetId, * constructor. */ public static AssetIssueContract getAssetIssueByIdFromSolidity(String assetId, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString assetIdBs = ByteString.copyFrom(assetId.getBytes()); BytesMessage request = BytesMessage.newBuilder().setValue(assetIdBs).build(); @@ -4541,7 +4555,7 @@ public static AssetIssueContract getAssetIssueByIdFromSolidity(String assetId, * constructor. */ public static Optional getAssetIssueByAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString addressBs = ByteString.copyFrom(address); Account request = Account.newBuilder().setAddress(addressBs).build(); @@ -4595,7 +4609,7 @@ private static Permission json2Permission(JSONObject json) { * constructor. */ public static boolean accountPermissionUpdate(String permissionJson, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] priKeys) { + WalletGrpc.WalletBlockingStub blockingStubFull, String[] priKeys) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -4649,7 +4663,7 @@ public static boolean accountPermissionUpdate(String permissionJson, byte[] owne return false; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response.getResult(); @@ -4660,7 +4674,7 @@ public static boolean accountPermissionUpdate(String permissionJson, byte[] owne * constructor. */ public static long getFreezeBalanceCount(byte[] accountAddress, String ecKey, Long targetEnergy, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { //Precision change as the entire network freezes AccountResourceMessage resourceInfo = getAccountResource(accountAddress, blockingStubFull); @@ -4686,8 +4700,8 @@ public static long getFreezeBalanceCount(byte[] accountAddress, String ecKey, Lo // totalEnergyLimit / (totalEnergyWeight + needBalance) = needEnergy / needBalance final BigInteger totalEnergyWeightBi = BigInteger.valueOf(totalEnergyWeight); long needBalance = totalEnergyWeightBi.multiply(BigInteger.valueOf(1_000_000)) - .multiply(BigInteger.valueOf(targetEnergy)) - .divide(BigInteger.valueOf(totalEnergyLimit - targetEnergy)).longValue(); + .multiply(BigInteger.valueOf(targetEnergy)) + .divide(BigInteger.valueOf(totalEnergyLimit - targetEnergy)).longValue(); logger.info("getFreezeBalanceCount, needBalance: " + needBalance); @@ -4702,7 +4716,7 @@ public static long getFreezeBalanceCount(byte[] accountAddress, String ecKey, Lo * constructor. */ public static Long getAssetIssueValue(byte[] accountAddress, ByteString assetIssueId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Long assetIssueCount = 0L; Account contractAccount = queryAccount(accountAddress, blockingStubFull); Map createAssetIssueMap = contractAccount.getAssetV2Map(); @@ -4744,7 +4758,7 @@ public static String byte2HexStr(byte[] b, int offset, int length) { * constructor. */ public static Transaction addTransactionSign(Transaction transaction, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -4757,7 +4771,7 @@ public static Transaction addTransactionSign(Transaction transaction, String pri Transaction.Builder transactionBuilderSigned = transaction.toBuilder(); byte[] hash = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()); + transaction.getRawData().toByteArray()); ECDSASignature signature = ecKey.sign(hash); ByteString bsSign = ByteString.copyFrom(signature.toByteArray()); @@ -4770,9 +4784,9 @@ public static Transaction addTransactionSign(Transaction transaction, String pri * constructor. */ public static GrpcAPI.Return deployContractAndGetResponse(String contractName, String abiString, - String code, String data, Long feeLimit, long value, long consumeUserResourcePercent, - long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, - byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + String code, String data, Long feeLimit, long value, long consumeUserResourcePercent, + long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, + byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -4815,16 +4829,16 @@ public static GrpcAPI.Return deployContractAndGetResponse(String contractName, S contractBuilder.setCallTokenValue(tokenValue); contractBuilder.setTokenId(Long.parseLong(tokenId)); CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + .build(); TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); + .deployContract(contractDeployContract); if (transactionExtention == null || !transactionExtention.getResult().getResult()) { System.out.println("RPC create trx failed!"); if (transactionExtention != null) { System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); } return null; } @@ -4832,7 +4846,7 @@ public static GrpcAPI.Return deployContractAndGetResponse(String contractName, S final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); Transaction.Builder transBuilder = Transaction.newBuilder(); Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); + .toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -4864,11 +4878,11 @@ public static GrpcAPI.Return deployContractAndGetResponse(String contractName, S } transaction = signTransaction(ecKey, transaction); System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); byte[] contractAddress = generateContractAddress(transaction, owner); System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response; @@ -4878,8 +4892,8 @@ public static GrpcAPI.Return deployContractAndGetResponse(String contractName, S * constructor. */ public static GrpcAPI.Return triggerContractAndGetResponse(byte[] contractAddress, String method, - String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, + byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -4911,16 +4925,16 @@ public static GrpcAPI.Return triggerContractAndGetResponse(byte[] contractAddres System.out.println("RPC create call trx failed!"); System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); return null; } Transaction transaction = transactionExtention.getTransaction(); if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { + && transactionExtention.getResult() != null) { byte[] result = transactionExtention.getConstantResult(0).toByteArray(); System.out.println("message:" + transaction.getRet(0).getRet()); System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); System.out.println("Result:" + Hex.toHexString(result)); return null; } @@ -4928,7 +4942,7 @@ public static GrpcAPI.Return triggerContractAndGetResponse(byte[] contractAddres final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); Transaction.Builder transBuilder = Transaction.newBuilder(); Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); + .toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -4959,8 +4973,8 @@ public static GrpcAPI.Return triggerContractAndGetResponse(byte[] contractAddres } transaction = signTransaction(ecKey, transaction); System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response; } @@ -4969,7 +4983,7 @@ public static GrpcAPI.Return triggerContractAndGetResponse(byte[] contractAddres * constructor. */ public static boolean updateEnergyLimit(byte[] contractAddress, long originEnergyLimit, - String priKey, byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + String priKey, byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -4988,13 +5002,13 @@ public static boolean updateEnergyLimit(byte[] contractAddress, long originEnerg UpdateEnergyLimitContract updateEnergyLimitContract = builder.build(); TransactionExtention transactionExtention = blockingStubFull - .updateEnergyLimit(updateEnergyLimitContract); + .updateEnergyLimit(updateEnergyLimitContract); if (transactionExtention == null || !transactionExtention.getResult().getResult()) { System.out.println("RPC create trx failed!"); if (transactionExtention != null) { System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); } return false; } @@ -5013,7 +5027,7 @@ public static boolean updateEnergyLimit(byte[] contractAddress, long originEnerg return false; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response.getResult(); @@ -5023,7 +5037,7 @@ public static boolean updateEnergyLimit(byte[] contractAddress, long originEnerg * constructor. */ public static GrpcAPI.Return accountPermissionUpdateForResponse(String permissionJson, - byte[] owner, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + byte[] owner, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -5077,7 +5091,7 @@ public static GrpcAPI.Return accountPermissionUpdateForResponse(String permissio return ret; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); @@ -5085,7 +5099,7 @@ public static GrpcAPI.Return accountPermissionUpdateForResponse(String permissio } public static TransactionApprovedList getTransactionApprovedList(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { return blockingStubFull.getTransactionApprovedList(transaction); } @@ -5093,7 +5107,7 @@ public static TransactionApprovedList getTransactionApprovedList(Transaction tra * constructor. */ public static long getFreezeBalanceNetCount(byte[] accountAddress, String ecKey, Long targetNet, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { //Precision change as the entire network freezes AccountResourceMessage resourceInfo = getAccountResource(accountAddress, blockingStubFull); @@ -5118,15 +5132,15 @@ public static long getFreezeBalanceNetCount(byte[] accountAddress, String ecKey, // totalNetLimit / (totalNetWeight + needBalance) = needNet / needBalance final BigInteger totalNetWeightBi = BigInteger.valueOf(totalNetWeight); long needBalance = totalNetWeightBi.multiply(BigInteger.valueOf(1_000_000)) - .multiply(BigInteger.valueOf(targetNet)) - .divide(BigInteger.valueOf(totalNetLimit - targetNet)).longValue(); + .multiply(BigInteger.valueOf(targetNet)) + .divide(BigInteger.valueOf(totalNetLimit - targetNet)).longValue(); logger.info("getFreezeBalanceNetCount, needBalance: " + needBalance); if (needBalance < 1000000L) { needBalance = 1000000L; logger - .info("getFreezeBalanceNetCount, needBalance less than 1 TRX, modify to: " + needBalance); + .info("getFreezeBalanceNetCount, needBalance less than 1 TRX, modify to: " + needBalance); } return needBalance; } @@ -5135,11 +5149,11 @@ public static long getFreezeBalanceNetCount(byte[] accountAddress, String ecKey, * constructor. */ public static GrpcAPI.Return broadcastTransaction(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { int i = 10; GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); while (!response.getResult() && response.getCode() == response_code.SERVER_BUSY - && i > 0) { + && i > 0) { try { Thread.sleep(300); } catch (InterruptedException e) { @@ -5161,14 +5175,14 @@ public static GrpcAPI.Return broadcastTransaction(Transaction transaction, * constructor. */ public static GrpcAPI.Return broadcastTransactionBoth(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletGrpc.WalletBlockingStub blockingStubFull1) { + WalletGrpc.WalletBlockingStub blockingStubFull, + WalletGrpc.WalletBlockingStub blockingStubFull1) { int i = 10; waitProduceNextBlock(blockingStubFull1); GrpcAPI.Return response = blockingStubFull1.broadcastTransaction(transaction); GrpcAPI.Return response1 = blockingStubFull.broadcastTransaction(transaction); while (response.getResult() == false && response.getCode() == response_code.SERVER_BUSY - && i > 0) { + && i > 0) { try { Thread.sleep(300); } catch (InterruptedException e) { @@ -5218,7 +5232,7 @@ public static String exec(String command) throws InterruptedException { */ public static HashMap getBycodeAbi(String solFile, String contractName) { final String compile = Configuration.getByPath("testng.conf") - .getString("defaultParameter.solidityCompile"); + .getString("defaultParameter.solidityCompile"); String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); String outputPath = "src/test/resources/soliditycode//output" + dirPath; @@ -5238,9 +5252,9 @@ public static HashMap getBycodeAbi(String solFile, String contra logger.debug("solFile: " + solFile); logger.debug("outputPath: " + outputPath); String cmd = - compile + " --optimize --bin --abi --overwrite " + absolutePath + "/" - + solFile + " -o " - + absolutePath + "/" + outputPath; + compile + " --optimize --bin --abi --overwrite " + absolutePath + "/" + + solFile + " -o " + + absolutePath + "/" + outputPath; logger.info("cmd: " + cmd); String byteCode = null; @@ -5299,7 +5313,7 @@ public static String fileRead(String filePath, boolean isLibrary) throws Excepti * constructor. */ public static HashMap getBycodeAbiForLibrary(String solFile, - String contractName) { + String contractName) { HashMap retMap = null; String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); String outputPath = "src/test/resources/soliditycode/output" + dirPath; @@ -5319,8 +5333,8 @@ public static HashMap getBycodeAbiForLibrary(String solFile, * constructor. */ public static String triggerConstantContract(byte[] contractAddress, String method, - String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, + byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -5348,21 +5362,21 @@ public static String triggerConstantContract(byte[] contractAddress, String meth TriggerSmartContract triggerContract = builder.build(); TransactionExtention transactionExtention = blockingStubFull - .triggerConstantContract(triggerContract); + .triggerConstantContract(triggerContract); if (transactionExtention == null || !transactionExtention.getResult().getResult()) { System.out.println("RPC create call trx failed!"); System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); return null; } Transaction transaction = transactionExtention.getTransaction(); if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { + && transactionExtention.getResult() != null) { byte[] result = transactionExtention.getConstantResult(0).toByteArray(); System.out.println("message:" + transaction.getRet(0).getRet()); System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); System.out.println("Result:" + Hex.toHexString(result)); return null; } @@ -5370,7 +5384,7 @@ public static String triggerConstantContract(byte[] contractAddress, String meth final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); Transaction.Builder transBuilder = Transaction.newBuilder(); Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); + .toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -5401,15 +5415,15 @@ public static String triggerConstantContract(byte[] contractAddress, String meth } transaction = signTransaction(ecKey, transaction); System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); if (response.getResult() == false) { return null; } else { return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } } @@ -5417,9 +5431,9 @@ public static String triggerConstantContract(byte[] contractAddress, String meth * constructor. */ public static TransactionExtention triggerConstantContractForExtentionOnSolidity( - byte[] contractAddress, String method, String argsStr, Boolean isHex, long callValue, - long feeLimit, String tokenId, long tokenValue, byte[] ownerAddress, String priKey, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + byte[] contractAddress, String method, String argsStr, Boolean isHex, long callValue, + long feeLimit, String tokenId, long tokenValue, byte[] ownerAddress, String priKey, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -5447,7 +5461,7 @@ public static TransactionExtention triggerConstantContractForExtentionOnSolidity TriggerSmartContract triggerContract = builder.build(); TransactionExtention transactionExtention = blockingStubSolidity - .triggerConstantContract(triggerContract); + .triggerConstantContract(triggerContract); return transactionExtention; } @@ -5456,7 +5470,7 @@ public static TransactionExtention triggerConstantContractForExtentionOnSolidity * constructor. */ public static String clearContractAbi(byte[] contractAddress, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -5480,16 +5494,16 @@ public static String clearContractAbi(byte[] contractAddress, byte[] ownerAddres System.out.println("RPC create call trx failed!"); System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); return null; } Transaction transaction = transactionExtention.getTransaction(); if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { + && transactionExtention.getResult() != null) { byte[] result = transactionExtention.getConstantResult(0).toByteArray(); System.out.println("message:" + transaction.getRet(0).getRet()); System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); System.out.println("Result:" + Hex.toHexString(result)); return null; } @@ -5497,7 +5511,7 @@ public static String clearContractAbi(byte[] contractAddress, byte[] ownerAddres final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); Transaction.Builder transBuilder = Transaction.newBuilder(); Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); + .toBuilder(); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { ByteString s = transactionExtention.getTransaction().getSignature(i); @@ -5527,15 +5541,15 @@ public static String clearContractAbi(byte[] contractAddress, byte[] ownerAddres } transaction = signTransaction(ecKey, transaction); System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); if (response.getResult() == false) { return null; } else { return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } } @@ -5543,7 +5557,7 @@ public static String clearContractAbi(byte[] contractAddress, byte[] ownerAddres * constructor. */ public static TransactionExtention clearContractAbiForExtention(byte[] contractAddress, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -5571,9 +5585,9 @@ public static TransactionExtention clearContractAbiForExtention(byte[] contractA * constructor. */ public static TransactionExtention triggerConstantContractForExtention(byte[] contractAddress, - String method, String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, - long tokenValue, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + String method, String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, + long tokenValue, byte[] ownerAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -5604,7 +5618,7 @@ public static TransactionExtention triggerConstantContractForExtention(byte[] co builder.setCallTokenValue(tokenValue); TriggerSmartContract triggerContract = builder.build(); TransactionExtention transactionExtention = blockingStubFull - .triggerConstantContract(triggerContract); + .triggerConstantContract(triggerContract); return transactionExtention; @@ -5614,10 +5628,10 @@ public static TransactionExtention triggerConstantContractForExtention(byte[] co * constructor. */ public static TransactionExtention triggerSolidityContractForExtention(byte[] contractAddress, - String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, - String priKey, WalletSolidityGrpc.WalletSolidityBlockingStub solidityBlockingStubFull) { + String method, String argsStr, + Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, + byte[] ownerAddress, + String priKey, WalletSolidityGrpc.WalletSolidityBlockingStub solidityBlockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -5645,7 +5659,7 @@ public static TransactionExtention triggerSolidityContractForExtention(byte[] co TriggerSmartContract triggerContract = builder.build(); TransactionExtention transactionExtention = solidityBlockingStubFull - .triggerConstantContract(triggerContract); + .triggerConstantContract(triggerContract); return transactionExtention; } @@ -5655,9 +5669,9 @@ public static TransactionExtention triggerSolidityContractForExtention(byte[] co */ public static TransactionExtention triggerContractForExtention(byte[] contractAddress, - String method, String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, - long tokenValue, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + String method, String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, + long tokenValue, byte[] ownerAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -5726,9 +5740,9 @@ public static String create2(String[] parameters) { * constructor. */ public static boolean sendShieldCoin(byte[] publicZenTokenOwnerAddress, long fromAmount, - ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, - byte[] publicZenTokenToAddress, long toAmount, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, + byte[] publicZenTokenToAddress, long toAmount, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -5795,7 +5809,7 @@ public static boolean sendShieldCoin(byte[] publicZenTokenOwnerAddress, long fro } IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); + .getMerkleTreeVoucherInfo(request.build()); spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); @@ -5803,19 +5817,19 @@ public static boolean sendShieldCoin(byte[] publicZenTokenOwnerAddress, long fro } else { byte[] ovk = ByteArray - .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); + .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); builder.setOvk(ByteString.copyFrom(ovk)); } if (shieldOutputList.size() > 0) { for (int i = 0; i < shieldOutputList.size(); ++i) { builder - .addShieldedReceives(ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); + .addShieldedReceives(ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); } } TransactionExtention transactionExtention = blockingStubFull - .createShieldedTransaction(builder.build()); + .createShieldedTransaction(builder.build()); if (transactionExtention == null) { return false; } @@ -5831,21 +5845,21 @@ public static boolean sendShieldCoin(byte[] publicZenTokenOwnerAddress, long fro return false; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); Any any = transaction.getRawData().getContract(0).getParameter(); try { ShieldedTransferContract shieldedTransferContract = any - .unpack(ShieldedTransferContract.class); + .unpack(ShieldedTransferContract.class); if (shieldedTransferContract.getFromAmount() > 0 || fromAmount == 321321) { transaction = signTransactionForShield(ecKey, transaction); System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); } else { System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); } } catch (Exception e) { System.out.println(e); @@ -5857,9 +5871,9 @@ public static boolean sendShieldCoin(byte[] publicZenTokenOwnerAddress, long fro * constructor. */ public static boolean sendShieldCoinWithoutAsk(byte[] publicZenTokenOwnerAddress, long fromAmount, - ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, - byte[] publicZenTokenToAddress, long toAmount, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, + byte[] publicZenTokenToAddress, long toAmount, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -5890,7 +5904,7 @@ public static boolean sendShieldCoinWithoutAsk(byte[] publicZenTokenOwnerAddress outPointBuild.setIndex(noteTx.getIndex()); request.addOutPoints(outPointBuild.build()); IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); + .getMerkleTreeVoucherInfo(request.build()); if (merkleVoucherInfo.getVouchersCount() != 1) { System.out.println("Can't get all merkel tree, please check the notes."); return false; @@ -5907,7 +5921,7 @@ public static boolean sendShieldCoinWithoutAsk(byte[] publicZenTokenOwnerAddress ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); System.arraycopy(expandedSpendingKey.getAsk(), 0, ask, 0, 32); builder.setAk( - ByteString.copyFrom(ExpandedSpendingKey.getAkFromAsk(expandedSpendingKey.getAsk()))); + ByteString.copyFrom(ExpandedSpendingKey.getAkFromAsk(expandedSpendingKey.getAsk()))); builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); } catch (Exception e) { @@ -5942,32 +5956,32 @@ public static boolean sendShieldCoinWithoutAsk(byte[] publicZenTokenOwnerAddress } else { byte[] ovk = ByteArray - .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); + .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); builder.setOvk(ByteString.copyFrom(ovk)); } if (shieldOutputList.size() > 0) { for (int i = 0; i < shieldOutputList.size(); ++i) { builder - .addShieldedReceives(ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); + .addShieldedReceives(ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); } } TransactionExtention transactionExtention = blockingStubFull - .createShieldedTransactionWithoutSpendAuthSig(builder.build()); + .createShieldedTransactionWithoutSpendAuthSig(builder.build()); if (transactionExtention == null) { System.out.println("sendShieldCoinWithoutAsk failure."); return false; } BytesMessage trxHash = blockingStubFull - .getShieldTransactionHash(transactionExtention.getTransaction()); + .getShieldTransactionHash(transactionExtention.getTransaction()); if (trxHash == null || trxHash.getValue().toByteArray().length != 32) { System.out.println("sendShieldCoinWithoutAsk get transaction hash failure."); return false; } Transaction transaction = transactionExtention.getTransaction(); if (transaction.getRawData().getContract(0).getType() - != ContractType.ShieldedTransferContract) { + != ContractType.ShieldedTransferContract) { System.out.println("This method only for ShieldedTransferContract, please check!"); return false; } @@ -5977,7 +5991,7 @@ public static boolean sendShieldCoinWithoutAsk(byte[] publicZenTokenOwnerAddress ShieldedTransferContract shieldContract = any.unpack(ShieldedTransferContract.class); List spendDescList = shieldContract.getSpendDescriptionList(); ShieldedTransferContract.Builder contractBuild = shieldContract.toBuilder() - .clearSpendDescription(); + .clearSpendDescription(); for (int i = 0; i < spendDescList.size(); i++) { SpendAuthSigParameters.Builder builder1 = SpendAuthSigParameters.newBuilder(); @@ -5987,15 +6001,15 @@ public static boolean sendShieldCoinWithoutAsk(byte[] publicZenTokenOwnerAddress SpendDescription.Builder spendDescription = spendDescList.get(i).toBuilder(); BytesMessage authSig = blockingStubFull.createSpendAuthSig(builder1.build()); spendDescription - .setSpendAuthoritySignature(ByteString.copyFrom(authSig.getValue().toByteArray())); + .setSpendAuthoritySignature(ByteString.copyFrom(authSig.getValue().toByteArray())); contractBuild.addSpendDescription(spendDescription.build()); } Transaction.raw.Builder rawBuilder = transaction.toBuilder().getRawDataBuilder() - .clearContract().addContract( - Transaction.Contract.newBuilder().setType(ContractType.ShieldedTransferContract) - .setParameter(Any.pack(contractBuild.build())).build()); + .clearContract().addContract( + Transaction.Contract.newBuilder().setType(ContractType.ShieldedTransferContract) + .setParameter(Any.pack(contractBuild.build())).build()); transaction = transaction.toBuilder().clearRawData().setRawData(rawBuilder).build(); @@ -6016,28 +6030,28 @@ public static boolean sendShieldCoinWithoutAsk(byte[] publicZenTokenOwnerAddress return false; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); if (transaction1.getRawData().getContract(0).getType() - != ContractType.ShieldedTransferContract) { + != ContractType.ShieldedTransferContract) { transaction1 = signTransaction(ecKey, transaction1); } else { Any any1 = transaction1.getRawData().getContract(0).getParameter(); ShieldedTransferContract shieldedTransferContract = any1 - .unpack(ShieldedTransferContract.class); + .unpack(ShieldedTransferContract.class); if (shieldedTransferContract.getFromAmount() > 0) { transaction1 = signTransactionForShield(ecKey, transaction1); System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction1.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction1.getRawData().toByteArray()))); } } } catch (Exception e) { System.out.println(e); } System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction1.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction1.getRawData().toByteArray()))); return broadcastTransaction(transaction1, blockingStubFull).getResult(); } @@ -6046,7 +6060,7 @@ public static boolean sendShieldCoinWithoutAsk(byte[] publicZenTokenOwnerAddress * constructor. */ public static List addShieldOutputList(List shieldOutList, String shieldToAddress, - String toAmountString, String menoString) { + String toAmountString, String menoString) { String shieldAddress = shieldToAddress; String amountString = toAmountString; if (menoString.equals("null")) { @@ -6105,7 +6119,7 @@ public static Optional generateShieldAddress() { * constructor. */ public static DecryptNotes listShieldNote(Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); Long startBlockNum = 0L; @@ -6126,7 +6140,7 @@ public static DecryptNotes listShieldNote(Optional shieldAddr * constructor. */ public static DecryptNotes getShieldNotesByIvk(Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); Long startBlockNum = 0L; @@ -6148,8 +6162,8 @@ public static DecryptNotes getShieldNotesByIvk(Optional shiel * constructor. */ public static DecryptNotesMarked getShieldNotesAndMarkByIvk( - Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { + Optional shieldAddressInfo, + WalletGrpc.WalletBlockingStub blockingStubFull) { Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); Long startBlockNum = 0L; @@ -6178,10 +6192,10 @@ public static DecryptNotesMarked getShieldNotesAndMarkByIvk( * constructor. */ public static DecryptNotesMarked getShieldNotesAndMarkByIvkOnSolidity( - Optional shieldAddressInfo, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + Optional shieldAddressInfo, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { Block currentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); Long startBlockNum = 0L; if (currentBlockNum > 100) { @@ -6209,7 +6223,7 @@ public static DecryptNotesMarked getShieldNotesAndMarkByIvkOnSolidity( * constructor. */ public static Integer getShieldNotesCount(Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); @@ -6247,10 +6261,10 @@ public static Integer getShieldNotesCount(Optional shieldAddr * constructor. */ public static DecryptNotes getShieldNotesByIvkOnSolidity( - Optional shieldAddressInfo, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + Optional shieldAddressInfo, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { Block currentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); Long startBlockNum = 0L; if (currentBlockNum > 100) { @@ -6270,7 +6284,7 @@ public static DecryptNotes getShieldNotesByIvkOnSolidity( * constructor. */ public static DecryptNotes getShieldNotesByOvk(Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); Long startBlockNum = 0L; @@ -6291,10 +6305,10 @@ public static DecryptNotes getShieldNotesByOvk(Optional shiel * constructor. */ public static DecryptNotes getShieldNotesByOvkOnSolidity( - Optional shieldAddressInfo, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + Optional shieldAddressInfo, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { Block currentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); Long startBlockNum = 0L; if (currentBlockNum > 100) { @@ -6321,7 +6335,7 @@ public static String getMemo(Note note) { * constructor. */ public static SpendResult getSpendResult(ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); @@ -6329,7 +6343,7 @@ public static SpendResult getSpendResult(ShieldAddressInfo shieldAddressInfo, No outPointBuild.setIndex(noteTx.getIndex()); request.addOutPoints(outPointBuild.build()); Optional merkleVoucherInfo = Optional - .of(blockingStubFull.getMerkleTreeVoucherInfo(request.build())); + .of(blockingStubFull.getMerkleTreeVoucherInfo(request.build())); if (merkleVoucherInfo.isPresent() && merkleVoucherInfo.get().getVouchersCount() > 0) { NoteParameters.Builder builder = NoteParameters.newBuilder(); @@ -6364,14 +6378,14 @@ public static SpendResult getSpendResult(ShieldAddressInfo shieldAddressInfo, No * constructor. */ public static SpendResult getSpendResultOnSolidity(ShieldAddressInfo shieldAddressInfo, - NoteTx noteTx, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + NoteTx noteTx, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); outPointBuild.setIndex(noteTx.getIndex()); request.addOutPoints(outPointBuild.build()); Optional merkleVoucherInfo = Optional - .of(blockingStubSolidity.getMerkleTreeVoucherInfo(request.build())); + .of(blockingStubSolidity.getMerkleTreeVoucherInfo(request.build())); if (merkleVoucherInfo.isPresent() && merkleVoucherInfo.get().getVouchersCount() > 0) { NoteParameters.Builder builder = NoteParameters.newBuilder(); @@ -6401,14 +6415,14 @@ public static SpendResult getSpendResultOnSolidity(ShieldAddressInfo shieldAddre * constructor. */ public static String getShieldNullifier(ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); outPointBuild.setIndex(noteTx.getIndex()); request.addOutPoints(outPointBuild.build()); IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); + .getMerkleTreeVoucherInfo(request.build()); if (merkleVoucherInfo.getVouchersCount() < 1) { System.out.println("get merkleVoucherInfo failure."); return null; @@ -6445,9 +6459,9 @@ public static String getShieldNullifier(ShieldAddressInfo shieldAddressInfo, Not * constructor. */ public static String sendShieldCoinGetTxid(byte[] publicZenTokenOwnerAddress, long fromAmount, - ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, - byte[] publicZenTokenToAddress, long toAmount, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, + byte[] publicZenTokenToAddress, long toAmount, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -6514,7 +6528,7 @@ public static String sendShieldCoinGetTxid(byte[] publicZenTokenOwnerAddress, lo } IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); + .getMerkleTreeVoucherInfo(request.build()); spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); @@ -6522,19 +6536,19 @@ public static String sendShieldCoinGetTxid(byte[] publicZenTokenOwnerAddress, lo } else { byte[] ovk = ByteArray - .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); + .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); builder.setOvk(ByteString.copyFrom(ovk)); } if (shieldOutputList.size() > 0) { for (int i = 0; i < shieldOutputList.size(); ++i) { builder - .addShieldedReceives(ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); + .addShieldedReceives(ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); } } TransactionExtention transactionExtention = blockingStubFull - .createShieldedTransaction(builder.build()); + .createShieldedTransaction(builder.build()); if (transactionExtention == null) { return null; } @@ -6550,29 +6564,29 @@ public static String sendShieldCoinGetTxid(byte[] publicZenTokenOwnerAddress, lo return null; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); Any any = transaction.getRawData().getContract(0).getParameter(); try { ShieldedTransferContract shieldedTransferContract = any - .unpack(ShieldedTransferContract.class); + .unpack(ShieldedTransferContract.class); if (shieldedTransferContract.getFromAmount() > 0) { transaction = signTransactionForShield(ecKey, transaction); System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); } else { System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); } } catch (Exception e) { System.out.println(e); } broadcastTransaction(transaction, blockingStubFull); return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } /** @@ -6588,8 +6602,8 @@ public static byte[] decode58Check(String input) { byte[] hash0 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), decodeData); byte[] hash1 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), hash0); if (hash1[0] == decodeCheck[decodeData.length] && hash1[1] == decodeCheck[decodeData.length + 1] - && hash1[2] == decodeCheck[decodeData.length + 2] && hash1[3] == decodeCheck[ - decodeData.length + 3]) { + && hash1[2] == decodeCheck[decodeData.length + 2] && hash1[3] == decodeCheck[ + decodeData.length + 3]) { return decodeData; } return null; @@ -6599,7 +6613,7 @@ public static byte[] decode58Check(String input) { * constructor. */ public static void freedResource(byte[] fromAddress, String priKey, byte[] toAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { long balance = PublicMethed.queryAccount(fromAddress, blockingStubFull).getBalance(); sendcoin(toAddress, balance - 500000, fromAddress, priKey, blockingStubFull); } @@ -6622,7 +6636,7 @@ public static String parametersString(List parameters) { inputArr[i++] = "[" + sb.toString() + "]"; } else { inputArr[i++] = - (parameter instanceof String) ? ("\"" + parameter + "\"") : ("" + parameter); + (parameter instanceof String) ? ("\"" + parameter + "\"") : ("" + parameter); } } String input = StringUtils.join(inputArr, ','); @@ -6655,7 +6669,7 @@ public static String bytes32ToString(byte[] bytes) { */ public static Return transferAssetForReturn(byte[] to, byte[] assertName, long amount, - byte[] address, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + byte[] address, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -6692,7 +6706,7 @@ public static Return transferAssetForReturn(byte[] to, byte[] assertName, long a */ public static Return sendcoinForReturn(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); //String priKey = testKey002; ECKey temKey = null; @@ -6725,7 +6739,7 @@ public static Return sendcoinForReturn(byte[] to, long amount, byte[] owner, Str */ public static Transaction sendcoinForTransaction(byte[] to, long amount, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); //String priKey = testKey002; ECKey temKey = null; @@ -6754,8 +6768,8 @@ public static Transaction sendcoinForTransaction(byte[] to, long amount, byte[] * constructor. */ public static String marketSellAsset(byte[] owner, String priKey, byte[] sellTokenId, - long sellTokenQuantity, byte[] buyTokenId, long buyTokenQuantity, - WalletGrpc.WalletBlockingStub blockingStubFull) { + long sellTokenQuantity, byte[] buyTokenId, long buyTokenQuantity, + WalletGrpc.WalletBlockingStub blockingStubFull) { ECKey temKey = null; try { @@ -6767,13 +6781,13 @@ public static String marketSellAsset(byte[] owner, String priKey, byte[] sellTok final ECKey ecKey = temKey; MarketContract.MarketSellAssetContract.Builder builder = MarketContract.MarketSellAssetContract - .newBuilder(); + .newBuilder(); builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setSellTokenQuantity(sellTokenQuantity) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .setBuyTokenQuantity(buyTokenQuantity); + .setOwnerAddress(ByteString.copyFrom(owner)) + .setSellTokenId(ByteString.copyFrom(sellTokenId)) + .setSellTokenQuantity(sellTokenQuantity) + .setBuyTokenId(ByteString.copyFrom(buyTokenId)) + .setBuyTokenQuantity(buyTokenQuantity); TransactionExtention transactionExtention = blockingStubFull.marketSellAsset(builder.build()); if (transactionExtention == null) { @@ -6792,7 +6806,7 @@ public static String marketSellAsset(byte[] owner, String priKey, byte[] sellTok } if (transaction.getRawData().getContract(0).getType() - == ContractType.ShieldedTransferContract) { + == ContractType.ShieldedTransferContract) { return null; } @@ -6800,8 +6814,8 @@ public static String marketSellAsset(byte[] owner, String priKey, byte[] sellTok broadcastTransaction(transaction, blockingStubFull); String txid = ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); System.out.println("trigger txid = " + txid); return txid; @@ -6812,8 +6826,8 @@ public static String marketSellAsset(byte[] owner, String priKey, byte[] sellTok * constructor. */ public static Return marketSellAssetGetResposne(byte[] owner, String priKey, byte[] sellTokenId, - long sellTokenQuantity, byte[] buyTokenId, long buyTokenQuantity, - WalletGrpc.WalletBlockingStub blockingStubFull) { + long sellTokenQuantity, byte[] buyTokenId, long buyTokenQuantity, + WalletGrpc.WalletBlockingStub blockingStubFull) { ECKey temKey = null; try { @@ -6825,13 +6839,13 @@ public static Return marketSellAssetGetResposne(byte[] owner, String priKey, byt ECKey ecKey = temKey; MarketContract.MarketSellAssetContract.Builder builder = MarketContract.MarketSellAssetContract - .newBuilder(); + .newBuilder(); builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setSellTokenQuantity(sellTokenQuantity) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .setBuyTokenQuantity(buyTokenQuantity); + .setOwnerAddress(ByteString.copyFrom(owner)) + .setSellTokenId(ByteString.copyFrom(sellTokenId)) + .setSellTokenQuantity(sellTokenQuantity) + .setBuyTokenId(ByteString.copyFrom(buyTokenId)) + .setBuyTokenQuantity(buyTokenQuantity); TransactionExtention transactionExtention = blockingStubFull.marketSellAsset(builder.build()); @@ -6843,7 +6857,7 @@ public static Return marketSellAssetGetResposne(byte[] owner, String priKey, byt * constructor. */ public static String marketCancelOrder(byte[] owner, String priKey, byte[] orderId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { ECKey temKey = null; try { @@ -6855,7 +6869,7 @@ public static String marketCancelOrder(byte[] owner, String priKey, byte[] order final ECKey ecKey = temKey; MarketContract.MarketCancelOrderContract.Builder builder = MarketContract - .MarketCancelOrderContract.newBuilder(); + .MarketCancelOrderContract.newBuilder(); builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); @@ -6876,7 +6890,7 @@ public static String marketCancelOrder(byte[] owner, String priKey, byte[] order } if (transaction.getRawData().getContract(0).getType() - == ContractType.ShieldedTransferContract) { + == ContractType.ShieldedTransferContract) { return null; } @@ -6884,8 +6898,8 @@ public static String marketCancelOrder(byte[] owner, String priKey, byte[] order broadcastTransaction(transaction, blockingStubFull); String txid = ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); System.out.println("trigger txid = " + txid); @@ -6897,7 +6911,7 @@ public static String marketCancelOrder(byte[] owner, String priKey, byte[] order */ public static Return marketCancelOrderGetResposne(byte[] owner, String priKey, byte[] orderId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { ECKey temKey = null; try { @@ -6909,7 +6923,7 @@ public static Return marketCancelOrderGetResposne(byte[] owner, String priKey, b ECKey ecKey = temKey; MarketContract.MarketCancelOrderContract.Builder builder = MarketContract - .MarketCancelOrderContract.newBuilder(); + .MarketCancelOrderContract.newBuilder(); builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); @@ -6924,7 +6938,7 @@ public static Return marketCancelOrderGetResposne(byte[] owner, String priKey, b * constructor. */ public static Optional getMarketOrderByAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { ByteString addressBs = ByteString.copyFrom(address); BytesMessage request = BytesMessage.newBuilder().setValue(addressBs).build(); @@ -6937,7 +6951,7 @@ public static Optional getMarketOrderByAccount(byte[] * constructor. */ public static Optional getMarketOrderByAccountSolidity(byte[] address, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { ByteString addressBs = ByteString.copyFrom(address); BytesMessage request = BytesMessage.newBuilder().setValue(addressBs).build(); @@ -6950,7 +6964,7 @@ public static Optional getMarketOrderByAccountSolidity * constructor. */ public static Optional getMarketOrderById(byte[] order, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { ByteString orderBytes = ByteString.copyFrom(order); BytesMessage request = BytesMessage.newBuilder().setValue(orderBytes).build(); Protocol.MarketOrder orderPair = blockingStubFull.getMarketOrderById(request); @@ -6961,7 +6975,7 @@ public static Optional getMarketOrderById(byte[] order, * constructor. */ public static Optional getMarketOrderByIdSolidity(byte[] order, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { ByteString orderBytes = ByteString.copyFrom(order); BytesMessage request = BytesMessage.newBuilder().setValue(orderBytes).build(); Protocol.MarketOrder orderPair = blockingStubSolidity.getMarketOrderById(request); @@ -6972,12 +6986,12 @@ public static Optional getMarketOrderByIdSolidity(byte[] o * constructor. */ public static Optional getMarketPriceByPair(byte[] sellTokenId, - byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { + byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { Protocol.MarketOrderPair request = - Protocol.MarketOrderPair.newBuilder() - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .build(); + Protocol.MarketOrderPair.newBuilder() + .setSellTokenId(ByteString.copyFrom(sellTokenId)) + .setBuyTokenId(ByteString.copyFrom(buyTokenId)) + .build(); Protocol.MarketPriceList marketPriceList = blockingStubFull.getMarketPriceByPair(request); return Optional.ofNullable(marketPriceList); @@ -6987,12 +7001,12 @@ public static Optional getMarketPriceByPair(byte[] sel * constructor. */ public static Optional getMarketOrderListByPair(byte[] sellTokenId, - byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { + byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { Protocol.MarketOrderPair request = - Protocol.MarketOrderPair.newBuilder() - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .build(); + Protocol.MarketOrderPair.newBuilder() + .setSellTokenId(ByteString.copyFrom(sellTokenId)) + .setBuyTokenId(ByteString.copyFrom(buyTokenId)) + .build(); Protocol.MarketOrderList marketOrderList = blockingStubFull.getMarketOrderListByPair(request); return Optional.ofNullable(marketOrderList); @@ -7002,16 +7016,16 @@ public static Optional getMarketOrderListByPair(byte[] * constructor. */ public static Optional getMarketOrderListByPairSolidity( - byte[] sellTokenId, - byte[] buyTokenId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + byte[] sellTokenId, + byte[] buyTokenId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { Protocol.MarketOrderPair request = - Protocol.MarketOrderPair.newBuilder() - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .build(); + Protocol.MarketOrderPair.newBuilder() + .setSellTokenId(ByteString.copyFrom(sellTokenId)) + .setBuyTokenId(ByteString.copyFrom(buyTokenId)) + .build(); Protocol.MarketOrderList marketOrderList = blockingStubSolidity - .getMarketOrderListByPair(request); + .getMarketOrderListByPair(request); return Optional.ofNullable(marketOrderList); } @@ -7019,9 +7033,9 @@ public static Optional getMarketOrderListByPairSolidit * constructor. */ public static Optional getMarketPairList( - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { Protocol.MarketOrderPairList marketOrderList = blockingStubFull - .getMarketPairList(EmptyMessage.newBuilder().build()); + .getMarketPairList(EmptyMessage.newBuilder().build()); return Optional.ofNullable(marketOrderList); } @@ -7029,9 +7043,9 @@ public static Optional getMarketPairList( * constructor. */ public static Optional getMarketPairListSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { Protocol.MarketOrderPairList marketOrderList = blockingStubSolidity - .getMarketPairList(EmptyMessage.newBuilder().build()); + .getMarketPairList(EmptyMessage.newBuilder().build()); return Optional.ofNullable(marketOrderList); } @@ -7060,7 +7074,7 @@ public static String hexStringToString(String s) { for (int i = 0; i < baKeyword.length; i++) { try { baKeyword[i] = (byte) (0xff & Integer.parseInt( - s.substring(i * 2, i * 2 + 2), 16)); + s.substring(i * 2, i * 2 + 2), 16)); } catch (Exception e) { e.printStackTrace(); } @@ -7101,21 +7115,21 @@ public static String replaceCode(String code, String address) { * constructor. */ public static Map getAllowance2(Long startNum, Long endNum, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { final String blackHole = Configuration.getByPath("testng.conf") - .getString("defaultParameter.blackHoleAddress"); + .getString("defaultParameter.blackHoleAddress"); Long totalCount = 0L; Map witnessBlockCount = new HashMap<>(); Map witnessBrokerage = new HashMap<>(); Map witnessVoteCount = new HashMap<>(); Map witnessAllowance = new HashMap<>(); List witnessList = PublicMethed.listWitnesses(blockingStubFull) - .get().getWitnessesList(); + .get().getWitnessesList(); for (Protocol.Witness witness : witnessList) { witnessVoteCount.put(ByteArray.toHexString(witness.getAddress().toByteArray()), - witness.getVoteCount()); + witness.getVoteCount()); GrpcAPI.BytesMessage bytesMessage = GrpcAPI.BytesMessage.newBuilder() - .setValue(witness.getAddress()).build(); + .setValue(witness.getAddress()).build(); Long brokerager = blockingStubFull.getBrokerageInfo(bytesMessage).getNum(); witnessBrokerage.put(ByteArray.toHexString(witness.getAddress().toByteArray()), brokerager); totalCount += witness.getVoteCount(); @@ -7123,27 +7137,27 @@ public static Map getAllowance2(Long startNum, Long endNum, Optional infoById = null; for (Long k = startNum; k < endNum; k++) { String witnessAdd = ByteArray.toHexString(PublicMethed.getBlock(k, blockingStubFull) - .getBlockHeader().getRawData().getWitnessAddress().toByteArray()); + .getBlockHeader().getRawData().getWitnessAddress().toByteArray()); witnessBlockCount.put(witnessAdd, witnessBlockCount.getOrDefault(witnessAdd, 0) + 1); List transList = PublicMethed.getBlock(k, - blockingStubFull).getTransactionsList(); + blockingStubFull).getTransactionsList(); for (Transaction tem : transList) { String txid = ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - tem.getRawData().toByteArray())); + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + tem.getRawData().toByteArray())); logger.info("----ss txid:" + txid); infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); Long packingFee = infoById.get().getPackingFee(); witnessAllowance.put(witnessAdd, witnessAllowance.getOrDefault(witnessAdd, 0L) - + packingFee); + + packingFee); } } logger.info("========totalCount:" + totalCount); List chainParaList = - blockingStubFull.getChainParameters(EmptyMessage.newBuilder().build()) - .getChainParameterList(); + blockingStubFull.getChainParameters(EmptyMessage.newBuilder().build()) + .getChainParameterList(); Long witness127PayPerBlock = 0L; Long witnessPayPerBlock = 0L; for (Protocol.ChainParameters.ChainParameter para : chainParaList) { @@ -7155,7 +7169,7 @@ public static Map getAllowance2(Long startNum, Long endNum, } } logger.info("witness127PayPerBlock:" + witness127PayPerBlock - + "\n witnessPayPerBlock:" + witnessPayPerBlock); + + "\n witnessPayPerBlock:" + witnessPayPerBlock); for (Map.Entry entry : witnessBrokerage.entrySet()) { logger.info("-----witnessBrokerage " + entry.getKey() + " : " + entry.getValue()); @@ -7170,12 +7184,12 @@ public static Map getAllowance2(Long startNum, Long endNum, for (Map.Entry entry : witnessVoteCount.entrySet()) { String witnessAdd = entry.getKey(); logger.info("----witnessAdd:" + witnessAdd + " block count:" - + witnessBlockCount.get(witnessAdd) - + " all: " + witnessAllowance.getOrDefault(witnessAdd, 0L)); + + witnessBlockCount.get(witnessAdd) + + " all: " + witnessAllowance.getOrDefault(witnessAdd, 0L)); Long pay = (witnessBlockCount.get(witnessAdd) * witnessPayPerBlock - + (endNum - startNum) * witness127PayPerBlock * entry.getValue() / totalCount - + witnessAllowance.getOrDefault(witnessAdd, 0L)) - * witnessBrokerage.get(witnessAdd) / 100; + + (endNum - startNum) * witness127PayPerBlock * entry.getValue() / totalCount + + witnessAllowance.getOrDefault(witnessAdd, 0L)) + * witnessBrokerage.get(witnessAdd) / 100; witnessAllowance.put(witnessAdd, pay); logger.info("****** " + witnessAdd + " : " + pay); @@ -7192,7 +7206,7 @@ public static String getContractStringMsg(byte[] contractMsgArray) { * constructor. */ public boolean updateBrokerage(byte[] owner, int brokerage, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { ECKey temKey = null; try { @@ -7206,13 +7220,13 @@ public boolean updateBrokerage(byte[] owner, int brokerage, String priKey, UpdateBrokerageContract.Builder updateBrokerageContract = UpdateBrokerageContract.newBuilder(); updateBrokerageContract.setOwnerAddress(ByteString.copyFrom(owner)).setBrokerage(brokerage); TransactionExtention transactionExtention = blockingStubFull - .updateBrokerage(updateBrokerageContract.build()); + .updateBrokerage(updateBrokerageContract.build()); Protocol.Transaction transaction = transactionExtention.getTransaction(); if (transactionExtention == null || !transactionExtention.getResult().getResult()) { if (transactionExtention != null) { System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); } return false; } @@ -7226,24 +7240,24 @@ public boolean updateBrokerage(byte[] owner, int brokerage, String priKey, * constructor. */ public static Long getAccountBalance(Protocol.Block block,byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { final Long blockNum = block.getBlockHeader().getRawData().getNumber(); BlockId blockId = new BlockId( - org.tron.common.utils.Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - block.getBlockHeader().getRawData().toByteArray()), - block.getBlockHeader().getRawData().getNumber()); + org.tron.common.utils.Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), + block.getBlockHeader().getRawData().toByteArray()), + block.getBlockHeader().getRawData().getNumber()); BalanceContract.AccountIdentifier accountIdentifier = BalanceContract - .AccountIdentifier.newBuilder().setAddress(ByteString.copyFrom(address)).build(); + .AccountIdentifier.newBuilder().setAddress(ByteString.copyFrom(address)).build(); BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier - = BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() - .setHash(blockId.getByteString()).setNumber(blockNum).build(); + = BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() + .setHash(blockId.getByteString()).setNumber(blockNum).build(); BalanceContract.AccountBalanceRequest accountBalanceRequest - = BalanceContract.AccountBalanceRequest.newBuilder() - .setAccountIdentifier(accountIdentifier).setBlockIdentifier(blockIdentifier).build(); + = BalanceContract.AccountBalanceRequest.newBuilder() + .setAccountIdentifier(accountIdentifier).setBlockIdentifier(blockIdentifier).build(); return blockingStubFull.getAccountBalance(accountBalanceRequest).getBalance(); } @@ -7251,15 +7265,15 @@ public static Long getAccountBalance(Protocol.Block block,byte[] address, * constructor. */ public static BalanceContract.BlockBalanceTrace getBlockBalance(Protocol.Block block, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { final Long blockNum = block.getBlockHeader().getRawData().getNumber(); BlockId blockId = new BlockId( - org.tron.common.utils.Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - block.getBlockHeader().getRawData().toByteArray()), - block.getBlockHeader().getRawData().getNumber()); + org.tron.common.utils.Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), + block.getBlockHeader().getRawData().toByteArray()), + block.getBlockHeader().getRawData().getNumber()); BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier - = BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() - .setHash(blockId.getByteString()).setNumber(blockNum).build(); + = BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() + .setHash(blockId.getByteString()).setNumber(blockNum).build(); return blockingStubFull.getBlockBalanceTrace(blockIdentifier); @@ -7271,7 +7285,7 @@ public static BalanceContract.BlockBalanceTrace getBlockBalance(Protocol.Block b */ public static Optional getTransactionFromPending(String txId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + WalletGrpc.WalletBlockingStub blockingStubFull) { ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); Transaction transaction; diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java new file mode 100644 index 00000000000..052accaaea5 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java @@ -0,0 +1,373 @@ +package stest.tron.wallet.dailybuild.jsonrpc; + +import com.alibaba.fastjson.JSONObject; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.HttpResponse; +import org.junit.Assert; +import org.testng.annotations.Test; +import stest.tron.wallet.common.client.utils.HttpMethed; +import stest.tron.wallet.common.client.utils.JsonRpcBase; + +@Slf4j +public class Accounts002 extends JsonRpcBase { + JSONObject responseContent; + HttpResponse response; + String topic0 = null; + String topic1 = null; + String fromBlock = null; + String toBlock = null; + String newFilterResultIdfrom01 = null; + String newFilterResultIdfrom02 = null; + String blockHash = null; + + @Test(enabled = true, description = "Eth api of eth_newFilter contains nothing.") + public void test01GetNewFilterContainNothing() { + JsonObject paramBody = new JsonObject(); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test01GetNewFilterContainNothing_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test01GetNewFilterContainNothing_responseContent" + responseContent); + logger.info("result:" + responseContent.getString("result")); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test( + enabled = true, + description = "Eth api of eth_newFilter contains address,fromBlock and toBlock.") + public void test02GetNewFilterContainAddress() { + if (blockNumForTrc20 - 10 < 0) { + fromBlock = "0"; + } else { + fromBlock = "0x" + Integer.toHexString(blockNumForTrc20 - 10); + } + toBlock = "0x" + Integer.toHexString(blockNumForTrc20 + 10); + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test02GetNewFilterContainAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test02GetNewFilterContainAddress_responseContent" + responseContent); + newFilterResultIdfrom01 = responseContent.getString("result"); + logger.info("test02GetNewFilterContainAddress_id:" + responseContent.getString("result")); + } + + @Test( + enabled = true, + description = "Eth api of eth_newFilter contains topic fromBlock and toBlock.") + public void test03GetNewFilterContainTopic() { + response = HttpMethed.getBlockByNum(httpFullNode, blockNumForTrc20); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + logger.info("blockHash:" + responseContent.getString("blockID")); + + blockHash = responseContent.getString("blockID"); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + JsonObject paramBody = new JsonObject(); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test03GetNewFilterContainTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test03GetNewFilterContainTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + newFilterResultIdfrom02 = responseContent.getString("result"); + logger.info("test03GetNewFilterContainTopic_id:" + newFilterResultIdfrom02); + } + + @Test(enabled = true, description = "Eth api of eth_newFilter contains topic and address.") + public void test04GetNewFilterContainsTopicAndAddress() { + + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test04GetNewFilterContainsTopicAndAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test04GetNewFilterContainsTopicAndAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_newFilter only contain topic and blockHash.") + public void test05GetNewFilterOnlyContainTopic() { + JsonObject paramBody = new JsonObject(); + paramBody.addProperty("blockHash", blockHash); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + paramBody.add("topics", topicArray); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test05GetNewFilterOnlyContainTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test05GetNewFilterOnlyContainTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_newFilter which only contains blockHash.") + public void test06GetNewFilterHasOnlyBlockHash() { + + response = HttpMethed.getNowBlock(httpFullNode); + responseContent = HttpMethed.parseResponseContent(response); + String blockHash = responseContent.getString("blockID"); + JsonObject paramBody = new JsonObject(); + paramBody.addProperty("blockHash", blockHash); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test06GetNewFilterHasOnlyBlockHash_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test06GetNewFilterHasOnlyBlockHash_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_newFilter check new and after block.") + public void test07GetNewFilterCheckNewBlock() { + JsonObject paramBody = new JsonObject(); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + paramBody.add("topics", topicArray); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test07GetNewFilterCheckNewBlock_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test07GetNewFilterCheckNewBlock_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_newBlockFilter") + public void test08GetEthNewBlockFilter() { + + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test08GetEthNewBlockFilter_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test08GetEthNewBlockFilter_responseContent:" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_getFilterChanges has less 20 elements.") + public void test09GetFilterChanges() { + + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); + String ethNewBlockFilterResult = responseContent.get("result").toString(); + logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); + String newFilterId = responseContent.getString("result"); + logger.info("newFilterId:" + newFilterId); + params = new JsonArray(); + params.add(newFilterId); + requestBody = getJsonRpcBody("eth_getFilterChanges", params); + logger.info("test09GetFilterChanges_requestBody: " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test09GetFilterChanges_responseContent:" + responseContent); + Assert.assertEquals("[]", responseContent.getString("result")); + } + + @Test( + enabled = true, + description = "Eth api of eth_getLogs contains address ,fromBlock and toBlock.") + public void test10GetLogsOnlyContainAddress() { + JsonArray addressArray = new JsonArray(); + logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); + addressArray.add(contractTrc20AddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + logger.info("blockNumForTrc20:" + blockNumForTrc20); + paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 20))); + paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 20))); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); + logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test10GetLogsOnlyContainAddress_responseContent:" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + String address = + responseContent.getJSONArray("result").getJSONObject(0).getString("address").substring(2); + Assert.assertEquals(address, contractTrc20AddressFrom58.substring(2)); + topic0 = responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); + } + + @Test(enabled = true, description = "Eth api of eth_getLogs both contains topic and address.") + public void test11GetLogsContainsTopicAndAddress() { + JsonArray topicArray = new JsonArray(); + topicArray.add(topic0); + JsonObject paramBody = new JsonObject(); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 10))); + paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 10))); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); + logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test11GetLogsContainsTopicAndAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + String topicFromResult = + responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); + Assert.assertEquals(topicFromResult, topic0); + } + + @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") + public void test12GetFilterLogsContainsAddress() { + + JsonArray params = new JsonArray(); + params.add(newFilterResultIdfrom01); + JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); + logger.info("test12GetFilterLogsContainsAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test12GetFilterLogsContainsAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") + public void test13GetFilterLogsContainsTopic() { + + JsonArray params = new JsonArray(); + params.add(newFilterResultIdfrom02); + JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); + logger.info("test13GetFilterLogsContainsTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test13GetFilterLogsContainsTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test( + enabled = true, + description = + "Eth api of eth_uninstallFilter which method is eth_newFilter" + + " and params has one element ") + public void test14EthUninstallFilter() { + // create ID + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.addProperty("fromBlock", "0x1f8b6a7"); + paramBody.addProperty("toBlock", "0x1f8b6a7"); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test14_newfilter " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_newfilter_responseContentr" + responseContent); + String ethNewFilterResult = responseContent.get("result").toString(); + logger.info("EthNewFilterResult:" + ethNewFilterResult); + Assert.assertNotNull(responseContent.getString("result")); + + // verify ID invalid + + // first time + params = new JsonArray(); + params.add(responseContent.get("result").toString()); + requestBody = getJsonRpcBody("eth_uninstallFilter", params); + logger.info("test14_eth_uninstallFilter " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_eth_uninstallFilter_responseContentr_first" + responseContent); + Assert.assertEquals(responseContent.get("result"), true); + // second time + logger.info("test14_eth_uninstallFilter_second " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_eth_uninstallFilter_responseContentr_second " + responseContent); + Assert.assertEquals( + responseContent.getJSONObject("error").getString("message"), "filter not found"); + + // query getFilterChanges to verify ID has invalid + params = new JsonArray(); + params.add(ethNewFilterResult); + requestBody = getJsonRpcBody("getFilterChanges", params); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14EthUninstallFilter_responseContent" + responseContent); + String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; + Assert.assertEquals(responseContent.get("error").toString(), expectResult); + } + + @Test( + enabled = true, + description = + "Eth api of eth_uninstallFilter which method is eth_newBlockFilter" + + " and params has one element ") + public void test15EthUninstallFilter() { + // create ID + + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); + String ethNewBlockFilterResult = responseContent.get("result").toString(); + logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); + Assert.assertNotNull(responseContent.getString("result")); + + // verify ID invalid + // first time + params = new JsonArray(); + params.add(responseContent.get("result").toString()); + requestBody = getJsonRpcBody("eth_uninstallFilter", params); + logger.info("test15_eth_uninstallFilter " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15_eth_uninstallFilter_responseContentr_first" + responseContent); + Assert.assertEquals(responseContent.get("result"), true); + // second time + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15_eth_uninstallFilter_responseContentr_second" + responseContent); + Assert.assertEquals( + responseContent.getJSONObject("error").getString("message"), "filter not found"); + // query getFilterChanges to verify ID has invalid + params = new JsonArray(); + params.add(ethNewBlockFilterResult); + requestBody = getJsonRpcBody("getFilterChanges", params); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_responseContent" + responseContent); + String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; + Assert.assertEquals(responseContent.get("error").toString(), expectResult); + } +} From 2eb8989cb10484af1d03f7b6e5e1c624ef29611a Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Thu, 2 Dec 2021 14:21:16 +0800 Subject: [PATCH 03/24] add --- .../wallet/onlinestress/ContractEvent001.java | 688 ++++++++++++++---- .../soliditycode/testGetFilterChange.sol | 11 + 2 files changed, 568 insertions(+), 131 deletions(-) create mode 100644 framework/src/test/resources/soliditycode/testGetFilterChange.sol diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java b/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java index 2616c3835e8..3013039904b 100644 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java +++ b/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java @@ -1,5 +1,10 @@ package stest.tron.wallet.onlinestress; +import com.alibaba.fastjson.JSONObject; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.client.HttpClient; import com.google.protobuf.ByteString; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; @@ -10,8 +15,18 @@ import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.util.HashMap; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.conn.PoolingClientConnectionManager; +import org.apache.http.params.CoreConnectionPNames; +import org.apache.http.util.EntityUtils; +import org.bouncycastle.util.encoders.Hex; import org.junit.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -29,17 +44,22 @@ import org.zeromq.ZMQ; import stest.tron.wallet.common.client.Configuration; import stest.tron.wallet.common.client.Parameter.CommonConstant; +import stest.tron.wallet.common.client.WalletClient; +import stest.tron.wallet.common.client.utils.HttpMethed; +import stest.tron.wallet.common.client.utils.JsonRpcBase; import stest.tron.wallet.common.client.utils.PublicMethed; import zmq.ZMQ.Event; +import static java.lang.Thread.sleep; + @Slf4j -public class ContractEvent001 { +public class ContractEvent001 extends JsonRpcBase { - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); + private final String testKey002 = + Configuration.getByPath("testng.conf").getString("foundationAccount.key1"); private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); + private final String testKey003 = + Configuration.getByPath("testng.conf").getString("foundationAccount.key2"); private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); String txid; ECKey ecKey1 = new ECKey(Utils.getRandom()); @@ -52,12 +72,16 @@ public class ContractEvent001 { private ManagedChannel channelFull1 = null; private WalletGrpc.WalletBlockingStub blockingStubFull = null; private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); + // byte[] contractAddress = null; + String param = "10"; + static HttpResponse response; + static JSONObject responseContent; + private String fullnode = + Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(0); + private String fullnode1 = + Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(1); + private Long maxFeeLimit = + Configuration.getByPath("testng.conf").getLong("defaultParameter.maxFeeLimit"); @BeforeSuite public void beforeSuite() { @@ -65,19 +89,12 @@ public void beforeSuite() { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); } - /** - * constructor. - */ - + /** constructor. */ @BeforeClass(enabled = true) public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); + channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); + channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); } @@ -94,14 +111,16 @@ public void test1ContractEventAndLog() { PublicMethed.printAddress(event001Key); PublicMethed.printAddress(testKey002); - Assert.assertTrue(PublicMethed.sendcoin(event001Address, maxFeeLimit * 30, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(event002Address, maxFeeLimit * 30, fromAddress, - testKey002, blockingStubFull)); + Assert.assertTrue( + PublicMethed.sendcoin( + event001Address, maxFeeLimit * 30, fromAddress, testKey002, blockingStubFull)); + Assert.assertTrue( + PublicMethed.sendcoin( + event002Address, maxFeeLimit * 30, fromAddress, testKey002, blockingStubFull)); PublicMethed.waitProduceNextBlock(blockingStubFull1); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(event001Address, - blockingStubFull); + AccountResourceMessage accountResource = + PublicMethed.getAccountResource(event001Address, blockingStubFull); Long energyLimit = accountResource.getEnergyLimit(); Long energyUsage = accountResource.getEnergyUsed(); Long balanceBefore = PublicMethed.queryAccount(event001Key, blockingStubFull).getBalance(); @@ -111,118 +130,279 @@ public void test1ContractEventAndLog() { logger.info("before balance is " + Long.toString(balanceBefore)); String contractName = "addressDemo"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_ContractEventAndLog1"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_ContractEventAndLog1"); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 50, null, event001Key, event001Address, blockingStubFull); + String code = + Configuration.getByPath("testng.conf").getString("code.code_ContractEventAndLog1"); + String abi = Configuration.getByPath("testng.conf").getString("abi.abi_ContractEventAndLog1"); + byte[] contractAddress = + PublicMethed.deployContract( + contractName, + abi, + code, + "", + maxFeeLimit, + 0L, + 50, + null, + event001Key, + event001Address, + blockingStubFull); PublicMethed.waitProduceNextBlock(blockingStubFull); SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); Assert.assertTrue(smartContract.getAbi() != null); Integer i = 0; for (i = 0; i < 1; i++) { - txid = PublicMethed.triggerContract(contractAddress, - "depositForEventCycle(uint256)", "100", false, - 1L, 100000000L, event002Address, event002Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "depositForEventCycle(uint256)", + "100", + false, + 1L, + 100000000L, + event002Address, + event002Key, + blockingStubFull); logger.info(txid); - txid = PublicMethed.triggerContract(contractAddress, - "depositForLogCycle(uint256)", "100", false, - 2L, 100000000L, event002Address, event002Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "depositForLogCycle(uint256)", + "100", + false, + 2L, + 100000000L, + event002Address, + event002Key, + blockingStubFull); logger.info(txid); - txid = PublicMethed.triggerContract(contractAddress, - "triggerUintEvent()", "#", false, - 0, maxFeeLimit, event001Address, event001Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "triggerUintEvent()", + "#", + false, + 0, + maxFeeLimit, + event001Address, + event001Key, + blockingStubFull); logger.info(txid); - txid = PublicMethed.triggerContract(contractAddress, - "triggerintEvent()", "#", false, - 0, maxFeeLimit, event001Address, event001Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "triggerintEvent()", + "#", + false, + 0, + maxFeeLimit, + event001Address, + event001Key, + blockingStubFull); logger.info(txid); - txid = PublicMethed.triggerContract(contractAddress, - "depositForEventAndLog()", "#", false, - 1, maxFeeLimit, event001Address, event001Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "depositForEventAndLog()", + "#", + false, + 1, + maxFeeLimit, + event001Address, + event001Key, + blockingStubFull); logger.info(txid); - txid = PublicMethed.triggerContract(contractAddress, - "depositForEventNoIndex()", "#", false, - 0L, 100000000L, event001Address, event001Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "depositForEventNoIndex()", + "#", + false, + 0L, + 100000000L, + event001Address, + event001Key, + blockingStubFull); logger.info(txid); - txid = PublicMethed.triggerContract(contractAddress, - "depositForLog()", "#", false, - 1L, 100000000L, event001Address, event001Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "depositForLog()", + "#", + false, + 1L, + 100000000L, + event001Address, + event001Key, + blockingStubFull); logger.info(txid); - txid = PublicMethed.triggerContract(contractAddress, - "depositForEventNoIndex()", "#", false, - 1L, 100000000L, event001Address, event001Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "depositForEventNoIndex()", + "#", + false, + 1L, + 100000000L, + event001Address, + event001Key, + blockingStubFull); logger.info(txid); - txid = PublicMethed.triggerContract(contractAddress, - "depositForEventOneIndex()", "#", false, - 1L, 100000000L, event001Address, event001Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "depositForEventOneIndex()", + "#", + false, + 1L, + 100000000L, + event001Address, + event001Key, + blockingStubFull); logger.info(txid); - txid = PublicMethed.triggerContract(contractAddress, - "depositForEventTwoIndex()", "#", false, - 2L, 100000000L, event001Address, event001Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "depositForEventTwoIndex()", + "#", + false, + 2L, + 100000000L, + event001Address, + event001Key, + blockingStubFull); logger.info(txid); - txid = PublicMethed.triggerContract(contractAddress, - "depositForEvent()", "#", false, - 3L, 100000000L, event001Address, event001Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "depositForEvent()", + "#", + false, + 3L, + 100000000L, + event001Address, + event001Key, + blockingStubFull); logger.info(txid); - txid = PublicMethed.triggerContract(contractAddress, - "depositForEventCycle(uint256)", "100", false, - 1L, 100000000L, event002Address, event002Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "depositForEventCycle(uint256)", + "100", + false, + 1L, + 100000000L, + event002Address, + event002Key, + blockingStubFull); logger.info(txid); - txid = PublicMethed.triggerContract(contractAddress, - "depositForLogCycle(uint256)", "100", false, - 2L, 100000000L, event002Address, event002Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "depositForLogCycle(uint256)", + "100", + false, + 2L, + 100000000L, + event002Address, + event002Key, + blockingStubFull); logger.info(txid); - txid = PublicMethed.triggerContract(contractAddress, - "depositForAnonymousHasLog()", "#", false, - 4L, 100000000L, event001Address, event001Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "depositForAnonymousHasLog()", + "#", + false, + 4L, + 100000000L, + event001Address, + event001Key, + blockingStubFull); logger.info(txid); - txid = PublicMethed.triggerContract(contractAddress, - "depositForAnonymousNoLog()", "#", false, - 5L, 100000000L, event001Address, event001Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "depositForAnonymousNoLog()", + "#", + false, + 5L, + 100000000L, + event001Address, + event001Key, + blockingStubFull); logger.info(txid); String param = "\"" + code + "\"" + "," + "\"" + code + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "triggerStringEvent(string,string)", param, false, - 0L, 100000000L, event001Address, event001Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "triggerStringEvent(string,string)", + param, + false, + 0L, + 100000000L, + event001Address, + event001Key, + blockingStubFull); logger.info(txid); param = "\"" + "true1" + "\"" + "," + "\"" + "false1" + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "triggerBoolEvent(bool,bool)", param, false, - 0L, 100000000L, event001Address, event001Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "triggerBoolEvent(bool,bool)", + param, + false, + 0L, + 100000000L, + event001Address, + event001Key, + blockingStubFull); logger.info(txid); String filename = "/Users/wangzihe/Documents/modify_fullnode/java-tron/tooLongString.txt"; try { - FileReader fr = new FileReader( - filename); + FileReader fr = new FileReader(filename); InputStreamReader read = new InputStreamReader(new FileInputStream(new File(filename))); BufferedReader reader = new BufferedReader(read); String tooLongString = reader.readLine(); param = "\"" + tooLongString + "\"" + "," + "\"" + tooLongString + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "triggerStringEventAnonymous(string,string)", param, false, - 0L, 100000000L, event001Address, event001Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "triggerStringEventAnonymous(string,string)", + param, + false, + 0L, + 100000000L, + event001Address, + event001Key, + blockingStubFull); logger.info(txid); - txid = PublicMethed.triggerContract(contractAddress, - "triggerStringEvent(string,string)", param, false, - 0L, 100000000L, event001Address, event001Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "triggerStringEvent(string,string)", + param, + false, + 0L, + 100000000L, + event001Address, + event001Key, + blockingStubFull); logger.info(txid); } catch (FileNotFoundException e) { @@ -230,27 +410,275 @@ public void test1ContractEventAndLog() { } catch (IOException ioe) { ioe.printStackTrace(); } - - } contractName = "addressDemo"; - code = Configuration.getByPath("testng.conf") - .getString("code.code_ContractEventAndLog2"); - abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_ContractEventAndLog2"); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 50, null, event001Key, event001Address, blockingStubFull); + code = Configuration.getByPath("testng.conf").getString("code.code_ContractEventAndLog2"); + abi = Configuration.getByPath("testng.conf").getString("abi.abi_ContractEventAndLog2"); + contractAddress = + PublicMethed.deployContract( + contractName, + abi, + code, + "", + maxFeeLimit, + 0L, + 50, + null, + event001Key, + event001Address, + blockingStubFull); PublicMethed.waitProduceNextBlock(blockingStubFull); smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); Assert.assertTrue(smartContract.getAbi() != null); - txid = PublicMethed.triggerContract(contractAddress, - "triggerEventBytes()", "#", false, - 0, maxFeeLimit, event001Address, event001Key, blockingStubFull); + txid = + PublicMethed.triggerContract( + contractAddress, + "triggerEventBytes()", + "#", + false, + 0, + maxFeeLimit, + event001Address, + event001Key, + blockingStubFull); logger.info(txid); } + @Test( + enabled = true, + threadPoolSize = 5, + invocationCount = 5, + description = "test eth_getFilterChanges") + public void testEthGetFilterChanges() throws InterruptedException { + ECKey ecKey1 = new ECKey(Utils.getRandom()); + byte[] event001Address = ecKey1.getAddress(); + String event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); + ECKey ecKey2 = new ECKey(Utils.getRandom()); + byte[] event002Address = ecKey2.getAddress(); + String event002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); + PublicMethed.printAddress(event001Key); + PublicMethed.printAddress(testKey002); + + Assert.assertTrue( + PublicMethed.sendcoin( + event001Address, maxFeeLimit * 30, fromAddress, testKey002, blockingStubFull)); + Assert.assertTrue( + PublicMethed.sendcoin( + event002Address, maxFeeLimit * 30, fromAddress, testKey002, blockingStubFull)); + PublicMethed.waitProduceNextBlock(blockingStubFull1); + + String contractName = "SolidityTest"; + String filePath = "./src/test/resources/soliditycode/testGetFilterChange.sol"; + HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); + + String code = retMap.get("byteCode").toString(); + String abi = retMap.get("abI").toString(); + byte[] contractAddress = + PublicMethed.deployContract( + contractName, + abi, + code, + "", + maxFeeLimit, + 0L, + 50, + null, + event001Key, + event001Address, + blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); + Assert.assertTrue(smartContract.getAbi() != null); + logger.info("11111111111111111111111111111111111"); + Thread.sleep(180000); + + long txidNum = 0; + HttpResponse response = getNowBlock(httpFullNode); + JSONObject responseContent = parseResponseContent(response); + long blockBefore = + responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); + Thread.sleep(180000); + for (int i = 0; i < 5000; i++) { + String txid = + PublicMethed.triggerContract( + contractAddress, + "getResult(uint256)", + param, + false, + 2L, + 100000000L, + event002Address, + event002Key, + blockingStubFull); + logger.info("txid:" + txid); + txidNum++; + } + Thread.sleep(180000); + response = getNowBlock(httpFullNode); + responseContent = parseResponseContent(response); + long blockAfter = + responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); + + logger.info("txidNum:" + txidNum); + + // 扫块 + long sumLogs = 0; + long totalTransactionsSize = 0; + logger.info("blockBefore:" + blockBefore); + logger.info("blockAfter:" + blockAfter); + for (long i = blockBefore; i <= blockAfter; i++) { + + response = getTransactionCountByBlocknum(httpFullNode, (int) i); + responseContent = parseResponseContent(response); + long transactionsSize = responseContent.getLong("count"); + + totalTransactionsSize += transactionsSize; + } + logger.info((int)(Thread.currentThread().getId())+"sumLogs:" + totalTransactionsSize * Long.parseLong(param)); + } + + public static String[] arr = new String[] {"00", "0x6b5c9c34aae469576dfcde3655c9036d", "0x450de4565abf4434d66948fb2a568608", "0x02a65b2cc37d2d34808a63b50b86e0cd", "0x7474d244cecf3a943bf8ac6dbd7d60fa", "0x4ab110c02b04d7781f774eeffa6432a3"}; + + @Test( + enabled = true, + threadPoolSize = 5, + invocationCount = 5, + description = "Eth api of eth_getFilterChanges .") + public void test09GetFilterChanges() { + long sumSize = 0; + while (true) { + JsonArray params = new JsonArray(); + String id = arr[(int) (Thread.currentThread().getId()) - 16]; + params.add(id); + JsonObject requestBody = getJsonRpcBody("eth_getFilterChanges", params); + HttpResponse response = getJsonRpc(jsonRpcNode, requestBody); + JSONObject responseContent = parseResponseContent(response); + long size = responseContent.getJSONArray("result").size(); + sumSize += size; + logger.info(Thread.currentThread().getId() + ":sumSize:" + sumSize); + } + } + + /** constructor. */ + public static JSONObject parseResponseContent(HttpResponse response) { + try { + String result = EntityUtils.toString(response.getEntity()); + StringEntity entity = new StringEntity(result, Charset.forName("UTF-8")); + response.setEntity(entity); + JSONObject obj = JSONObject.parseObject(result); + return obj; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /* public static HttpResponse getNowBlock(String httpNode, Boolean visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + }*/ + + /** constructor. */ + public static HttpResponse getTransactionCountByBlocknum(String httpNode, long blocknum) { + HttpResponse response; + try { + + String requestUrl = "http://" + httpNode + "/wallet/gettransactioncountbyblocknum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blocknum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + + return null; + } + return response; + } + + public static HttpResponse getNowBlock(String httpNode) { + return getNowBlock(httpNode, false); + } + + /** constructor. */ + public static HttpResponse getNowBlock(String httpNode, Boolean visible) { + + HttpResponse response; + try { + String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse createConnect(String url, JsonObject requestBody) { + HttpResponse response; + HttpPost httppost; + HttpClient httpClient; + Integer connectionTimeout = + Configuration.getByPath("testng.conf").getInt("defaultParameter.httpConnectionTimeout"); + Integer soTimeout = + Configuration.getByPath("testng.conf").getInt("defaultParameter.httpSoTimeout"); + PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(); + pccm.setDefaultMaxPerRoute(80); + pccm.setMaxTotal(100); + + httpClient = new DefaultHttpClient(pccm); + try { + + httpClient + .getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + httppost = new HttpPost(url); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + if (requestBody != null) { + StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httppost.setEntity(entity); + } + + logger.info(httppost.toString()); + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); + + return null; + } + return response; + } + + public static HttpResponse getJsonRpc(String jsonRpcNode, JsonObject jsonRpcObject) { + HttpResponse response; + try { + String requestUrl = "http://" + jsonRpcNode + "/jsonrpc"; + response = createConnect(requestUrl, jsonRpcObject); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + return response; + } + @Test(enabled = true, description = "Subscribe event client") public void testEnergyCostDetail() { ZMQ.Context context = ZMQ.context(1); @@ -263,15 +691,16 @@ public void testEnergyCostDetail() { req.monitor("inproc://reqmoniter", ZMQ.EVENT_CONNECTED | ZMQ.EVENT_DISCONNECTED); final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); moniter.connect("inproc://reqmoniter"); - new Thread(new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - - }).start(); + new Thread( + new Runnable() { + public void run() { + while (true) { + Event event = Event.read(moniter.base()); + System.out.println(event.event + " " + event.addr); + } + } + }) + .start(); req.connect("tcp://47.94.197.215:55555"); req.setReceiveTimeOut(10000); @@ -281,36 +710,35 @@ public void run() { System.out.println("receive : " + new String(message)); } } - - } @Test(enabled = true) public void testSingForHex() { try { - SignInterface cryptoEngine = SignUtils.fromPrivate(ByteArray - .fromHexString("6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"), - true); - /* ByteString sig = ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine - .signHash(Sha256Hash.of(DBConfig.isECKeyCryptoEngine(), + SignInterface cryptoEngine = + SignUtils.fromPrivate( ByteArray.fromHexString( - "ba989430c392dedef66a259a1f1112b178dbe7f2793975d8cf80f9b31ecd33ff")) - .getBytes())));*/ + "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"), + true); + /* ByteString sig = ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine + .signHash(Sha256Hash.of(DBConfig.isECKeyCryptoEngine(), + ByteArray.fromHexString( + "ba989430c392dedef66a259a1f1112b178dbe7f2793975d8cf80f9b31ecd33ff")) + .getBytes())));*/ // - ByteString sig = ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine - .signHash(ByteArray - .fromHexString("4f2a4c136f56a41714b42e14d497e38dcbe0f9c4ca2e5957cf3a340c62d133f8")))); + ByteString sig = + ByteString.copyFrom( + cryptoEngine.Base64toBytes( + cryptoEngine.signHash( + ByteArray.fromHexString( + "4f2a4c136f56a41714b42e14d497e38dcbe0f9c4ca2e5957cf3a340c62d133f8")))); logger.info(ByteArray.toHexString(sig.toByteArray())); } catch (Exception e) { e.printStackTrace(); } } - - /** - * constructor. - */ - + /** constructor. */ @AfterClass public void shutdown() throws InterruptedException { if (channelFull != null) { @@ -318,5 +746,3 @@ public void shutdown() throws InterruptedException { } } } - - diff --git a/framework/src/test/resources/soliditycode/testGetFilterChange.sol b/framework/src/test/resources/soliditycode/testGetFilterChange.sol new file mode 100644 index 00000000000..8a922031c2f --- /dev/null +++ b/framework/src/test/resources/soliditycode/testGetFilterChange.sol @@ -0,0 +1,11 @@ +pragma solidity ^0.8.0; +contract SolidityTest { + event Deployed(address sender, uint256 a, uint256 num); + function getResult(uint256 num) public payable returns(uint256) { + uint256 a=0; + for(a=0;a Date: Thu, 2 Dec 2021 15:20:11 +0800 Subject: [PATCH 04/24] add --- .../tron/wallet/dailybuild/jsonrpc/Accounts001.java | 9 +++++---- .../wallet/dailybuild/jsonrpc/EthSmartContract001.java | 6 +++--- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts001.java index df3b008d0a1..d654364ce18 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts001.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts001.java @@ -91,15 +91,16 @@ public void test03JsonRpcApiTestForEthCall() throws Exception { HttpMethed.waitToProduceOneBlock(httpFullNode); param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0"); - param.addProperty("gasPrice", "0"); - param.addProperty("value", "0"); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x0"); param.addProperty("data", "0x06fdde03"); JsonArray params = new JsonArray(); params.add(param); params.add("latest"); JsonObject requestBody = getJsonRpcBody("eth_call", params); - logger.info("params:" + params); + logger.info("03params:" + params); + logger.info("requestBody:" + requestBody); response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); String dataResult = responseContent.getString("result"); diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/EthSmartContract001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/EthSmartContract001.java index aee3436aed9..0fe564ad177 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/EthSmartContract001.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/EthSmartContract001.java @@ -29,9 +29,9 @@ public void test01JsonRpcApiTestForEthCall() throws Exception { JsonObject param = new JsonObject(); param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0"); - param.addProperty("gasPrice", "0"); - param.addProperty("value", "0"); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x0"); param.addProperty("data", "0x06fdde03"); JsonArray params = new JsonArray(); params.add(param); From 2295d451bcc58eaeb86e9ba9eda92462dcf07e09 Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Thu, 2 Dec 2021 15:23:33 +0800 Subject: [PATCH 05/24] add --- .../java/stest/tron/wallet/common/client/utils/JsonRpcBase.java | 1 - 1 file changed, 1 deletion(-) diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java index 109459aade2..ae76505c0b5 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java @@ -68,7 +68,6 @@ public class JsonRpcBase { public ManagedChannel channelPbft = null; public String data = null; public String paramString = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; public String fullnode = From 4a8208a7329efa60d7d736583a53b906a0eedfc4 Mon Sep 17 00:00:00 2001 From: sophiawang <1975054324@qq.com> Date: Thu, 2 Dec 2021 17:59:59 +0800 Subject: [PATCH 06/24] add case for opcode test --- .../common/client/utils/PublicMethed.java | 53 ++ .../dailybuild/eventquery/EventLog2.java | 117 ++++ .../tvmnewcommand/newGrammar/Opcode.java | 551 ++++++++++++++++++ .../test/resources/soliditycode/eventLog2.sol | 8 + .../test/resources/soliditycode/opCode.sol | 112 ++++ 5 files changed, 841 insertions(+) create mode 100644 framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventLog2.java create mode 100644 framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java create mode 100644 framework/src/test/resources/soliditycode/eventLog2.sol create mode 100644 framework/src/test/resources/soliditycode/opCode.sol diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java index 19c53eba3a5..f861cb7a738 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java @@ -5227,6 +5227,59 @@ public static String exec(String command) throws InterruptedException { return returnString; } + /** + * constructor. + */ + public static HashMap getBycodeAbiNoOptimize(String solFile, String contractName) { + final String compile = Configuration.getByPath("testng.conf") + .getString("defaultParameter.solidityCompile"); + + String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); + String outputPath = "src/test/resources/soliditycode//output" + dirPath; + + File binFile = new File(outputPath + "/" + contractName + ".bin"); + File abiFile = new File(outputPath + "/" + contractName + ".abi"); + if (binFile.exists()) { + binFile.delete(); + } + if (abiFile.exists()) { + abiFile.delete(); + } + + HashMap retMap = new HashMap<>(); + String absolutePath = System.getProperty("user.dir"); + logger.debug("absolutePath: " + absolutePath); + logger.debug("solFile: " + solFile); + logger.debug("outputPath: " + outputPath); + String cmd = + compile + " --bin --abi --overwrite " + absolutePath + "/" + + solFile + " -o " + + absolutePath + "/" + outputPath; + logger.info("cmd: " + cmd); + + String byteCode = null; + String abI = null; + + // compile solidity file + try { + exec(cmd); + } catch (InterruptedException e) { + e.printStackTrace(); + } + // get byteCode and ABI + try { + byteCode = fileRead(outputPath + "/" + contractName + ".bin", false); + retMap.put("byteCode", byteCode); + logger.debug("byteCode: " + byteCode); + abI = fileRead(outputPath + "/" + contractName + ".abi", false); + retMap.put("abI", abI); + logger.debug("abI: " + abI); + } catch (Exception e) { + e.printStackTrace(); + } + return retMap; + } + /** * constructor. */ diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventLog2.java b/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventLog2.java new file mode 100644 index 00000000000..124a8d4405f --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventLog2.java @@ -0,0 +1,117 @@ +package stest.tron.wallet.dailybuild.eventquery; + +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import java.util.HashMap; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; +import org.tron.api.GrpcAPI; +import org.tron.api.WalletGrpc; +import org.tron.common.crypto.ECKey; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.Utils; +import org.tron.core.Wallet; +import org.tron.protos.Protocol; +import org.tron.protos.contract.SmartContractOuterClass; +import stest.tron.wallet.common.client.Configuration; +import stest.tron.wallet.common.client.Parameter; +import stest.tron.wallet.common.client.utils.PublicMethed; + + + + +@Slf4j +public class EventLog2 { + + private final String testNetAccountKey = Configuration.getByPath("testng.conf") + .getString("foundationAccount.key2"); + private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); + byte[] mapKeyContract = null; + ECKey ecKey1 = new ECKey(Utils.getRandom()); + byte[] contractExcAddress = ecKey1.getAddress(); + String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); + private Long maxFeeLimit = Configuration.getByPath("testng.conf") + .getLong("defaultParameter.maxFeeLimit"); + private ManagedChannel channelFull = null; + private WalletGrpc.WalletBlockingStub blockingStubFull = null; + + private String fullnode = Configuration.getByPath("testng.conf") + .getStringList("fullnode.ip.list").get(0); + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + } + + /** + * constructor. + */ + + @BeforeClass(enabled = true) + public void beforeClass() { + PublicMethed.printAddress(contractExcKey); + channelFull = ManagedChannelBuilder.forTarget(fullnode) + .usePlaintext(true) + .build(); + blockingStubFull = WalletGrpc.newBlockingStub(channelFull); + + Assert.assertTrue(PublicMethed + .sendcoin(contractExcAddress, 300100_000_000L, + testNetAccountAddress, testNetAccountKey, blockingStubFull)); + PublicMethed.waitProduceNextBlock(blockingStubFull); + + String filePath = "src/test/resources/soliditycode/eventLog2.sol"; + String contractName = "Event"; + HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); + String code = retMap.get("byteCode").toString(); + String abi = retMap.get("abI").toString(); + mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, + 0L, 100, null, contractExcKey, + contractExcAddress, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, + blockingStubFull); + Assert.assertNotNull(smartContract.getAbi()); + } + + + @Test(enabled = true, description = "test opcode log2") + public void test01EmitLog2() { + GrpcAPI.TransactionExtention transactionExtention = PublicMethed + .triggerConstantContractForExtention(mapKeyContract, + "messageI()", "#", true, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + String logStr1 = ByteArray.toHexString(transactionExtention.getLogs(0).getData().toByteArray()); + Assert.assertTrue(logStr1.contains("000000000000000000000000000000000000000" + + "000000000000000000000000100000000000000000" + + "000000000000000000000000000000000000000000000010000000000000000" + + "000000000000000000000000000000000000000000000001")); + int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); + logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); + Assert.assertEquals(1, trueRes); + } + + + + /** + * constructor. + */ + @AfterClass + public void shutdown() throws InterruptedException { + PublicMethed.freedResource(contractExcAddress, contractExcKey, + testNetAccountAddress, blockingStubFull); + if (channelFull != null) { + channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); + } + } + + +} + diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java new file mode 100644 index 00000000000..64e86395791 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java @@ -0,0 +1,551 @@ +package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; + +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import java.util.HashMap; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; +import org.tron.api.GrpcAPI; +import org.tron.api.WalletGrpc; +import org.tron.common.crypto.ECKey; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.Utils; +import org.tron.core.Wallet; +import org.tron.protos.Protocol; +import org.tron.protos.contract.SmartContractOuterClass; +import stest.tron.wallet.common.client.Configuration; +import stest.tron.wallet.common.client.Parameter; +import stest.tron.wallet.common.client.utils.Base58; +import stest.tron.wallet.common.client.utils.PublicMethed; + + + +@Slf4j +public class Opcode { + + private final String testNetAccountKey = Configuration.getByPath("testng.conf") + .getString("foundationAccount.key2"); + private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); + byte[] mapKeyContract = null; + ECKey ecKey1 = new ECKey(Utils.getRandom()); + byte[] contractExcAddress = ecKey1.getAddress(); + String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); + private Long maxFeeLimit = Configuration.getByPath("testng.conf") + .getLong("defaultParameter.maxFeeLimit"); + private ManagedChannel channelFull = null; + private WalletGrpc.WalletBlockingStub blockingStubFull = null; + + private String fullnode = Configuration.getByPath("testng.conf") + .getStringList("fullnode.ip.list").get(0); + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + } + + /** + * constructor. + */ + + @BeforeClass(enabled = true) + public void beforeClass() { + PublicMethed.printAddress(contractExcKey); + channelFull = ManagedChannelBuilder.forTarget(fullnode) + .usePlaintext(true) + .build(); + blockingStubFull = WalletGrpc.newBlockingStub(channelFull); + + Assert.assertTrue(PublicMethed + .sendcoin(contractExcAddress, 300100_000_000L, + testNetAccountAddress, testNetAccountKey, blockingStubFull)); + PublicMethed.waitProduceNextBlock(blockingStubFull); + + String filePath = "src/test/resources/soliditycode/opCode.sol"; + String contractName = "A"; + HashMap retMap = PublicMethed.getBycodeAbiNoOptimize(filePath, contractName); + String code = retMap.get("byteCode").toString(); + String abi = retMap.get("abI").toString(); + mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, + 0L, 100, null, contractExcKey, + contractExcAddress, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, + blockingStubFull); + Assert.assertNotNull(smartContract.getAbi()); + + } + + + @Test(enabled = true, description = "test opcode smod, used for int") + public void test01Smod() { + GrpcAPI.TransactionExtention transactionExtention = PublicMethed + .triggerConstantContractForExtention(mapKeyContract, + "sssmod()", "#", true, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); + logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); + Assert.assertEquals(1, trueRes); + } + + @Test(enabled = true, description = "test opcode extcodecopy") + public void test02Extcodecopy() { + String base58 = Base58.encode58Check(mapKeyContract); + String txid = PublicMethed.triggerContract(mapKeyContract, + "eextcodecopy(address)", "\"" + base58 + "\"", false, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + Optional infoById = PublicMethed + .getTransactionInfoById(txid, blockingStubFull); + logger.info("txid: " + txid + "\n" + infoById.toString()); + Assert.assertEquals(0, infoById.get().getResultValue()); + Assert.assertTrue(ByteArray.toHexString( + infoById.get().getContractResult(0).toByteArray()).contains( + "000000000000000000000000000000000000000000000000000000000000002000000000000000" + + "000000000000000000000000000000000000000000000005f06080604052600436106100705760" + + "003560e01c80638d2702f41161004e5780638d2702f414610144578063ad0a3301146101625780" + + "63d159bd5f146101a7578063f6d3ba26146101fe57610070565b806330adc4b114610075578063" + + "805ad10f146100ba5780638c82bdbd146100ff575b600080fd5b34801561008157600080fd5b50" + + "d3801561008e57600080fd5b50d2801561009b57600080fd5b506100a4610243565b6040516100" + + "b19190610421565b60405180910390f35b3480156100c657600080fd5b50d380156100d3576000" + + "80fd5b50d280156100e057600080fd5b506100e96102b3565b6040516100f691906103e4565b60" + + "405180910390f35b34801561010b57600080fd5b50d3801561011857600080fd5b50d280156101" + + "2557600080fd5b5061012e6102bb565b60405161013b919061043c565b60405180910390f35b61" + + "014c6102c3565b6040516101599190610421565b60405180910390f35b34801561016e57600080" + + "fd5b50d3801561017b57600080fd5b50d2801561018857600080fd5b506101916102e9565b6040" + + "5161019e919061043c565b60405180910390f35b3480156101b357600080fd5b50d380156101c0" + + "57600080fd5b50d280156101cd57600080fd5b506101e860048036038101906101e39190610351" + + "565b6102fe565b6040516101f591906103ff565b60405180910390f35b34801561020a57600080" + + "fd5b50d3801561021757600080fd5b50d2801561022457600080fd5b5061022d610329565b6040" + + "5161023a919061043c565b60405180910390f35b60008060019050600060029050600060039050" + + "600060039050600060039050600060039050600060039050600060039050600060019050600060" + + "0290506000600390506000600390506000600390506000600390506000600390508e9f50505050" + + "50505050505050505050505090565b600041905090565b600044905090565b6000806003905060" + + "0060029050600081836102de919061050d565b905080935050505090565b60006c112233445566" + + "77889900112233905090565b6060813b6040519150601f19601f60208301011682016040528082" + + "5280600060208401853c50919050565b600045905090565b60008135905061034081610583565b" + + "61034981610473565b905092915050565b6000602082840312156103675761036661056d565b5b" + + "600061037584828501610331565b91505092915050565b61038781610473565b82525050565b60" + + "0061039882610457565b6103a28185610462565b93506103b28185602086016104da565b6103bb" + + "81610572565b840191505092915050565b6103cf81610485565b82525050565b6103de816104d0" + + "565b82525050565b60006020820190506103f9600083018461037e565b92915050565b60006020" + + "820190508181036000830152610419818461038d565b905092915050565b600060208201905061" + + "043660008301846103c6565b92915050565b600060208201905061045160008301846103d5565b" + + "92915050565b600081519050919050565b600082825260208201905092915050565b600061047e" + + "8261048f565b9050919050565b6000819050919050565b600073ffffffffffffffffffffffffff" + + "ffffffffffffff82169050919050565b600074ffffffffffffffffffffffffffffffffffffffff" + + "ff82169050919050565b6000819050919050565b60005b838110156104f8578082015181840152" + + "6020810190506104dd565b83811115610507576000848401525b50505050565b60006105188261" + + "0485565b915061052383610485565b9250826105335761053261053e565b5b8282079050929150" + + "50565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052" + + "601260045260246000fd5b600080fd5b6000601f19601f8301169050919050565b61058c816104" + + "af565b811461059757600080fd5b5056fea26474726f6e582212205dba90535ae40d8e2cafc63f" + + "67490cd4bcb4b3600957a9d8e03c201725728c2d64736f6c637822302e382e372d63692e323032" + + "312e372e32302b636f6d6d69742e32313238636465350053000000000000000000000000000000" + )); + + } + + @Test(enabled = true, description = "test opcode coinbase," + + "block.coinbase is sr address which produced the block") + public void test03Coinbase() { + GrpcAPI.TransactionExtention transactionExtention = PublicMethed + .triggerConstantContractForExtention(mapKeyContract, + "cccoinbase()", "#", true, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + String trueRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); + logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); + Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); + Assert.assertTrue(trueRes.startsWith("00000000000000000000000" + + "0bafb56091591790e00aa05eaddcc7dc1474b5d4b") + || trueRes.startsWith("0000000000000000000000000be88a918d74d0dfd71dc84bd4abf036d0562991")); + + } + + @Test(enabled = true, description = "test opcode difficulty,block.difficulty is always 0") + public void test04Difficulty() { + GrpcAPI.TransactionExtention transactionExtention = PublicMethed + .triggerConstantContractForExtention(mapKeyContract, + "ddifficulty()", "#", true, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); + logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); + Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); + Assert.assertEquals(0, trueRes); + + } + + @Test(enabled = true, description = "test opcode gaslimit,block.gaslimit is always 0") + public void test05Gaslimit() { + GrpcAPI.TransactionExtention transactionExtention = PublicMethed + .triggerConstantContractForExtention(mapKeyContract, + "gggaslimit()", "#", true, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); + logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); + Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); + Assert.assertEquals(0, trueRes); + + } + + @Test(enabled = true, description = "test opcode pc,return current position, " + + "ppppc() can refer to opCode.sol") + public void test06Pc() { + String code = "608060405260838060116000396000f3fe608060405234" + + "8015600f57600080fd5b506004361060285760003560e01c806" + + "36d3a027714602d575b600080fd5b60336045565b6040805191825251" + + "9081900360200190f35b60005890509056fea264697" + + "0667358221220fe03cbd3d2aae7454565f203b9abd76ce74cf0ac" + + "a079b151cf6b8e2bfda2d5c464736f6c634300060c0033"; + String abi = "[\n" + + "\t{\n" + + "\t\t\"inputs\": [],\n" + + "\t\t\"stateMutability\": \"payable\",\n" + + "\t\t\"type\": \"constructor\"\n" + + "\t},\n" + + "\t{\n" + + "\t\t\"inputs\": [],\n" + + "\t\t\"name\": \"ppppc\",\n" + + "\t\t\"outputs\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"internalType\": \"uint256\",\n" + + "\t\t\t\t\"name\": \"a\",\n" + + "\t\t\t\t\"type\": \"uint256\"\n" + + "\t\t\t}\n" + + "\t\t],\n" + + "\t\t\"stateMutability\": \"nonpayable\",\n" + + "\t\t\"type\": \"function\"\n" + + "\t}\n" + + "]"; + byte[] temContract = PublicMethed.deployContract("A", abi, code, "", maxFeeLimit, + 0L, 100, null, contractExcKey, + contractExcAddress, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(temContract, + blockingStubFull); + Assert.assertNotNull(smartContract.getAbi()); + + GrpcAPI.TransactionExtention transactionExtention = PublicMethed + .triggerConstantContractForExtention(temContract, + "ppppc()", "#", true, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); + logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); + Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); + Assert.assertEquals(72, trueRes); + + } + + @Test(enabled = true, description = "test opcode msize,return size of memory, " + + "msize cannot be used if optimize is open, mmmsize() can refer to opCode.sol") + public void test07Msize() { + String code = "608060405260b5806100126000396000f3fe6080604052348015600f5760" + + "0080fd5b506004361060285760003560e01c8063bf1a725d14602d575b600080fd5b60" + + "336047565b604051603e9190605c565b60405180910390f35b600059905090565b6056" + + "816075565b82525050565b6000602082019050606f6000830184604f565b9291505056" + + "5b600081905091905056fea26469706673582212202252652aad4bca9a4aa9db179e03" + + "f7b3bf439f47152e31f45d8587b710bce79664736f6c63430008060033"; + String abi = "[\n" + + "\t{\n" + + "\t\t\"inputs\": [],\n" + + "\t\t\"stateMutability\": \"payable\",\n" + + "\t\t\"type\": \"constructor\"\n" + + "\t},\n" + + "\t{\n" + + "\t\t\"inputs\": [],\n" + + "\t\t\"name\": \"mmmsize\",\n" + + "\t\t\"outputs\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"internalType\": \"uint256\",\n" + + "\t\t\t\t\"name\": \"a\",\n" + + "\t\t\t\t\"type\": \"uint256\"\n" + + "\t\t\t}\n" + + "\t\t],\n" + + "\t\t\"stateMutability\": \"nonpayable\",\n" + + "\t\t\"type\": \"function\"\n" + + "\t}\n" + + "]"; + byte[] temContract = PublicMethed.deployContract("A", abi, code, "", maxFeeLimit, + 0L, 100, null, contractExcKey, + contractExcAddress, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(temContract, + blockingStubFull); + Assert.assertNotNull(smartContract.getAbi()); + + GrpcAPI.TransactionExtention transactionExtention = PublicMethed + .triggerConstantContractForExtention(temContract, + "mmmsize()", "#", true, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); + logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); + Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); + Assert.assertEquals(96, trueRes); + + } + + + @Test(enabled = true, description = "test opcode swap14-16,solidity cannot use optimize") + public void test08Swap() { + GrpcAPI.TransactionExtention transactionExtention = PublicMethed + .triggerConstantContractForExtention(mapKeyContract, + "ssswap()", "#", true, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); + logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); + Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); + Assert.assertEquals(1, trueRes); + + } + + @Test(enabled = true, description = "test opcode push13-30 but exclude push20 and push29," + + "solidity cannot use optimize") + public void test08Pushx() { + GrpcAPI.TransactionExtention transactionExtention = PublicMethed + .triggerConstantContractForExtention(mapKeyContract, + "pppushx()", "#", true, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + String trueRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); + logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); + Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); + Assert.assertTrue(trueRes.contains("000000000000000000000000000000000000001" + + "1223344556677889900112233")); + } + + @Test(enabled = true, description = "test opcode callcode,difference with delegatecall " + + "is caller and callvalue,the bytecode is compiled with solidity 0.4.22, " + + "can refer to opCode.sol for code") + public void test09Callcode() { + String code = "60806040526103b4806100136000396000f3006080604052600436106100565763" + + "ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416634" + + "cb335db811461005b578063ae02d91d14610081578063ea856db2146100a5575b600080fd5b61007f" + + "73ffffffffffffffffffffffffffffffffffffffff600435166024356100c9565b005b61007f73ffff" + + "ffffffffffffffffffffffffffffffffffff600435166024356101b6565b61007f73ffffffffffffff" + + "ffffffffffffffffffffffffff600435166024356102a3565b604080516024808201849052825180830" + + "39091018152604490910182526020810180517bffffffffffffffffffffffffffffffffffffffffffff" + + "ffffffffffff167f66c99139000000000000000000000000000000000000000000000000000000001781529" + + "151815173ffffffffffffffffffffffffffffffffffffffff861693600a93929182919080838360005b8" + + "3811015610170578181015183820152602001610158565b50505050905090810190601f16801561019d5" + + "780820380516001836020036101000a031916815260200191505b5091505060006040518083038185875" + + "af1505050505050565b60408051602480820184905282518083039091018152604490910182526020810" + + "180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f66c99139000000000" + + "000000000000000000000000000000000000000000000001781529151815173fffffffffffffffffffff" + + "fffffffffffffffffff861693600a93929182919080838360005b8381101561025d57818101518382015" + + "2602001610245565b50505050905090810190601f16801561028a5780820380516001836020036101000" + + "a031916815260200191505b5091505060006040518083038185875af2505050505050565b60408051602" + + "480820184905282518083039091018152604490910182526020810180517bfffffffffffffffffffffff" + + "fffffffffffffffffffffffffffffffff167f66c991390000000000000000000000000000000000000000" + + "00000000000000001781529151815173ffffffffffffffffffffffffffffffffffffffff8616938291808" + + "38360005b8381101561034457818101518382015260200161032c565b50505050905090810190601f1680" + + "156103715780820380516001836020036101000a031916815260200191505b50915050600060405180830" + + "381855af450505050505600a165627a7a72305820210d132d0c4006264ef113f342556c616d9e69acc20" + + "bfa80cf440a4eac170de80029"; + String abi = "[\n" + + "\t{\n" + + "\t\t\"constant\": false,\n" + + "\t\t\"inputs\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"name\": \"callCAddress\",\n" + + "\t\t\t\t\"type\": \"address\"\n" + + "\t\t\t},\n" + + "\t\t\t{\n" + + "\t\t\t\t\"name\": \"amount\",\n" + + "\t\t\t\t\"type\": \"uint256\"\n" + + "\t\t\t}\n" + + "\t\t],\n" + + "\t\t\"name\": \"testInCall\",\n" + + "\t\t\"outputs\": [],\n" + + "\t\t\"payable\": true,\n" + + "\t\t\"stateMutability\": \"payable\",\n" + + "\t\t\"type\": \"function\"\n" + + "\t},\n" + + "\t{\n" + + "\t\t\"constant\": false,\n" + + "\t\t\"inputs\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"name\": \"callCAddress\",\n" + + "\t\t\t\t\"type\": \"address\"\n" + + "\t\t\t},\n" + + "\t\t\t{\n" + + "\t\t\t\t\"name\": \"amount\",\n" + + "\t\t\t\t\"type\": \"uint256\"\n" + + "\t\t\t}\n" + + "\t\t],\n" + + "\t\t\"name\": \"testInCallcode\",\n" + + "\t\t\"outputs\": [],\n" + + "\t\t\"payable\": true,\n" + + "\t\t\"stateMutability\": \"payable\",\n" + + "\t\t\"type\": \"function\"\n" + + "\t},\n" + + "\t{\n" + + "\t\t\"constant\": false,\n" + + "\t\t\"inputs\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"name\": \"callCAddress\",\n" + + "\t\t\t\t\"type\": \"address\"\n" + + "\t\t\t},\n" + + "\t\t\t{\n" + + "\t\t\t\t\"name\": \"amount\",\n" + + "\t\t\t\t\"type\": \"uint256\"\n" + + "\t\t\t}\n" + + "\t\t],\n" + + "\t\t\"name\": \"testIndelegateCall\",\n" + + "\t\t\"outputs\": [],\n" + + "\t\t\"payable\": true,\n" + + "\t\t\"stateMutability\": \"payable\",\n" + + "\t\t\"type\": \"function\"\n" + + "\t},\n" + + "\t{\n" + + "\t\t\"inputs\": [],\n" + + "\t\t\"payable\": true,\n" + + "\t\t\"stateMutability\": \"payable\",\n" + + "\t\t\"type\": \"constructor\"\n" + + "\t}\n" + + "]"; + byte[] contractA = PublicMethed.deployContract("A", abi, code, "", maxFeeLimit, + 1000000L, 100, null, contractExcKey, + contractExcAddress, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(contractA, + blockingStubFull); + Assert.assertNotNull(smartContract.getAbi()); + + code = "608060405260d2806100126000396000f300608060405260043610603e5763ffffffff7c0" + + "10000000000000000000000000000000000000000000000000000000060003504166366c99" + + "13981146043575b600080fd5b604c600435604e565b005b6040805173fffffffffffffffff" + + "fffffffffffffffffffffff3316815234602082015280820183905290517fac74fdf75f0e5" + + "a43f870f7135801b44f404be82b1dcad73423c542b840d1d64b9181900360600190a150560" + + "0a165627a7a72305820c460a35f70e363777be22b3a4ace5f95533de626073ab4e06d9bf3bbb2cffceb0029"; + abi = "[\n" + + "\t{\n" + + "\t\t\"constant\": false,\n" + + "\t\t\"inputs\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"name\": \"amount\",\n" + + "\t\t\t\t\"type\": \"uint256\"\n" + + "\t\t\t}\n" + + "\t\t],\n" + + "\t\t\"name\": \"trans\",\n" + + "\t\t\"outputs\": [],\n" + + "\t\t\"payable\": true,\n" + + "\t\t\"stateMutability\": \"payable\",\n" + + "\t\t\"type\": \"function\"\n" + + "\t},\n" + + "\t{\n" + + "\t\t\"inputs\": [],\n" + + "\t\t\"payable\": true,\n" + + "\t\t\"stateMutability\": \"payable\",\n" + + "\t\t\"type\": \"constructor\"\n" + + "\t},\n" + + "\t{\n" + + "\t\t\"anonymous\": false,\n" + + "\t\t\"inputs\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"indexed\": false,\n" + + "\t\t\t\t\"name\": \"\",\n" + + "\t\t\t\t\"type\": \"address\"\n" + + "\t\t\t},\n" + + "\t\t\t{\n" + + "\t\t\t\t\"indexed\": false,\n" + + "\t\t\t\t\"name\": \"\",\n" + + "\t\t\t\t\"type\": \"uint256\"\n" + + "\t\t\t},\n" + + "\t\t\t{\n" + + "\t\t\t\t\"indexed\": false,\n" + + "\t\t\t\t\"name\": \"\",\n" + + "\t\t\t\t\"type\": \"uint256\"\n" + + "\t\t\t}\n" + + "\t\t],\n" + + "\t\t\"name\": \"clog\",\n" + + "\t\t\"type\": \"event\"\n" + + "\t}\n" + + "]"; + byte[] contractC = PublicMethed.deployContract("C", abi, code, "", maxFeeLimit, + 0L, 100, null, contractExcKey, + contractExcAddress, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + smartContract = PublicMethed.getContract(contractC, + blockingStubFull); + Assert.assertNotNull(smartContract.getAbi()); + + String base58C = Base58.encode58Check(contractC); + + String txid = PublicMethed.triggerContract(contractA, + "testInCall(address,uint256)", "\"" + base58C + "\",1", false, + 1, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + Optional infoById = PublicMethed + .getTransactionInfoById(txid, blockingStubFull); + Assert.assertEquals(0, infoById.get().getResultValue()); + String logRes = ByteArray.toHexString(infoById.get().getLog(0).getData().toByteArray()); + System.out.println("000000: " + logRes); + String b = "41" + logRes.substring(24, 64); + String c = logRes.substring(64, 128); + String x = ByteArray.toHexString(contractA); + Assert.assertEquals(b, x); + Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000000a", c); + + txid = PublicMethed.triggerContract(contractA, + "testIndelegateCall(address,uint256)", "\"" + base58C + "\",1", false, + 2, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + infoById = PublicMethed + .getTransactionInfoById(txid, blockingStubFull); + logger.info("txid: " + txid + "\n" + infoById.toString()); + Assert.assertEquals(0, infoById.get().getResultValue()); + logRes = ByteArray.toHexString(infoById.get().getLog(0).getData().toByteArray()); + System.out.println("000000: " + logRes); + b = "41" + logRes.substring(24, 64); + c = logRes.substring(64, 128); + x = ByteArray.toHexString(contractExcAddress); + Assert.assertEquals(b, x); + Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000002", c); + + + txid = PublicMethed.triggerContract(contractA, + "testInCallcode(address,uint256)", "\"" + base58C + "\",1", false, + 3, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + infoById = PublicMethed + .getTransactionInfoById(txid, blockingStubFull); + logger.info("txid: " + txid + "\n" + infoById.toString()); + Assert.assertEquals(0, infoById.get().getResultValue()); + logRes = ByteArray.toHexString(infoById.get().getLog(0).getData().toByteArray()); + System.out.println("000000: " + logRes); + b = "41" + logRes.substring(24, 64); + c = logRes.substring(64, 128); + x = ByteArray.toHexString(contractA); + Assert.assertEquals(b, x); + Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000000a", c); + } + + + /** + * constructor. + */ + @AfterClass + public void shutdown() throws InterruptedException { + PublicMethed.freedResource(contractExcAddress, contractExcKey, + testNetAccountAddress, blockingStubFull); + if (channelFull != null) { + channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); + } + } + + +} + diff --git a/framework/src/test/resources/soliditycode/eventLog2.sol b/framework/src/test/resources/soliditycode/eventLog2.sol new file mode 100644 index 00000000000..0ad82f6dd1f --- /dev/null +++ b/framework/src/test/resources/soliditycode/eventLog2.sol @@ -0,0 +1,8 @@ +contract Event { + event log2(uint256,uint256,uint256); + constructor() public payable{} + function messageI() payable public returns (uint ret) { + emit log2(1,1,1); + return 1; + } +} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/opCode.sol b/framework/src/test/resources/soliditycode/opCode.sol new file mode 100644 index 00000000000..ccfe8d56c8a --- /dev/null +++ b/framework/src/test/resources/soliditycode/opCode.sol @@ -0,0 +1,112 @@ +contract A { + constructor() public payable{} + function sssmod() payable public returns (int256) { + int s1 = 3; + int s2 = 2; + int s3 = s1 % s2; + return s3; + } + + function eextcodecopy(address _addr) public returns (bytes memory o_code) { + assembly { + // retrieve the size of the code, this needs assembly + let size := extcodesize(_addr) + // allocate output byte array - this could also be done without assembly + // by using o_code = new bytes(size) + o_code := mload(0x40) + // new "memory end" including padding + mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f)))) + // store length in memory + mstore(o_code, size) + // actually retrieve the code, this needs assembly + extcodecopy(_addr, add(o_code, 0x20), 0, size) + } + } + + function cccoinbase() public returns (address) { + return block.coinbase; + } + + function ddifficulty() public returns (uint256) { + return block.difficulty; + } + + function gggaslimit() public returns (uint256) { + return block.gaslimit; + } + + //pc() is disabled from solidity 0.7.0 +// function ppppc() public returns (uint a) { +// assembly { +// a := pc() +// } +// } + +// function mmmsize() public returns (uint a) { +// assembly { +// // a := pc() +// a := msize() +// } +// } + + function ssswap() public returns (int a) { + int a=1; + int b=2; + int c=3; + int d=3; + int e=3; + int f=3; + int g=3; + int h=3; + int a1=1; + int b1=2; + int c1=3; + int d1=3; + int e1=3; //swap 14 + int f1=3; //swap 15 + int g1=3; //swap 16 + return (a); + } + + function pppushx() public returns (uint256) { + return 0x11223344556677889900112233; //push13 +// return 0x1122334455667788990011223344; //push14 +// return 0x112233445566778899001122334455; //push15 +// return 0x11223344556677889900112233445566; //push16 +// return 0x1122334455667788990011223344556611; //push17 +// return 0x112233445566778899001122334455661111; //push18 +// return 0x11223344556677889900112233445566111111; //push19 +// return 0x112233445566778899001122334455661111111111; //push21 +// return 0x11223344556677889900112233445566111111111111; //push22 +// return 0x1122334455667788990011223344556611111111111111; //push23 +// return 0x112233445566778899001122334455661111111111111111; //push24 +// return 0x11223344556677889900112233445566111111111111111111; //push25 +// return 0x1122334455667788990011223344556611111111111111111111; //push26 +// return 0x112233445566778899001122334455661111111111111111111111; //push27 +// return 0x11223344556677889900112233445566111111111111111111111111; //push28 +// return 0x112233445566778899001122334455661111111111111111111111111111; //push30 + } + + // for test09Callcode +// function testInCall(address callCAddress,uint256 amount) payable public{ +// callCAddress.call.value(10)(abi.encodeWithSignature("trans(uint256)",amount)); +// } +// function testIndelegateCall(address callCAddress,uint256 amount) payable public{ +// callCAddress.delegatecall(abi.encodeWithSignature("trans(uint256)",amount)); +// } +// +// function testInCallcode(address callCAddress,uint256 amount) payable public{ +// callCAddress.callcode.value(10)(abi.encodeWithSignature("trans(uint256)",amount)); +// } +} + +//for test09Callcode +//contract C{ +// event clog(address,uint256,uint256); +// constructor() payable public{} +// fallback() payable external{} +// function trans(uint256 amount) payable public{ +// emit clog(msg.sender,msg.value,amount); +// } +// +//} \ No newline at end of file From 203bc52569d11719b99cae510f6be008194e1892 Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Fri, 3 Dec 2021 18:19:11 +0800 Subject: [PATCH 07/24] framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java --- .../common/client/utils/JsonRpcBase.java | 721 +++++++++--------- 1 file changed, 370 insertions(+), 351 deletions(-) diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java index ae76505c0b5..38beefc88b4 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java @@ -9,6 +9,7 @@ import io.grpc.ManagedChannelBuilder; import io.grpc.Status; import io.netty.util.internal.StringUtil; + import java.math.BigInteger; import java.util.HashMap; import java.util.Optional; @@ -44,359 +45,377 @@ @Slf4j public class JsonRpcBase { - public final String foundationAccountKey = - Configuration.getByPath("testng.conf").getString("foundationAccount.key1"); - public final byte[] foundationAccountAddress = PublicMethed.getFinalAddress(foundationAccountKey); - - public static final String jsonRpcOwnerKey = - Configuration.getByPath("testng.conf").getString("defaultParameter.jsonRpcOwnerKey"); - public static final byte[] jsonRpcOwnerAddress = PublicMethed.getFinalAddress(jsonRpcOwnerKey); - public static final String jsonRpcOwnerAddressString = - PublicMethed.getAddressString(jsonRpcOwnerKey); - public static String jsonRpcNode = - Configuration.getByPath("testng.conf").getStringList("jsonRpcNode.ip.list").get(0); - public static String httpFullNode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(0); - public static String solidityNode = - Configuration.getByPath("testng.conf").getStringList("solidityNode.ip.list").get(0); - public static String ethHttpsNode = - Configuration.getByPath("testng.conf").getStringList("ethHttpsNode.host.list").get(0); - - public ManagedChannel channelFull = null; - public WalletGrpc.WalletBlockingStub blockingStubFull = null; - public ManagedChannel channelSolidity = null; - public ManagedChannel channelPbft = null; - public String data = null; - public String paramString = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - public String fullnode = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(0); - - public static long maxFeeLimit = - Configuration.getByPath("testng.conf").getLong("defaultParameter.maxFeeLimit"); - public static String trc20AddressByteString; - public static String trc20AddressHex; - public static String contractAddressFrom58; - public static String contractTrc20AddressFrom58; - public static String contractAddressFromHex; - public static ByteString shieldAddressByteString; - public static byte[] shieldAddressByte; - public static String shieldAddress; - public static String deployTrc20Txid; - public static String deployShieldTxid; - public static String mint = "mint(uint256,bytes32[9],bytes32[2],bytes32[21])"; - public static String transfer = - "transfer(bytes32[10][],bytes32[2][],bytes32[9][],bytes32[2],bytes32[21][])"; - public static String burn = - "burn(bytes32[10],bytes32[2],uint256,bytes32[2],address," - + "bytes32[3],bytes32[9][],bytes32[21][])"; - public Wallet wallet = new Wallet(); - static HttpResponse response; - static HttpPost httppost; - static JSONObject responseContent; - public static Integer scalingFactorLogarithm = 0; - public static Long totalSupply = 1000000000000L; - public static String name = "jsonrpc-test"; - public static String jsonRpcAssetId; - public static Integer blockNum; - public static Integer blockNumForTrc20; - public static String blockNumHex; - public static String blockId; - public static String txid; - public static String trc20Txid; - - /** constructor. */ - @BeforeSuite(enabled = true, description = "Deploy json rpc test case resource") - public void deployJsonRpcUseResource() throws Exception { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue( - PublicMethed.sendcoin( - jsonRpcOwnerAddress, - 2048000000L, - foundationAccountAddress, - foundationAccountKey, - blockingStubFull)); - if (PublicMethed.queryAccount(jsonRpcOwnerAddress, blockingStubFull).getAssetV2Count() == 0L) { - Assert.assertTrue( - PublicMethed.sendcoin( - jsonRpcOwnerAddress, - 2048000000L, - foundationAccountAddress, - foundationAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // Create a new Asset Issue - Assert.assertTrue( - PublicMethed.createAssetIssue( - jsonRpcOwnerAddress, - name, - totalSupply, - 1, - 1, - System.currentTimeMillis() + 5000, - System.currentTimeMillis() + 1000000000, - 1, - "description", - "urlurlurl", - 2000L, - 2000L, - 1L, - 1L, - jsonRpcOwnerKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); + public final String foundationAccountKey = + Configuration.getByPath("testng.conf").getString("foundationAccount.key1"); + public final byte[] foundationAccountAddress = PublicMethed.getFinalAddress(foundationAccountKey); + + public static final String jsonRpcOwnerKey = + Configuration.getByPath("testng.conf").getString("defaultParameter.jsonRpcOwnerKey"); + public static final byte[] jsonRpcOwnerAddress = PublicMethed.getFinalAddress(jsonRpcOwnerKey); + public static final String jsonRpcOwnerAddressString = + PublicMethed.getAddressString(jsonRpcOwnerKey); + public static String jsonRpcNode = + Configuration.getByPath("testng.conf").getStringList("jsonRpcNode.ip.list").get(0); + public static String httpFullNode = + Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(0); + public static String solidityNode = + Configuration.getByPath("testng.conf").getStringList("solidityNode.ip.list").get(0); + public static String ethHttpsNode = + Configuration.getByPath("testng.conf").getStringList("ethHttpsNode.host.list").get(0); + + public ManagedChannel channelFull = null; + public WalletGrpc.WalletBlockingStub blockingStubFull = null; + public ManagedChannel channelSolidity = null; + public ManagedChannel channelPbft = null; + public static String data = null; + public String paramString = null; + public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; + public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; + public String fullnode = + Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(0); + + public static long maxFeeLimit = + Configuration.getByPath("testng.conf").getLong("defaultParameter.maxFeeLimit"); + public static String trc20AddressByteString; + public static String trc20AddressHex; + public static String contractAddressFrom58; + public static String contractTrc20AddressFrom58; + public static String contractAddressFromHex; + public static ByteString shieldAddressByteString; + public static byte[] shieldAddressByte; + public static String shieldAddress; + public static String deployTrc20Txid; + public static String deployShieldTxid; + public static String mint = "mint(uint256,bytes32[9],bytes32[2],bytes32[21])"; + public static String transfer = + "transfer(bytes32[10][],bytes32[2][],bytes32[9][],bytes32[2],bytes32[21][])"; + public static String burn = + "burn(bytes32[10],bytes32[2],uint256,bytes32[2],address," + + "bytes32[3],bytes32[9][],bytes32[21][])"; + public Wallet wallet = new Wallet(); + static HttpResponse response; + static HttpPost httppost; + static JSONObject responseContent; + public static Integer scalingFactorLogarithm = 0; + public static Long totalSupply = 1000000000000L; + public static String name = "jsonrpc-test"; + public static String jsonRpcAssetId; + public static Integer blockNum; + public static Integer blockNumForTrc20; + public static String blockNumHex; + public static String blockId; + public static String txid; + public static String trc20Txid; + + /** + * constructor. + */ + @BeforeSuite(enabled = true, description = "Deploy json rpc test case resource") + public void deployJsonRpcUseResource() throws Exception { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); + blockingStubFull = WalletGrpc.newBlockingStub(channelFull); + Assert.assertTrue( + PublicMethed.sendcoin( + jsonRpcOwnerAddress, + 2048000000L, + foundationAccountAddress, + foundationAccountKey, + blockingStubFull)); + if (PublicMethed.queryAccount(jsonRpcOwnerAddress, blockingStubFull).getAssetV2Count() == 0L) { + Assert.assertTrue( + PublicMethed.sendcoin( + jsonRpcOwnerAddress, + 2048000000L, + foundationAccountAddress, + foundationAccountKey, + blockingStubFull)); + PublicMethed.waitProduceNextBlock(blockingStubFull); + + // Create a new Asset Issue + Assert.assertTrue( + PublicMethed.createAssetIssue( + jsonRpcOwnerAddress, + name, + totalSupply, + 1, + 1, + System.currentTimeMillis() + 5000, + System.currentTimeMillis() + 1000000000, + 1, + "description", + "urlurlurl", + 2000L, + 2000L, + 1L, + 1L, + jsonRpcOwnerKey, + blockingStubFull)); + + PublicMethed.waitProduceNextBlock(blockingStubFull); + } + + response = HttpMethed.getAccount(httpFullNode, jsonRpcOwnerAddress); + responseContent = HttpMethed.parseResponseContent(response); + jsonRpcAssetId = responseContent.getString("asset_issued_ID"); + + deployContract(); + triggerContract(); + deployTrc20Contract(); + } + + /** + * constructor. + */ + public void deployContract() throws Exception { + final Long beforeTokenBalance = + PublicMethed.getAssetBalanceByAssetId( + ByteString.copyFromUtf8(jsonRpcAssetId), jsonRpcOwnerKey, blockingStubFull); + + JsonObject param = new JsonObject(); + param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); + param.addProperty("name", "transferTokenContract"); + param.addProperty("gas", "0x245498"); + String filePath = "./src/test/resources/soliditycode/contractTrcToken001.sol"; + String contractName = "tokenTest"; + HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); + + String code = retMap.get("byteCode").toString(); + System.out.println("CODE:" + code); + String abi = retMap.get("abI").toString(); + System.out.println("abi:" + abi); + + param.addProperty("abi", abi); + param.addProperty("data", code); + param.addProperty("consumeUserResourcePercent", 100); + param.addProperty("originEnergyLimit", 11111111111111L); + param.addProperty("value", "0x1f4"); + param.addProperty("tokenId", Long.valueOf(jsonRpcAssetId)); + param.addProperty("tokenValue", 1); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("buildTransaction", params); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String transactionString = responseContent.getJSONObject("result").getString("transaction"); + String transactionSignString = + HttpMethed.gettransactionsign(httpFullNode, transactionString, jsonRpcOwnerKey); + + responseContent = HttpMethed.parseStringContent(transactionString); + final String txid = responseContent.getString("txID"); + response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); + org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); + + HttpMethed.waitToProduceOneBlock(httpFullNode); + Long afterTokenBalance = + PublicMethed.getAssetBalanceByAssetId( + ByteString.copyFromUtf8(jsonRpcAssetId), jsonRpcOwnerKey, blockingStubFull); + + org.junit.Assert.assertEquals(beforeTokenBalance - afterTokenBalance, 1L); + + response = HttpMethed.getTransactionById(httpFullNode, txid); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + org.junit.Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); + contractAddressFrom58 = responseContent.getString("contract_address"); + logger.info("contractAddressFrom58:" + contractAddressFrom58); + } + + /** + * constructor. + */ + public void triggerContract() throws Exception { + final Long beforeTokenBalance = + PublicMethed.getAssetBalanceByAssetId( + ByteString.copyFromUtf8(jsonRpcAssetId), foundationAccountKey, blockingStubFull); + final Long beforeBalance = HttpMethed.getBalance(httpFullNode, jsonRpcOwnerAddress); + JsonObject param = new JsonObject(); + param.addProperty("from", "0x" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2)); + param.addProperty("to", "0x" + contractAddressFrom58); + + String addressParam = + "000000000000000000000000" + + ByteArray.toHexString(foundationAccountAddress).substring(2); // [0,3) + + String tokenIdParam = + "00000000000000000000000000000000000000000000000000000000000" + + Integer.toHexString(Integer.valueOf(jsonRpcAssetId)); + + String tokenValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; + paramString = addressParam + tokenIdParam + tokenValueParam; + logger.info("paramString:" + paramString); + + String selector = "TransferTokenTo(address,trcToken,uint256)"; + // exit(1); + param.addProperty("data", "0x" + Util.parseMethod(selector, paramString)); + data = "0x" + Util.parseMethod(selector, paramString); + param.addProperty("gas", "0x245498"); + param.addProperty("value", "0x1389"); + param.addProperty("tokenId", Long.valueOf(jsonRpcAssetId)); + param.addProperty("tokenValue", 1); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("buildTransaction", params); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String transactionString = responseContent.getJSONObject("result").getString("transaction"); + logger.info("transactionString : " + transactionString); + String transactionSignString = + HttpMethed.gettransactionsign(httpFullNode, transactionString, jsonRpcOwnerKey); + logger.info("transactionSignString:" + transactionSignString); + responseContent = HttpMethed.parseStringContent(transactionString); + txid = responseContent.getString("txID"); + logger.info("triggerTxid:" + txid); + + response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); + logger.info("response:" + response); + HttpMethed.verificationResult(response); + org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); + + HttpMethed.waitToProduceOneBlock(httpFullNode); + Long afterTokenBalance = + PublicMethed.getAssetBalanceByAssetId( + ByteString.copyFromUtf8(jsonRpcAssetId), foundationAccountKey, blockingStubFull); + Long afterBalance = HttpMethed.getBalance(httpFullNode, jsonRpcOwnerAddress); + + org.junit.Assert.assertEquals(beforeTokenBalance - afterTokenBalance, -1L); + org.junit.Assert.assertTrue(beforeBalance - afterBalance >= 5000); + + blockNum = + (int) (PublicMethed.getTransactionInfoById(txid, blockingStubFull).get().getBlockNumber()); + PublicMethed.waitProduceNextBlock(blockingStubFull); + response = HttpMethed.getBlockByNum(httpFullNode, blockNum); + org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + blockId = responseContent.get("blockID").toString(); + } + + /** + * constructor. + */ + public void deployTrc20Contract() throws InterruptedException { + String contractName = "shieldTrc20Token"; + + String abi = Configuration.getByPath("testng.conf").getString("abi.abi_shieldTrc20Token"); + String code = Configuration.getByPath("testng.conf").getString("code.code_shieldTrc20Token"); + String constructorStr = "constructor(uint256,string,string)"; + String data = totalSupply.toString() + "," + "\"TokenTRC20\"" + "," + "\"zen20\""; + logger.info("data:" + data); + deployTrc20Txid = + PublicMethed.deployContractWithConstantParame( + contractName, + abi, + code, + constructorStr, + data, + "", + maxFeeLimit, + 0L, + 100, + null, + jsonRpcOwnerKey, + jsonRpcOwnerAddress, + blockingStubFull); + + PublicMethed.waitProduceNextBlock(blockingStubFull); + logger.info("deployTrc20Txid:" + deployTrc20Txid); + response = HttpMethed.getTransactionById(httpFullNode, deployTrc20Txid); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + org.junit.Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); + contractTrc20AddressFrom58 = responseContent.getString("contract_address"); + logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); + + // NewFilterId = createNewFilterId(); + + Optional infoById = + PublicMethed.getTransactionInfoById(deployTrc20Txid, blockingStubFull); + + trc20AddressHex = ByteArray.toHexString(infoById.get().getContractAddress().toByteArray()); + byte[] trc20Address = infoById.get().getContractAddress().toByteArray(); + + String selector = "transfer(address,uint256)"; + String addressParam = + "000000000000000000000000" + + ByteArray.toHexString(foundationAccountAddress).substring(2); // [0,3) + String transferValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; + String paramString = addressParam + transferValueParam; + trc20Txid = + PublicMethed.triggerContract( + trc20Address, + selector, + paramString, + true, + 0, + maxFeeLimit, + "0", + 0, + jsonRpcOwnerAddress, + jsonRpcOwnerKey, + blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + blockNumForTrc20 = + (int) + (PublicMethed.getTransactionInfoById(trc20Txid, blockingStubFull) + .get() + .getBlockNumber()); } - response = HttpMethed.getAccount(httpFullNode, jsonRpcOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - jsonRpcAssetId = responseContent.getString("asset_issued_ID"); - - deployContract(); - triggerContract(); - deployTrc20Contract(); - } - - /** constructor. */ - public void deployContract() throws Exception { - final Long beforeTokenBalance = - PublicMethed.getAssetBalanceByAssetId( - ByteString.copyFromUtf8(jsonRpcAssetId), jsonRpcOwnerKey, blockingStubFull); - - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("name", "transferTokenContract"); - param.addProperty("gas", "0x245498"); - String filePath = "./src/test/resources/soliditycode/contractTrcToken001.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - System.out.println("CODE:" + code); - String abi = retMap.get("abI").toString(); - System.out.println("abi:" + abi); - - param.addProperty("abi", abi); - param.addProperty("data", code); - param.addProperty("consumeUserResourcePercent", 100); - param.addProperty("originEnergyLimit", 11111111111111L); - param.addProperty("value", "0x1f4"); - param.addProperty("tokenId", Long.valueOf(jsonRpcAssetId)); - param.addProperty("tokenValue", 1); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("buildTransaction", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String transactionString = responseContent.getJSONObject("result").getString("transaction"); - String transactionSignString = - HttpMethed.gettransactionsign(httpFullNode, transactionString, jsonRpcOwnerKey); - - responseContent = HttpMethed.parseStringContent(transactionString); - final String txid = responseContent.getString("txID"); - response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); - org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpFullNode); - Long afterTokenBalance = - PublicMethed.getAssetBalanceByAssetId( - ByteString.copyFromUtf8(jsonRpcAssetId), jsonRpcOwnerKey, blockingStubFull); - - org.junit.Assert.assertEquals(beforeTokenBalance - afterTokenBalance, 1L); - - response = HttpMethed.getTransactionById(httpFullNode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - org.junit.Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); - contractAddressFrom58 = responseContent.getString("contract_address"); - logger.info("contractAddressFrom58:" + contractAddressFrom58); - } - - /** constructor. */ - public void triggerContract() throws Exception { - final Long beforeTokenBalance = - PublicMethed.getAssetBalanceByAssetId( - ByteString.copyFromUtf8(jsonRpcAssetId), foundationAccountKey, blockingStubFull); - final Long beforeBalance = HttpMethed.getBalance(httpFullNode, jsonRpcOwnerAddress); - JsonObject param = new JsonObject(); - param.addProperty("from", "0x" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2)); - param.addProperty("to", "0x" + contractAddressFrom58); - - String addressParam = - "000000000000000000000000" - + ByteArray.toHexString(foundationAccountAddress).substring(2); // [0,3) - - String tokenIdParam = - "00000000000000000000000000000000000000000000000000000000000" - + Integer.toHexString(Integer.valueOf(jsonRpcAssetId)); - - String tokenValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; - paramString = addressParam + tokenIdParam + tokenValueParam; - logger.info("paramString:" + paramString); - - String selector = "TransferTokenTo(address,trcToken,uint256)"; - // exit(1); - param.addProperty("data", "0x" + Util.parseMethod(selector, paramString)); - data = "0x" + Util.parseMethod(selector, paramString); - param.addProperty("gas", "0x245498"); - param.addProperty("value", "0x1389"); - param.addProperty("tokenId", Long.valueOf(jsonRpcAssetId)); - param.addProperty("tokenValue", 1); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("buildTransaction", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String transactionString = responseContent.getJSONObject("result").getString("transaction"); - logger.info("transactionString : " + transactionString); - String transactionSignString = - HttpMethed.gettransactionsign(httpFullNode, transactionString, jsonRpcOwnerKey); - logger.info("transactionSignString:" + transactionSignString); - responseContent = HttpMethed.parseStringContent(transactionString); - txid = responseContent.getString("txID"); - logger.info("triggerTxid:" + txid); - - response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); - logger.info("response:" + response); - HttpMethed.verificationResult(response); - org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpFullNode); - Long afterTokenBalance = - PublicMethed.getAssetBalanceByAssetId( - ByteString.copyFromUtf8(jsonRpcAssetId), foundationAccountKey, blockingStubFull); - Long afterBalance = HttpMethed.getBalance(httpFullNode, jsonRpcOwnerAddress); - - org.junit.Assert.assertEquals(beforeTokenBalance - afterTokenBalance, -1L); - org.junit.Assert.assertTrue(beforeBalance - afterBalance >= 5000); - - blockNum = - (int) (PublicMethed.getTransactionInfoById(txid, blockingStubFull).get().getBlockNumber()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - response = HttpMethed.getBlockByNum(httpFullNode, blockNum); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - blockId = responseContent.get("blockID").toString(); - } - - /** constructor. */ - public void deployTrc20Contract() throws InterruptedException { - String contractName = "shieldTrc20Token"; - - String abi = Configuration.getByPath("testng.conf").getString("abi.abi_shieldTrc20Token"); - String code = Configuration.getByPath("testng.conf").getString("code.code_shieldTrc20Token"); - String constructorStr = "constructor(uint256,string,string)"; - String data = totalSupply.toString() + "," + "\"TokenTRC20\"" + "," + "\"zen20\""; - logger.info("data:" + data); - deployTrc20Txid = - PublicMethed.deployContractWithConstantParame( - contractName, - abi, - code, - constructorStr, - data, - "", - maxFeeLimit, - 0L, - 100, - null, - jsonRpcOwnerKey, - jsonRpcOwnerAddress, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("deployTrc20Txid:" + deployTrc20Txid); - response = HttpMethed.getTransactionById(httpFullNode, deployTrc20Txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - org.junit.Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); - contractTrc20AddressFrom58 = responseContent.getString("contract_address"); - logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); - - // NewFilterId = createNewFilterId(); - - Optional infoById = - PublicMethed.getTransactionInfoById(deployTrc20Txid, blockingStubFull); - - trc20AddressHex = ByteArray.toHexString(infoById.get().getContractAddress().toByteArray()); - byte[] trc20Address = infoById.get().getContractAddress().toByteArray(); - - String selector = "transfer(address,uint256)"; - String addressParam = - "000000000000000000000000" - + ByteArray.toHexString(foundationAccountAddress).substring(2); // [0,3) - String transferValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; - String paramString = addressParam + transferValueParam; - trc20Txid = - PublicMethed.triggerContract( - trc20Address, - selector, - paramString, - true, - 0, - maxFeeLimit, - "0", - 0, - jsonRpcOwnerAddress, - jsonRpcOwnerKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - blockNumForTrc20 = - (int) - (PublicMethed.getTransactionInfoById(trc20Txid, blockingStubFull) - .get() - .getBlockNumber()); - } - - /** constructor. */ - public static HttpResponse getEthHttps(String ethHttpsNode, JsonObject jsonRpcObject) { - try { - String requestUrl = "https://" + ethHttpsNode + "/v3/dfb752dd45204b8daae74249f4653584"; - response = HttpMethed.createConnect(requestUrl, jsonRpcObject); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; + /** + * constructor. + */ + public static HttpResponse getEthHttps(String ethHttpsNode, JsonObject jsonRpcObject) { + try { + String requestUrl = "https://" + ethHttpsNode + "/v3/dfb752dd45204b8daae74249f4653584"; + response = HttpMethed.createConnect(requestUrl, jsonRpcObject); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; } - return response; - } - - /** constructor. */ - public static HttpResponse getJsonRpc(String jsonRpcNode, JsonObject jsonRpcObject) { - try { - String requestUrl = "http://" + jsonRpcNode + "/jsonrpc"; - response = HttpMethed.createConnect(requestUrl, jsonRpcObject); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; + + /** + * constructor. + */ + public static HttpResponse getJsonRpc(String jsonRpcNode, JsonObject jsonRpcObject) { + try { + String requestUrl = "http://" + jsonRpcNode + "/jsonrpc"; + response = HttpMethed.createConnect(requestUrl, jsonRpcObject); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static JsonObject getJsonRpcBody(String method) { + return getJsonRpcBody(method, new JsonArray(), 1); + } + + /** + * constructor. + */ + public static JsonObject getJsonRpcBody(String method, JsonArray params) { + return getJsonRpcBody(method, params, 1); + } + + /** + * constructor. + */ + public static JsonObject getJsonRpcBody(String method, JsonArray params, Integer id) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("jsonrpc", "2.0"); + jsonObject.addProperty("method", method); + jsonObject.add("params", params); + jsonObject.addProperty("id", id); + + return jsonObject; } - return response; - } - - /** constructor. */ - public static JsonObject getJsonRpcBody(String method) { - return getJsonRpcBody(method, new JsonArray(), 1); - } - - /** constructor. */ - public static JsonObject getJsonRpcBody(String method, JsonArray params) { - return getJsonRpcBody(method, params, 1); - } - - /** constructor. */ - public static JsonObject getJsonRpcBody(String method, JsonArray params, Integer id) { - JsonObject jsonObject = new JsonObject(); - jsonObject.addProperty("jsonrpc", "2.0"); - jsonObject.addProperty("method", method); - jsonObject.add("params", params); - jsonObject.addProperty("id", id); - - return jsonObject; - } } From 16346197971c3502d26dcf0f37e872016da534dd Mon Sep 17 00:00:00 2001 From: sophiawang <1975054324@qq.com> Date: Mon, 6 Dec 2021 11:41:08 +0800 Subject: [PATCH 08/24] fix case for opcode test in linux --- .../dailybuild/tvmnewcommand/newGrammar/Opcode.java | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java index 64e86395791..ea72aa3bdb1 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java @@ -137,18 +137,7 @@ public void test02Extcodecopy() { + "81610572565b840191505092915050565b6103cf81610485565b82525050565b6103de816104d0" + "565b82525050565b60006020820190506103f9600083018461037e565b92915050565b60006020" + "820190508181036000830152610419818461038d565b905092915050565b600060208201905061" - + "043660008301846103c6565b92915050565b600060208201905061045160008301846103d5565b" - + "92915050565b600081519050919050565b600082825260208201905092915050565b600061047e" - + "8261048f565b9050919050565b6000819050919050565b600073ffffffffffffffffffffffffff" - + "ffffffffffffff82169050919050565b600074ffffffffffffffffffffffffffffffffffffffff" - + "ff82169050919050565b6000819050919050565b60005b838110156104f8578082015181840152" - + "6020810190506104dd565b83811115610507576000848401525b50505050565b60006105188261" - + "0485565b915061052383610485565b9250826105335761053261053e565b5b8282079050929150" - + "50565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052" - + "601260045260246000fd5b600080fd5b6000601f19601f8301169050919050565b61058c816104" - + "af565b811461059757600080fd5b5056fea26474726f6e582212205dba90535ae40d8e2cafc63f" - + "67490cd4bcb4b3600957a9d8e03c201725728c2d64736f6c637822302e382e372d63692e323032" - + "312e372e32302b636f6d6d69742e32313238636465350053000000000000000000000000000000" + )); } From 3800854f53ee36596093c7165be74d6862664d31 Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Mon, 6 Dec 2021 12:15:04 +0800 Subject: [PATCH 09/24] add --- .../common/client/utils/HttpMethed.java | 10584 +++++++------ .../common/client/utils/PublicMethed.java | 13002 ++++++++-------- 2 files changed, 11792 insertions(+), 11794 deletions(-) diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java index b8e4b2dcf8a..ce84cc011b2 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java @@ -8,12 +8,14 @@ import com.google.gson.JsonParser; import com.google.protobuf.ByteString; import io.netty.util.internal.StringUtil; + import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; + import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; @@ -35,5317 +37,5313 @@ @Slf4j public class HttpMethed { - static HttpClient httpClient; - static HttpPost httppost; - static HttpResponse response; - static Integer connectionTimeout = Configuration.getByPath("testng.conf") - .getInt("defaultParameter.httpConnectionTimeout"); - static Integer soTimeout = Configuration.getByPath("testng.conf") - .getInt("defaultParameter.httpSoTimeout"); - static String transactionString; - static String transactionSignString; - static JSONObject responseContent; - static JSONObject signResponseContent; - static JSONObject transactionApprovedListContent; - public static volatile Integer witnessNum; - - /** - * constructor. - */ - private static volatile String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list") - .get(1); - - /** - * constructor. - */ - public static Integer getWitnessNum() { - if (null == witnessNum) { - witnessNum = parseResponseContent(listwitnesses(httpnode)).getJSONArray("witnesses").size(); - } - - return witnessNum; - } - - static { - PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(); - pccm.setDefaultMaxPerRoute(80); - pccm.setMaxTotal(100); - - httpClient = new DefaultHttpClient(pccm); - } - - /** - * constructor. - */ - public static HttpResponse updateAccount(String httpNode, byte[] updateAccountAddress, - String accountName, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/updateaccount"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("account_name", str2hex(accountName)); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(updateAccountAddress)); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse setAccountId(String httpNode, byte[] setAccountIdAddress, - String accountId, Boolean visable, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/setaccountid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("account_id", accountId); - userBaseObj2.addProperty("owner_address", - Base58.encode58Check(PublicMethed.getFinalAddress(fromKey))); - userBaseObj2.addProperty("visible", visable); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse updateWitness(String httpNode, byte[] witnessAddress, String updateUrl, - String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/updatewitness"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("update_url", str2hex(updateUrl)); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(witnessAddress)); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse voteWitnessAccount(String httpNode, byte[] ownerAddress, - JsonArray voteArray, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/votewitnessaccount"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.add("votes", voteArray); - logger.info(userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse createAccount(String httpNode, byte[] ownerAddress, - byte[] accountAddress, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createaccount"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("account_address", ByteArray.toHexString(accountAddress)); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse createWitness(String httpNode, byte[] ownerAddress, String url) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createwitness"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("url", str2hex(url)); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - //transactionString = EntityUtils.toString(response.getEntity()); - //transactionSignString = gettransactionsign(httpNode,transactionString,fromKey); - //response = broadcastTransaction(httpNode,transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse withdrawBalance(String httpNode, byte[] witnessAddress) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/withdrawbalance"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(witnessAddress)); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - //transactionString = EntityUtils.toString(response.getEntity()); - //transactionSignString = gettransactionsign(httpNode,transactionString,fromKey); - //response = broadcastTransaction(httpNode,transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse sendCoin(String httpNode, byte[] fromAddress, byte[] toAddress, - Long amount, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(fromAddress)); - userBaseObj2.addProperty("amount", amount); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse sendCoin(String httpNode, byte[] fromAddress, byte[] toAddress, - Long amount, Integer permissionId, String[] managerKeys) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(fromAddress)); - userBaseObj2.addProperty("amount", amount); - userBaseObj2.addProperty("Permission_id", permissionId); - response = createConnect(requestUrl, userBaseObj2); - transactionSignString = EntityUtils.toString(response.getEntity()); - HttpResponse getSignWeightResponse; - HttpResponse getTransactionApprovedListResponse; - - for (String key : managerKeys) { - transactionSignString = gettransactionsign(httpNode, transactionSignString, key); - getSignWeightResponse = getSignWeight(httpNode, transactionSignString); - signResponseContent = parseResponseContent(getSignWeightResponse); - logger.info("-----------sign information-----------------"); - printJsonContent(signResponseContent); - getSignWeightResponse = getTransactionApprovedList(httpNode, transactionSignString); - signResponseContent = parseResponseContent(getSignWeightResponse); - logger.info("-----------get Transaction Approved List-----------------"); - printJsonContent(signResponseContent); - - - } - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static String sendCoin(String httpNode, byte[] fromAddress, byte[] toAddress, Long amount, - String notes, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(fromAddress)); - userBaseObj2.addProperty("amount", amount); - userBaseObj2.addProperty("extra_data", ByteArray.toHexString(notes.getBytes())); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseStringContent(transactionString); - return responseContent.getString("txID"); - } - - /** - * constructor. - */ - public static String sendCoinGetTxid(String httpNode, byte[] fromAddress, byte[] toAddress, - Long amount, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(fromAddress)); - userBaseObj2.addProperty("amount", amount); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseStringContent(transactionString); - logger.info(responseContent.getString("txID")); - return responseContent.getString("txID"); - } - - /** - * constructor. - */ - public static HttpResponse createProposal(String httpNode, byte[] ownerAddress, Long proposalKey, - Long proposalValue, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/proposalcreate"; - JsonObject userBaseObj2 = new JsonObject(); - JsonObject proposalMap = new JsonObject(); - proposalMap.addProperty("key", proposalKey); - proposalMap.addProperty("value", proposalValue); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.add("parameters", proposalMap); - - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse approvalProposal(String httpNode, byte[] ownerAddress, - Integer proposalId, Boolean isAddApproval, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/proposalapprove"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("proposal_id", proposalId); - userBaseObj2.addProperty("is_add_approval", isAddApproval); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse deleteProposal(String httpNode, byte[] ownerAddress, - Integer proposalId, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/proposaldelete"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("proposal_id", proposalId); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getEnergyPric(String httpNode) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getenergyprices"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - /** - * constructor. - */ - - public static HttpResponse getChainParameters(String httpNode) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getchainparameters"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse accountPermissionUpdate(String httpNode, byte[] ownerAddress, - JsonObject ownerObject, JsonObject witnessObject, JsonObject activesObject, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/accountpermissionupdate"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.add("owner", ownerObject); - //userBaseObj2.add("witness", witnessObject); - userBaseObj2.add("actives", activesObject); - logger.info(userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse exchangeCreate(String httpNode, byte[] ownerAddress, - String firstTokenId, Long firstTokenBalance, String secondTokenId, Long secondTokenBalance, - String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/exchangecreate"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("first_token_id", str2hex(firstTokenId)); - userBaseObj2.addProperty("first_token_balance", firstTokenBalance); - userBaseObj2.addProperty("second_token_id", str2hex(secondTokenId)); - userBaseObj2.addProperty("second_token_balance", secondTokenBalance); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse exchangeInject(String httpNode, byte[] ownerAddress, - Integer exchangeId, String tokenId, Long quant, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/exchangeinject"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("exchange_id", exchangeId); - userBaseObj2.addProperty("token_id", str2hex(tokenId)); - userBaseObj2.addProperty("quant", quant); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse exchangeWithdraw(String httpNode, byte[] ownerAddress, - Integer exchangeId, String tokenId, Long quant, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/exchangewithdraw"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("exchange_id", exchangeId); - userBaseObj2.addProperty("token_id", str2hex(tokenId)); - userBaseObj2.addProperty("quant", quant); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse exchangeTransaction(String httpNode, byte[] ownerAddress, - Integer exchangeId, String tokenId, Long quant, Long expected, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/exchangetransaction"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("exchange_id", exchangeId); - userBaseObj2.addProperty("token_id", str2hex(tokenId)); - userBaseObj2.addProperty("quant", quant); - userBaseObj2.addProperty("expected", expected); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse assetIssue(String httpNode, byte[] ownerAddress, String name, - String abbr, Long totalSupply, Integer trxNum, Integer num, Long startTime, Long endTime, - Integer voteScore, Integer precision, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createassetissue"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("name", str2hex(name)); - userBaseObj2.addProperty("abbr", str2hex(abbr)); - userBaseObj2.addProperty("total_supply", totalSupply); - userBaseObj2.addProperty("trx_num", trxNum); - userBaseObj2.addProperty("num", num); - userBaseObj2.addProperty("precision", precision); - userBaseObj2.addProperty("start_time", startTime); - userBaseObj2.addProperty("end_time", endTime); - userBaseObj2.addProperty("vote_score", voteScore); - userBaseObj2.addProperty("description", str2hex(description)); - userBaseObj2.addProperty("url", str2hex(url)); - userBaseObj2.addProperty("free_asset_net_limit", freeAssetNetLimit); - userBaseObj2.addProperty("public_free_asset_net_limit", publicFreeAssetNetLimit); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse transferAsset(String httpNode, byte[] ownerAddress, byte[] toAddress, - String assetIssueById, Long amount, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/transferasset"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("asset_name", str2hex(assetIssueById)); - userBaseObj2.addProperty("amount", amount); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse deployContract(String httpNode, String name, String abi, - String bytecode, Long bandwidthLimit, Long feeLimit, Integer consumeUserResourcePercent, - Long originEnergyLimit, Long callValue, Integer tokenId, Long tokenValue, byte[] ownerAddress, - String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/deploycontract"; - JsonObject userBaseObj2 = new JsonObject(); - //userBaseObj2.addProperty("name", str2hex(name)); - userBaseObj2.addProperty("name", name); - userBaseObj2.addProperty("abi", abi); - userBaseObj2.addProperty("bytecode", bytecode); - userBaseObj2.addProperty("bandwidth_limit", bandwidthLimit); - userBaseObj2.addProperty("fee_limit", feeLimit); - userBaseObj2.addProperty("consume_user_resource_percent", consumeUserResourcePercent); - userBaseObj2.addProperty("origin_energy_limit", originEnergyLimit); - userBaseObj2.addProperty("call_value", callValue); - userBaseObj2.addProperty("token_id", tokenId); - userBaseObj2.addProperty("tokenValue", tokenValue); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static String deployContractGetTxid(String httpNode, String name, String abi, - String bytecode, Long bandwidthLimit, Long feeLimit, Integer consumeUserResourcePercent, - Long originEnergyLimit, Long callValue, Integer tokenId, Long tokenValue, byte[] ownerAddress, + static HttpClient httpClient; + static HttpPost httppost; + static HttpResponse response; + static Integer connectionTimeout = Configuration.getByPath("testng.conf") + .getInt("defaultParameter.httpConnectionTimeout"); + static Integer soTimeout = Configuration.getByPath("testng.conf") + .getInt("defaultParameter.httpSoTimeout"); + static String transactionString; + static String transactionSignString; + static JSONObject responseContent; + static JSONObject signResponseContent; + static JSONObject transactionApprovedListContent; + public static volatile Integer witnessNum; + + /** + * constructor. + */ + private static volatile String httpnode = Configuration.getByPath("testng.conf") + .getStringList("httpnode.ip.list") + .get(1); + + /** + * constructor. + */ + public static Integer getWitnessNum() { + if (null == witnessNum) { + witnessNum = parseResponseContent(listwitnesses(httpnode)).getJSONArray("witnesses").size(); + } + + return witnessNum; + } + + static { + PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(); + pccm.setDefaultMaxPerRoute(80); + pccm.setMaxTotal(100); + + httpClient = new DefaultHttpClient(pccm); + } + + /** + * constructor. + */ + public static HttpResponse updateAccount(String httpNode, byte[] updateAccountAddress, + String accountName, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/updateaccount"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("account_name", str2hex(accountName)); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(updateAccountAddress)); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse setAccountId(String httpNode, byte[] setAccountIdAddress, + String accountId, Boolean visable, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/setaccountid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("account_id", accountId); + userBaseObj2.addProperty("owner_address", + Base58.encode58Check(PublicMethed.getFinalAddress(fromKey))); + userBaseObj2.addProperty("visible", visable); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse updateWitness(String httpNode, byte[] witnessAddress, String updateUrl, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/deploycontract"; - JsonObject userBaseObj2 = new JsonObject(); - //userBaseObj2.addProperty("name", str2hex(name)); - userBaseObj2.addProperty("name", name); - userBaseObj2.addProperty("abi", abi); - userBaseObj2.addProperty("bytecode", bytecode); - userBaseObj2.addProperty("bandwidth_limit", bandwidthLimit); - userBaseObj2.addProperty("fee_limit", feeLimit); - userBaseObj2.addProperty("consume_user_resource_percent", consumeUserResourcePercent); - userBaseObj2.addProperty("origin_energy_limit", originEnergyLimit); - userBaseObj2.addProperty("call_value", callValue); - userBaseObj2.addProperty("token_id", tokenId); - userBaseObj2.addProperty("call_token_value", tokenValue); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - - logger.info(userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseStringContent(transactionString); - return responseContent.getString("txID"); - } - - /** - * constructor. - */ - public static HttpResponse deployContractGetTxidWithTooBigLong(String httpNode, String name, - String abi, String bytecode, Long bandwidthLimit, Long feeLimit, - Integer consumeUserResourcePercent, Long originEnergyLimit, Long callValue, Integer tokenId, - Long tokenValue, byte[] ownerAddress, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/deploycontract"; - - String text = "{\"call_token_value\": 10000000e100000000}"; - JSONObject jsonObject = JSONObject.parseObject(text); - logger.info("jsonObject: " + jsonObject.toString()); - jsonObject.put("name", name); - jsonObject.put("abi", abi); - jsonObject.put("bytecode", bytecode); - jsonObject.put("bandwidth_limit", bandwidthLimit); - jsonObject.put("fee_limit", feeLimit); - jsonObject.put("consume_user_resource_percent", consumeUserResourcePercent); - jsonObject.put("origin_energy_limit", originEnergyLimit); - jsonObject.put("call_value", callValue); - jsonObject.put("token_id", tokenId); - jsonObject.put("owner_address", ByteArray.toHexString(ownerAddress)); - - logger.info(jsonObject.toString()); - response = createConnect1(requestUrl, jsonObject); + try { + final String requestUrl = "http://" + httpNode + "/wallet/updatewitness"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("update_url", str2hex(updateUrl)); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(witnessAddress)); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse voteWitnessAccount(String httpNode, byte[] ownerAddress, + JsonArray voteArray, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/votewitnessaccount"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.add("votes", voteArray); + logger.info(userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse createAccount(String httpNode, byte[] ownerAddress, + byte[] accountAddress, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createaccount"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("account_address", ByteArray.toHexString(accountAddress)); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse createWitness(String httpNode, byte[] ownerAddress, String url) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createwitness"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("url", str2hex(url)); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + response = createConnect(requestUrl, userBaseObj2); + logger.info(userBaseObj2.toString()); + //transactionString = EntityUtils.toString(response.getEntity()); + //transactionSignString = gettransactionsign(httpNode,transactionString,fromKey); + //response = broadcastTransaction(httpNode,transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse withdrawBalance(String httpNode, byte[] witnessAddress) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/withdrawbalance"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(witnessAddress)); + response = createConnect(requestUrl, userBaseObj2); + logger.info(userBaseObj2.toString()); + //transactionString = EntityUtils.toString(response.getEntity()); + //transactionSignString = gettransactionsign(httpNode,transactionString,fromKey); + //response = broadcastTransaction(httpNode,transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse sendCoin(String httpNode, byte[] fromAddress, byte[] toAddress, + Long amount, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(fromAddress)); + userBaseObj2.addProperty("amount", amount); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse sendCoin(String httpNode, byte[] fromAddress, byte[] toAddress, + Long amount, Integer permissionId, String[] managerKeys) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(fromAddress)); + userBaseObj2.addProperty("amount", amount); + userBaseObj2.addProperty("Permission_id", permissionId); + response = createConnect(requestUrl, userBaseObj2); + transactionSignString = EntityUtils.toString(response.getEntity()); + HttpResponse getSignWeightResponse; + HttpResponse getTransactionApprovedListResponse; + + for (String key : managerKeys) { + transactionSignString = gettransactionsign(httpNode, transactionSignString, key); + getSignWeightResponse = getSignWeight(httpNode, transactionSignString); + signResponseContent = parseResponseContent(getSignWeightResponse); + logger.info("-----------sign information-----------------"); + printJsonContent(signResponseContent); + getSignWeightResponse = getTransactionApprovedList(httpNode, transactionSignString); + signResponseContent = parseResponseContent(getSignWeightResponse); + logger.info("-----------get Transaction Approved List-----------------"); + printJsonContent(signResponseContent); + + + } + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static String sendCoin(String httpNode, byte[] fromAddress, byte[] toAddress, Long amount, + String notes, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(fromAddress)); + userBaseObj2.addProperty("amount", amount); + userBaseObj2.addProperty("extra_data", ByteArray.toHexString(notes.getBytes())); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseStringContent(transactionString); + return responseContent.getString("txID"); + } + + /** + * constructor. + */ + public static String sendCoinGetTxid(String httpNode, byte[] fromAddress, byte[] toAddress, + Long amount, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(fromAddress)); + userBaseObj2.addProperty("amount", amount); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseStringContent(transactionString); + logger.info(responseContent.getString("txID")); + return responseContent.getString("txID"); + } + + /** + * constructor. + */ + public static HttpResponse createProposal(String httpNode, byte[] ownerAddress, Long proposalKey, + Long proposalValue, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/proposalcreate"; + JsonObject userBaseObj2 = new JsonObject(); + JsonObject proposalMap = new JsonObject(); + proposalMap.addProperty("key", proposalKey); + proposalMap.addProperty("value", proposalValue); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.add("parameters", proposalMap); + + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse approvalProposal(String httpNode, byte[] ownerAddress, + Integer proposalId, Boolean isAddApproval, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/proposalapprove"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("proposal_id", proposalId); + userBaseObj2.addProperty("is_add_approval", isAddApproval); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse deleteProposal(String httpNode, byte[] ownerAddress, + Integer proposalId, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/proposaldelete"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("proposal_id", proposalId); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getEnergyPric(String httpNode) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getenergyprices"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + + public static HttpResponse getChainParameters(String httpNode) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getchainparameters"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse accountPermissionUpdate(String httpNode, byte[] ownerAddress, + JsonObject ownerObject, JsonObject witnessObject, JsonObject activesObject, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/accountpermissionupdate"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.add("owner", ownerObject); + //userBaseObj2.add("witness", witnessObject); + userBaseObj2.add("actives", activesObject); + logger.info(userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse exchangeCreate(String httpNode, byte[] ownerAddress, + String firstTokenId, Long firstTokenBalance, String secondTokenId, Long secondTokenBalance, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/exchangecreate"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("first_token_id", str2hex(firstTokenId)); + userBaseObj2.addProperty("first_token_balance", firstTokenBalance); + userBaseObj2.addProperty("second_token_id", str2hex(secondTokenId)); + userBaseObj2.addProperty("second_token_balance", secondTokenBalance); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse exchangeInject(String httpNode, byte[] ownerAddress, + Integer exchangeId, String tokenId, Long quant, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/exchangeinject"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("exchange_id", exchangeId); + userBaseObj2.addProperty("token_id", str2hex(tokenId)); + userBaseObj2.addProperty("quant", quant); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse exchangeWithdraw(String httpNode, byte[] ownerAddress, + Integer exchangeId, String tokenId, Long quant, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/exchangewithdraw"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("exchange_id", exchangeId); + userBaseObj2.addProperty("token_id", str2hex(tokenId)); + userBaseObj2.addProperty("quant", quant); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse exchangeTransaction(String httpNode, byte[] ownerAddress, + Integer exchangeId, String tokenId, Long quant, Long expected, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/exchangetransaction"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("exchange_id", exchangeId); + userBaseObj2.addProperty("token_id", str2hex(tokenId)); + userBaseObj2.addProperty("quant", quant); + userBaseObj2.addProperty("expected", expected); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse assetIssue(String httpNode, byte[] ownerAddress, String name, + String abbr, Long totalSupply, Integer trxNum, Integer num, Long startTime, Long endTime, + Integer voteScore, Integer precision, String description, String url, Long freeAssetNetLimit, + Long publicFreeAssetNetLimit, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createassetissue"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("name", str2hex(name)); + userBaseObj2.addProperty("abbr", str2hex(abbr)); + userBaseObj2.addProperty("total_supply", totalSupply); + userBaseObj2.addProperty("trx_num", trxNum); + userBaseObj2.addProperty("num", num); + userBaseObj2.addProperty("precision", precision); + userBaseObj2.addProperty("start_time", startTime); + userBaseObj2.addProperty("end_time", endTime); + userBaseObj2.addProperty("vote_score", voteScore); + userBaseObj2.addProperty("description", str2hex(description)); + userBaseObj2.addProperty("url", str2hex(url)); + userBaseObj2.addProperty("free_asset_net_limit", freeAssetNetLimit); + userBaseObj2.addProperty("public_free_asset_net_limit", publicFreeAssetNetLimit); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse transferAsset(String httpNode, byte[] ownerAddress, byte[] toAddress, + String assetIssueById, Long amount, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/transferasset"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("asset_name", str2hex(assetIssueById)); + userBaseObj2.addProperty("amount", amount); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse deployContract(String httpNode, String name, String abi, + String bytecode, Long bandwidthLimit, Long feeLimit, Integer consumeUserResourcePercent, + Long originEnergyLimit, Long callValue, Integer tokenId, Long tokenValue, byte[] ownerAddress, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/deploycontract"; + JsonObject userBaseObj2 = new JsonObject(); + //userBaseObj2.addProperty("name", str2hex(name)); + userBaseObj2.addProperty("name", name); + userBaseObj2.addProperty("abi", abi); + userBaseObj2.addProperty("bytecode", bytecode); + userBaseObj2.addProperty("bandwidth_limit", bandwidthLimit); + userBaseObj2.addProperty("fee_limit", feeLimit); + userBaseObj2.addProperty("consume_user_resource_percent", consumeUserResourcePercent); + userBaseObj2.addProperty("origin_energy_limit", originEnergyLimit); + userBaseObj2.addProperty("call_value", callValue); + userBaseObj2.addProperty("token_id", tokenId); + userBaseObj2.addProperty("tokenValue", tokenValue); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static String deployContractGetTxid(String httpNode, String name, String abi, + String bytecode, Long bandwidthLimit, Long feeLimit, Integer consumeUserResourcePercent, + Long originEnergyLimit, Long callValue, Integer tokenId, Long tokenValue, byte[] ownerAddress, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/deploycontract"; + JsonObject userBaseObj2 = new JsonObject(); + //userBaseObj2.addProperty("name", str2hex(name)); + userBaseObj2.addProperty("name", name); + userBaseObj2.addProperty("abi", abi); + userBaseObj2.addProperty("bytecode", bytecode); + userBaseObj2.addProperty("bandwidth_limit", bandwidthLimit); + userBaseObj2.addProperty("fee_limit", feeLimit); + userBaseObj2.addProperty("consume_user_resource_percent", consumeUserResourcePercent); + userBaseObj2.addProperty("origin_energy_limit", originEnergyLimit); + userBaseObj2.addProperty("call_value", callValue); + userBaseObj2.addProperty("token_id", tokenId); + userBaseObj2.addProperty("call_token_value", tokenValue); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + + logger.info(userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseStringContent(transactionString); + return responseContent.getString("txID"); + } + + /** + * constructor. + */ + public static HttpResponse deployContractGetTxidWithTooBigLong(String httpNode, String name, + String abi, String bytecode, Long bandwidthLimit, Long feeLimit, + Integer consumeUserResourcePercent, Long originEnergyLimit, Long callValue, Integer tokenId, + Long tokenValue, byte[] ownerAddress, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/deploycontract"; + + String text = "{\"call_token_value\": 10000000e100000000}"; + JSONObject jsonObject = JSONObject.parseObject(text); + logger.info("jsonObject: " + jsonObject.toString()); + jsonObject.put("name", name); + jsonObject.put("abi", abi); + jsonObject.put("bytecode", bytecode); + jsonObject.put("bandwidth_limit", bandwidthLimit); + jsonObject.put("fee_limit", feeLimit); + jsonObject.put("consume_user_resource_percent", consumeUserResourcePercent); + jsonObject.put("origin_energy_limit", originEnergyLimit); + jsonObject.put("call_value", callValue); + jsonObject.put("token_id", tokenId); + jsonObject.put("owner_address", ByteArray.toHexString(ownerAddress)); + + logger.info(jsonObject.toString()); + response = createConnect1(requestUrl, jsonObject); /* transactionString = EntityUtils.toString(response.getEntity()); logger.info(transactionString); transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); logger.info(transactionSignString); response = broadcastTransaction(httpNode, transactionSignString);*/ - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static String triggerContractGetTxid(String httpNode, byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter, Long feeLimit, - Long callValue, Integer tokenId, Long tokenValue, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/triggersmartcontract"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("contract_address", contractAddress); - userBaseObj2.addProperty("function_selector", functionSelector); - userBaseObj2.addProperty("parameter", parameter); - userBaseObj2.addProperty("fee_limit", feeLimit); - userBaseObj2.addProperty("call_value", callValue); - userBaseObj2.addProperty("token_id", tokenId); - userBaseObj2.addProperty("call_token_value", tokenValue); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static String triggerContractGetTxid(String httpNode, byte[] ownerAddress, + String contractAddress, String functionSelector, String parameter, Long feeLimit, + Long callValue, Integer tokenId, Long tokenValue, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/triggersmartcontract"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("function_selector", functionSelector); + userBaseObj2.addProperty("parameter", parameter); + userBaseObj2.addProperty("fee_limit", feeLimit); + userBaseObj2.addProperty("call_value", callValue); + userBaseObj2.addProperty("token_id", tokenId); + userBaseObj2.addProperty("call_token_value", tokenValue); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + + transactionSignString = gettransactionsign(httpNode, + parseStringContent(transactionString).getString("transaction"), fromKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseStringContent(transactionSignString); + return responseContent.getString("txID"); + } + + + /** + * constructor. + */ + public static String triggerContractGetTxidWithVisibleTrue(String httpNode, String ownerAddress, + String contractAddress, String functionSelector, String parameter, Long feeLimit, + Long callValue, Integer tokenId, Long tokenValue, String fromKey) { + return triggerContractGetTxidWithVisibleTrue(httpNode, "", ownerAddress, + contractAddress, functionSelector, parameter, feeLimit, callValue, tokenId, tokenValue, + fromKey); + + } + + /** + * constructor. + */ + public static String triggerContractGetTxidWithVisibleTrue(String httpNode, + String anotherHttpNode, + String ownerAddress, + String contractAddress, String functionSelector, String parameter, Long feeLimit, + Long callValue, Integer tokenId, Long tokenValue, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/triggersmartcontract"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ownerAddress); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("function_selector", functionSelector); + userBaseObj2.addProperty("parameter", parameter); + userBaseObj2.addProperty("fee_limit", feeLimit); + userBaseObj2.addProperty("call_value", callValue); + userBaseObj2.addProperty("token_id", tokenId); + userBaseObj2.addProperty("call_token_value", tokenValue); + userBaseObj2.addProperty("visible", true); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + + transactionSignString = gettransactionsign(httpNode, + parseStringContent(transactionString).getString("transaction"), fromKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + if (!anotherHttpNode.isEmpty()) { + broadcastTransaction(anotherHttpNode, transactionSignString); + } + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseStringContent(transactionSignString); + return responseContent.getString("txID"); + } + + + /** + * constructor. + */ + public static HttpResponse triggerConstantContract(String httpNode, byte[] ownerAddress, + String contractAddress, String functionSelector, String parameter, Long feeLimit, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/triggerconstantcontract"; + JsonObject userBaseObj2 = new JsonObject(); + + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("function_selector", functionSelector); + userBaseObj2.addProperty("parameter", parameter); + userBaseObj2.addProperty("fee_limit", feeLimit); + + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse triggerConstantContract(String httpNode, byte[] ownerAddress, + String contractAddress, String functionSelector, String parameter) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/triggerconstantcontract"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("function_selector", functionSelector); + userBaseObj2.addProperty("parameter", parameter); + response = createConnect(requestUrl, userBaseObj2); + return response; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } - transactionSignString = gettransactionsign(httpNode, - parseStringContent(transactionString).getString("transaction"), fromKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseStringContent(transactionSignString); - return responseContent.getString("txID"); - } - - - /** - * constructor. - */ - public static String triggerContractGetTxidWithVisibleTrue(String httpNode, String ownerAddress, - String contractAddress, String functionSelector, String parameter, Long feeLimit, - Long callValue, Integer tokenId, Long tokenValue, String fromKey) { - return triggerContractGetTxidWithVisibleTrue(httpNode, "", ownerAddress, - contractAddress, functionSelector, parameter, feeLimit, callValue, tokenId, tokenValue, - fromKey); - - } - - /** - * constructor. - */ - public static String triggerContractGetTxidWithVisibleTrue(String httpNode, - String anotherHttpNode, - String ownerAddress, - String contractAddress, String functionSelector, String parameter, Long feeLimit, - Long callValue, Integer tokenId, Long tokenValue, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/triggersmartcontract"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ownerAddress); - userBaseObj2.addProperty("contract_address", contractAddress); - userBaseObj2.addProperty("function_selector", functionSelector); - userBaseObj2.addProperty("parameter", parameter); - userBaseObj2.addProperty("fee_limit", feeLimit); - userBaseObj2.addProperty("call_value", callValue); - userBaseObj2.addProperty("token_id", tokenId); - userBaseObj2.addProperty("call_token_value", tokenValue); - userBaseObj2.addProperty("visible", true); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); + /** + * constructor. + */ + public static HttpResponse triggerConstantContractFromSolidity(String httSoliditypNode, + byte[] ownerAddress, + String contractAddress, String functionSelector, String parameter) { + try { + final String requestUrl = + "http://" + httSoliditypNode + "/walletsolidity/triggerconstantcontract"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("function_selector", functionSelector); + userBaseObj2.addProperty("parameter", parameter); + response = createConnect(requestUrl, userBaseObj2); + return response; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } - transactionSignString = gettransactionsign(httpNode, - parseStringContent(transactionString).getString("transaction"), fromKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - if (!anotherHttpNode.isEmpty()) { - broadcastTransaction(anotherHttpNode, transactionSignString); - } - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseStringContent(transactionSignString); - return responseContent.getString("txID"); - } - - - /** - * constructor. - */ - public static HttpResponse triggerConstantContract(String httpNode, byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter, Long feeLimit, - String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/triggerconstantcontract"; - JsonObject userBaseObj2 = new JsonObject(); - - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("contract_address", contractAddress); - userBaseObj2.addProperty("function_selector", functionSelector); - userBaseObj2.addProperty("parameter", parameter); - userBaseObj2.addProperty("fee_limit", feeLimit); - - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse triggerConstantContract(String httpNode, byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/triggerconstantcontract"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("contract_address", contractAddress); - userBaseObj2.addProperty("function_selector", functionSelector); - userBaseObj2.addProperty("parameter", parameter); - response = createConnect(requestUrl, userBaseObj2); - return response; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static HttpResponse triggerConstantContractFromSolidity(String httSoliditypNode, - byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter) { - try { - final String requestUrl = - "http://" + httSoliditypNode + "/walletsolidity/triggerconstantcontract"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("contract_address", contractAddress); - userBaseObj2.addProperty("function_selector", functionSelector); - userBaseObj2.addProperty("parameter", parameter); - response = createConnect(requestUrl, userBaseObj2); - return response; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static HttpResponse triggerConstantContractFromPbft(String httpPbftNode, - byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter) { - try { - final String requestUrl = "http://" + httpPbftNode + "/walletpbft/triggerconstantcontract"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("contract_address", contractAddress); - userBaseObj2.addProperty("function_selector", functionSelector); - userBaseObj2.addProperty("parameter", parameter); - response = createConnect(requestUrl, userBaseObj2); - return response; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static HttpResponse participateAssetIssue(String httpNode, byte[] toAddress, - byte[] ownerAddress, String assetIssueById, Long amount, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/participateassetissue"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("asset_name", str2hex(assetIssueById)); - userBaseObj2.addProperty("amount", amount); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse updateAssetIssue(String httpNode, byte[] ownerAddress, - String description, String url, Long newLimit, Long newPublicLimit, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/updateasset"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("url", str2hex(url)); - userBaseObj2.addProperty("description", str2hex(description)); - userBaseObj2.addProperty("new_limit", newLimit); - userBaseObj2.addProperty("new_public_limit", newPublicLimit); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static Boolean verificationResult(HttpResponse response) { - if (response.getStatusLine().getStatusCode() != 200) { - return false; - } - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - //HttpMethed.printJsonContent(responseContent); - return Boolean.valueOf(responseContent.getString("result")).booleanValue(); - } - - /** - * constructor. - */ - public static HttpResponse freezeBalance(String httpNode, byte[] ownerAddress, Long frozenBalance, - Integer frozenDuration, Integer resourceCode, String fromKey) { - return freezeBalance(httpNode, ownerAddress, frozenBalance, frozenDuration, resourceCode, null, - fromKey); - } - - /** - * constructor. - */ - public static HttpResponse freezeBalance(String httpNode, byte[] ownerAddress, Long frozenBalance, - Integer frozenDuration, Integer resourceCode, byte[] receiverAddress, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/freezebalance"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("frozen_balance", frozenBalance); - userBaseObj2.addProperty("frozen_duration", frozenDuration); - if (resourceCode == 0) { - userBaseObj2.addProperty("resource", "BANDWIDTH"); - } - if (resourceCode == 1) { - userBaseObj2.addProperty("resource", "ENERGY"); - } - if (resourceCode == 2) { - userBaseObj2.addProperty("resource", "TRON_POWER"); - } - if (receiverAddress != null) { - userBaseObj2.addProperty("receiver_address", ByteArray.toHexString(receiverAddress)); - } - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse unFreezeBalance(String httpNode, byte[] ownerAddress, - Integer resourceCode, String fromKey) { - return unFreezeBalance(httpNode, ownerAddress, resourceCode, null, fromKey); - } - - /** - * constructor. - */ - public static HttpResponse unFreezeBalance(String httpNode, byte[] ownerAddress, - Integer resourceCode, byte[] receiverAddress, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/unfreezebalance"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - if (resourceCode == 0) { - userBaseObj2.addProperty("resource", "BANDWIDTH"); - } - if (resourceCode == 1) { - userBaseObj2.addProperty("resource", "ENERGY"); - } - if (resourceCode == 2) { - userBaseObj2.addProperty("resource", "TRON_POWER"); - } - if (receiverAddress != null) { - userBaseObj2.addProperty("receiver_address", ByteArray.toHexString(receiverAddress)); - } - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static String gettransactionsign(String httpNode, String transactionString, - String privateKey) { - try { - String requestUrl = "http://" + httpNode + "/wallet/gettransactionsign"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("transaction", transactionString); - userBaseObj2.addProperty("privateKey", privateKey); - response = createConnect(requestUrl, userBaseObj2); - transactionSignString = EntityUtils.toString(response.getEntity()); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return transactionSignString; - } - - /** - * constructor. - */ - public static HttpResponse broadcastTransaction(String httpNode, String transactionSignString) { - try { - String requestUrl = "http://" + httpNode + "/wallet/broadcasttransaction"; - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httppost = new HttpPost(requestUrl); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - if (transactionSignString != null) { - StringEntity entity = new StringEntity(transactionSignString, Charset.forName("UTF-8")); - entity.setContentEncoding("UTF-8"); - entity.setContentType("application/json"); - httppost.setEntity(entity); - } - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - - responseContent = HttpMethed.parseResponseContent(response); - Integer times = 0; - - while (times++ <= 10 && responseContent.getString("code") != null && responseContent - .getString("code").equalsIgnoreCase("SERVER_BUSY")) { - logger.info("retry num are " + times); - try { - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseResponseContent(response); - try { - Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - httppost.releaseConnection(); - return response; - } - - /** - * constructor. - */ - public static HttpResponse broadcasthex(String httpNode, String transactionHex) { - try { - String requestUrl = "http://" + httpNode + "/wallet/broadcasthex"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("transaction", transactionHex); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getAccountById(String httpNode, String accountId, Boolean visable) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getaccountbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("account_id", accountId); - userBaseObj2.addProperty("visible", visable); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAccountByIdFromSolidity(String httpSolidityNode, String accountId, - Boolean visable) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getaccountbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("account_id", accountId); - userBaseObj2.addProperty("visible", visable); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAccountByIdFromPbft(String httpSolidityNode, String accountId, - Boolean visable) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getaccountbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("account_id", accountId); - userBaseObj2.addProperty("visible", visable); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAccount(String httpNode, byte[] queryAddress) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getaccount"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static Long getAccountForResponse(String httpNode, byte[] queryAddress, Integer times) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getaccount"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); - Long duration = createConnectForResponse(requestUrl, userBaseObj2, times); - return duration; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return -1L; - } - } - - - /** - * constructor. - */ - public static HttpResponse getAccountFromSolidity(String httpSolidityNode, byte[] queryAddress) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getaccount"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); - response = createConnect(requestUrl, userBaseObj2); - logger.info(requestUrl); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAccountFromPbft(String httpSolidityNode, byte[] queryAddress) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getaccount"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getContract(String httpNode, String contractAddress) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getcontract"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", contractAddress); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getSignWeight(String httpNode, String transactionSignString) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getsignweight"; - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httppost = new HttpPost(requestUrl); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - if (transactionSignString != null) { - StringEntity entity = new StringEntity(transactionSignString, Charset.forName("UTF-8")); - entity.setContentEncoding("UTF-8"); - entity.setContentType("application/json"); - httppost.setEntity(entity); - } - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - //httppost.releaseConnection(); - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionApprovedList(String httpNode, - String transactionSignString) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getapprovedlist"; - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httppost = new HttpPost(requestUrl); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - if (transactionSignString != null) { - StringEntity entity = new StringEntity(transactionSignString, Charset.forName("UTF-8")); - entity.setContentEncoding("UTF-8"); - entity.setContentType("application/json"); - httppost.setEntity(entity); - } - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - //httppost.releaseConnection(); - return response; - } - - - /** - * constructor. - */ - public static HttpResponse listExchanges(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/listexchanges"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse listExchangesFromSolidity(String httpSolidityNode) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/listexchanges"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse listExchangesFromPbft(String httpSolidityNode) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/listexchanges"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse listNodes(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/listnodes"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getStatsInfo(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/monitor/getstatsinfo"; - response = createConnectForGet(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getNextmaintenanceTime(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnextmaintenancetime"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getChainParameter(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getchainparameters"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getNodeInfo(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnodeinfo"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse listwitnesses(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/listwitnesses"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse listwitnessesFromSolidity(String httpSolidityNode) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/listwitnesses"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse listwitnessesFromPbft(String httpSolidityNode) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/listwitnesses"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse listProposals(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/listproposals"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getExchangeById(String httpNode, Integer exchangeId) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getexchangebyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("id", exchangeId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getExchangeByIdFromSolidity(String httpSolidityNode, - Integer exchangeId) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getexchangebyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("id", exchangeId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getExchangeByIdFromPbft(String httpSolidityNode, Integer exchangeId) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getexchangebyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("id", exchangeId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getProposalById(String httpNode, Integer proposalId) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getproposalbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("id", proposalId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueListByName(String httpNode, String name) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getassetissuelistbyname"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", str2hex(name)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueListByNameFromSolidity(String httpSolidityNode, - String name) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuelistbyname"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", str2hex(name)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueListByNameFromPbft(String httpPbftNode, - String name) { - try { - String requestUrl = "http://" + httpPbftNode + "/walletpbft/getassetissuelistbyname"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", str2hex(name)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueById(String httpNode, String assetIssueId) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getassetissuebyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", assetIssueId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueByIdFromSolidity(String httpSolidityNode, - String assetIssueId) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuebyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", assetIssueId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueByIdFromPbft(String httpSolidityNode, - String assetIssueId) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getassetissuebyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", assetIssueId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getTransactionById(String httpNode, String txid) { - try { - String requestUrl = "http://" + httpNode + "/wallet/gettransactionbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", txid); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static Long getTransactionByIdForResponse(String httpNode, String txid, Integer times) { - try { - String requestUrl = "http://" + httpNode + "/wallet/gettransactionbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", txid); - Long duration = createConnectForResponse(requestUrl, userBaseObj2, times); - return duration; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - - /** - * constructor. - */ - public static HttpResponse getTransactionByIdFromSolidity(String httpSolidityNode, String txid) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/gettransactionbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", txid); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionByIdFromPbft(String httpSolidityNode, String txid) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/gettransactionbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", txid); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getTransactionInfoById(String httpNode, String txid) { - return getTransactionInfoById(httpNode, txid, false); - } - - /** - * constructor. - */ - public static HttpResponse getTransactionInfoById(String httpNode, String txid, Boolean visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/gettransactioninfobyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", txid); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getTransactionInfoByIdFromSolidity(String httpSolidityNode, - String txid) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/gettransactioninfobyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", txid); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionInfoByIdFromPbft(String httpSolidityNode, String txid) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/gettransactioninfobyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", txid); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionInfoByBlocknum(String httpNode, long blocknum) { - try { - String requestUrl = "http://" + httpNode + "/wallet/gettransactioninfobyblocknum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blocknum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionInfoByBlocknumFromSolidity(String httpSolidityNode, - long blocknum) { - try { - String requestUrl = - "http://" + httpSolidityNode + "/walletsolidity/gettransactioninfobyblocknum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blocknum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionCountByBlocknumFromSolidity(String httpSolidityNode, - long blocknum) { - try { - String requestUrl = - "http://" + httpSolidityNode + "/walletsolidity/gettransactioncountbyblocknum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blocknum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionCountByBlocknumFromPbft(String httpSolidityNode, - long blocknum) { - try { - String requestUrl = - "http://" + httpSolidityNode + "/walletpbft/gettransactioncountbyblocknum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blocknum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getTransactionsFromThisFromSolidity(String httpSolidityNode, - byte[] fromAddress, long offset, long limit) { - try { - Map map1 = new HashMap(); - Map map = new HashMap(); - map1.put("address", ByteArray.toHexString(fromAddress)); - map.put("account", map1); - map.put("offset", offset); - map.put("limit", limit); - String requestUrl = "http://" + httpSolidityNode + "/walletextension/gettransactionsfromthis"; - String jsonStr = new Gson().toJson(map); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - response = createConnect(requestUrl, jsonObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionsToThisFromSolidity(String httpSolidityNode, - byte[] toAddress, long offset, long limit) { - try { - Map map1 = new HashMap(); - Map map = new HashMap(); - map1.put("address", ByteArray.toHexString(toAddress)); - map.put("account", map1); - map.put("offset", offset); - map.put("limit", limit); - String requestUrl = "http://" + httpSolidityNode + "/walletextension/gettransactionstothis"; - String jsonStr = new Gson().toJson(map); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - response = createConnect(requestUrl, jsonObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueByName(String httpNode, String name) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getassetissuebyname"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", str2hex(name)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getAssetIssueByNameFromSolidity(String httpSolidityNode, String name) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuebyname"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", str2hex(name)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueByNameFromPbft(String httpSolidityNode, String name) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getassetissuebyname"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", str2hex(name)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static Long getBalance(String httpNode, byte[] queryAddress) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getaccount"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseResponseContent(response); - //HttpMethed.printJsonContent(responseContent); - //httppost.releaseConnection(); - if (!responseContent.containsKey("balance")) { - return 0L; - } - return Long.parseLong(responseContent.get("balance").toString()); - } - - - /** - * constructor. - */ - public static HttpResponse getAccountNet(String httpNode, byte[] queryAddress) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getaccountnet"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAccountReource(String httpNode, byte[] queryAddress) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getaccountresource"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAccountBalance(String httpNode, - byte[] queryAddress, Integer blockNum, String blockHash) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getaccountbalance"; - JsonObject addressObj = new JsonObject(); - addressObj.addProperty("address", Base58.encode58Check(queryAddress)); - JsonObject blockObj = new JsonObject(); - blockObj.addProperty("hash", blockHash); - blockObj.addProperty("number", blockNum); - JsonObject accountBalanceObj = new JsonObject(); - accountBalanceObj.add("account_identifier", addressObj); - accountBalanceObj.add("block_identifier", blockObj); - accountBalanceObj.addProperty("visible", true); - logger.info(accountBalanceObj.toString()); - response = createConnect(requestUrl, accountBalanceObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBlockBalance(String httpNode, Integer blockNum, String blockHash) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getblockbalance"; - JsonObject blockObj = new JsonObject(); - blockObj.addProperty("hash", blockHash); - blockObj.addProperty("number", blockNum); - blockObj.addProperty("visible", true); - response = createConnect(requestUrl, blockObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static Long getBurnTrx(String httpNode) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getburntrx"; - JsonObject blockObj = new JsonObject(); - response = createConnect(requestUrl, blockObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseResponseContent(response); - return responseContent.getLong("burnTrxAmount"); - } - - /** - * constructor. - */ - public static Long getBurnTrxFromSolidity(String httpNode) { - try { - final String requestUrl = "http://" + httpNode + "/walletsolidity/getburntrx"; - JsonObject blockObj = new JsonObject(); - response = createConnect(requestUrl, blockObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseResponseContent(response); - return responseContent.getLong("burnTrxAmount"); - } - - /** - * constructor. - */ - public static Long getBurnTrxFromPbft(String httpNode) { - try { - final String requestUrl = "http://" + httpNode + "/walletpbft/getburntrx"; - JsonObject blockObj = new JsonObject(); - response = createConnect(requestUrl, blockObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseResponseContent(response); - return responseContent.getLong("burnTrxAmount"); - } - - - - - /** - * constructor. - */ - public static HttpResponse getNowBlock(String httpNode) { - return getNowBlock(httpNode, false); - } - - /** - * constructor. - */ - public static HttpResponse getNowBlock(String httpNode, Boolean visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static Long getNowBlockNum(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return parseResponseContent(response).getJSONObject("block_header").getJSONObject("raw_data") - .getLong("number"); - } - - /** - * constructor. - */ - public static Long getNowBlockNumOnSolidity(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/walletsolidity/getnowblock"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return parseResponseContent(response).getJSONObject("block_header").getJSONObject("raw_data") - .getLong("number"); - } - - - /** - * constructor. - */ - public static HttpResponse getNowBlockFromSolidity(String httpSolidityNode) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getnowblock"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getNowBlockFromPbft(String httpSolidityNode) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getnowblock"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static void waitToProduceOneBlock(String httpNode) { - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - Integer currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); - Integer nextBlockNum = 0; - Integer times = 0; - while (nextBlockNum <= currentBlockNum + 1 && times++ <= 10) { - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - responseContent = HttpMethed - .parseStringContent(responseContent.get("block_header").toString()); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); - try { - Thread.sleep(1200); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - /** - * constructor. - */ - public static void waitToProduceOneBlockFromSolidity(String httpNode, String httpSolidityNode) { - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - Integer currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); - Integer nextBlockNum = 0; - Integer times = 0; - while (nextBlockNum <= currentBlockNum && times++ < ((getWitnessNum() >= 27) - ? 18 : (getWitnessNum() * 70 / 100))) { - response = HttpMethed.getNowBlockFromSolidity(httpSolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - responseContent = HttpMethed - .parseStringContent(responseContent.get("block_header").toString()); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); - logger.info("currentBlockNum1:"+currentBlockNum); - logger.info("nextBlockNum:"+nextBlockNum); - try { - Thread.sleep(3500); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - /** - * constructor. - */ - public static void waitToProduceOneBlockFromPbft(String httpNode, String httpSolidityNode) { - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - Integer currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); - Integer nextBlockNum = 0; - Integer times = 0; - while (nextBlockNum <= currentBlockNum && times++ <= 3) { - response = HttpMethed.getNowBlockFromPbft(httpSolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - responseContent = HttpMethed - .parseStringContent(responseContent.get("block_header").toString()); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); - try { - Thread.sleep(3500); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - - /** - * constructor. - */ - public static HttpResponse getBlockByNum(String httpNode, Integer blockNUm) { - return getBlockByNum(httpNode, blockNUm, false); - } - - /** - * constructor. - */ - public static HttpResponse getBlockByNum(String httpNode, Integer blockNUm, Boolean visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getblockbynum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blockNUm); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static Long getBlockByNumForResponse(String httpNode, Integer blockNUm, Integer times) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getblockbynum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blockNUm); - Long duration = createConnectForResponse(requestUrl, userBaseObj2, times); - return duration; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return -1L; - } - } - - - /** - * constructor. - */ - public static HttpResponse getBlockByNumFromSolidity(String httpSolidityNode, Integer blockNum) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getblockbynum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blockNum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBlockByNumFromPbft(String httpSolidityNode, Integer blockNum) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getblockbynum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blockNum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getBlockByLimitNext(String httpNode, Integer startNum, - Integer endNum) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getblockbylimitnext"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("startNum", startNum); - userBaseObj2.addProperty("endNum", endNum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBlockByLimitNextFromSolidity(String httpNode, Integer startNum, - Integer endNum) { - try { - String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbylimitnext"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("startNum", startNum); - userBaseObj2.addProperty("endNum", endNum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBlockByLimitNextFromPbft(String httpNode, Integer startNum, - Integer endNum) { - try { - String requestUrl = "http://" + httpNode + "/walletpbft/getblockbylimitnext"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("startNum", startNum); - userBaseObj2.addProperty("endNum", endNum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getBlockByLastNum(String httpNode, Integer num) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getblockbylatestnum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", num); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBlockByLastNum2(String httpNode, Integer num) { - try { - String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbylatestnum2"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", num); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getBlockByLastNumFromSolidity(String httpNode, Integer num) { - try { - String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbylatestnum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", num); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBlockByLastNumFromPbft(String httpNode, Integer num) { - try { - String requestUrl = "http://" + httpNode + "/walletpbft/getblockbylatestnum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", num); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getBlockById(String httpNode, String blockId) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getblockbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", blockId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBlockByIdFromSolidity(String httpNode, String blockId) { - try { - String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", blockId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBlockByIdFromPbft(String httpNode, String blockId) { - try { - String requestUrl = "http://" + httpNode + "/walletpbft/getblockbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", blockId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getDelegatedResource(String httpNode, byte[] fromAddress, - byte[] toAddress) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getdelegatedresource"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("fromAddress", ByteArray.toHexString(fromAddress)); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getDelegatedResourceFromSolidity(String httpSolidityNode, - byte[] fromAddress, byte[] toAddress) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getdelegatedresource"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("fromAddress", ByteArray.toHexString(fromAddress)); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getDelegatedResourceFromPbft(String httpSolidityNode, - byte[] fromAddress, byte[] toAddress) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getdelegatedresource"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("fromAddress", ByteArray.toHexString(fromAddress)); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getDelegatedResourceAccountIndex(String httpNode, - byte[] queryAddress) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getdelegatedresourceaccountindex"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", ByteArray.toHexString(queryAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getDelegatedResourceAccountIndexFromSolidity(String httpSolidityNode, - byte[] queryAddress) { - try { - String requestUrl = - "http://" + httpSolidityNode + "/walletsolidity/getdelegatedresourceaccountindex"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", ByteArray.toHexString(queryAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getDelegatedResourceAccountIndexFromPbft(String httpSolidityNode, - byte[] queryAddress) { - try { - String requestUrl = - "http://" + httpSolidityNode + "/walletpbft/getdelegatedresourceaccountindex"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", ByteArray.toHexString(queryAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse createConnect(String url) { - return createConnect(url, null); - } - - /** - * constructor. - */ - public static HttpResponse createConnect(String url, JsonObject requestBody) { - try { - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httppost = new HttpPost(url); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - if (requestBody != null) { - StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); - entity.setContentEncoding("UTF-8"); - entity.setContentType("application/json"); - httppost.setEntity(entity); - } - - logger.info(httppost.toString()); - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse createConnectForGet(String url) { - try { - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - HttpGet httppost; - httppost = new HttpGet(url); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - - logger.info(httppost.toString()); - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse createConnectForShieldTrc20(String url, JSONObject requestBody) { - try { - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httppost = new HttpPost(url); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - if (requestBody != null) { - StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); - entity.setContentEncoding("UTF-8"); - entity.setContentType("application/json"); - httppost.setEntity(entity); - } - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static Long createConnectForResponse(String url, JsonObject requestBody, Integer times) { - try { - - Long start = 0L; - Long end = 0L; - Long duration = 0L; - while (times-- > 0) { - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httppost = new HttpPost(url); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - if (requestBody != null) { - StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); - entity.setContentEncoding("UTF-8"); - entity.setContentType("application/json"); - httppost.setEntity(entity); - } - - start = System.currentTimeMillis(); - response = httpClient.execute(httppost); - /* responseContent = HttpMethed.parseResponseContent(response); - logger.info(responseContent.toString());*/ - end = System.currentTimeMillis(); - duration = duration + end - start; + /** + * constructor. + */ + public static HttpResponse triggerConstantContractFromPbft(String httpPbftNode, + byte[] ownerAddress, + String contractAddress, String functionSelector, String parameter) { + try { + final String requestUrl = "http://" + httpPbftNode + "/walletpbft/triggerconstantcontract"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("function_selector", functionSelector); + userBaseObj2.addProperty("parameter", parameter); + response = createConnect(requestUrl, userBaseObj2); + return response; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** + * constructor. + */ + public static HttpResponse participateAssetIssue(String httpNode, byte[] toAddress, + byte[] ownerAddress, String assetIssueById, Long amount, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/participateassetissue"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("asset_name", str2hex(assetIssueById)); + userBaseObj2.addProperty("amount", amount); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse updateAssetIssue(String httpNode, byte[] ownerAddress, + String description, String url, Long newLimit, Long newPublicLimit, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/updateasset"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("url", str2hex(url)); + userBaseObj2.addProperty("description", str2hex(description)); + userBaseObj2.addProperty("new_limit", newLimit); + userBaseObj2.addProperty("new_public_limit", newPublicLimit); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static Boolean verificationResult(HttpResponse response) { + if (response.getStatusLine().getStatusCode() != 200) { + return false; + } + Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); + responseContent = HttpMethed.parseResponseContent(response); + //HttpMethed.printJsonContent(responseContent); + return Boolean.valueOf(responseContent.getString("result")).booleanValue(); + } + + /** + * constructor. + */ + public static HttpResponse freezeBalance(String httpNode, byte[] ownerAddress, Long frozenBalance, + Integer frozenDuration, Integer resourceCode, String fromKey) { + return freezeBalance(httpNode, ownerAddress, frozenBalance, frozenDuration, resourceCode, null, + fromKey); + } + + /** + * constructor. + */ + public static HttpResponse freezeBalance(String httpNode, byte[] ownerAddress, Long frozenBalance, + Integer frozenDuration, Integer resourceCode, byte[] receiverAddress, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/freezebalance"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("frozen_balance", frozenBalance); + userBaseObj2.addProperty("frozen_duration", frozenDuration); + if (resourceCode == 0) { + userBaseObj2.addProperty("resource", "BANDWIDTH"); + } + if (resourceCode == 1) { + userBaseObj2.addProperty("resource", "ENERGY"); + } + if (resourceCode == 2) { + userBaseObj2.addProperty("resource", "TRON_POWER"); + } + if (receiverAddress != null) { + userBaseObj2.addProperty("receiver_address", ByteArray.toHexString(receiverAddress)); + } + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse unFreezeBalance(String httpNode, byte[] ownerAddress, + Integer resourceCode, String fromKey) { + return unFreezeBalance(httpNode, ownerAddress, resourceCode, null, fromKey); + } + + /** + * constructor. + */ + public static HttpResponse unFreezeBalance(String httpNode, byte[] ownerAddress, + Integer resourceCode, byte[] receiverAddress, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/unfreezebalance"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + if (resourceCode == 0) { + userBaseObj2.addProperty("resource", "BANDWIDTH"); + } + if (resourceCode == 1) { + userBaseObj2.addProperty("resource", "ENERGY"); + } + if (resourceCode == 2) { + userBaseObj2.addProperty("resource", "TRON_POWER"); + } + if (receiverAddress != null) { + userBaseObj2.addProperty("receiver_address", ByteArray.toHexString(receiverAddress)); + } + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static String gettransactionsign(String httpNode, String transactionString, + String privateKey) { + try { + String requestUrl = "http://" + httpNode + "/wallet/gettransactionsign"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("transaction", transactionString); + userBaseObj2.addProperty("privateKey", privateKey); + response = createConnect(requestUrl, userBaseObj2); + transactionSignString = EntityUtils.toString(response.getEntity()); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return transactionSignString; + } + + /** + * constructor. + */ + public static HttpResponse broadcastTransaction(String httpNode, String transactionSignString) { + try { + String requestUrl = "http://" + httpNode + "/wallet/broadcasttransaction"; + httpClient.getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + httppost = new HttpPost(requestUrl); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + if (transactionSignString != null) { + StringEntity entity = new StringEntity(transactionSignString, Charset.forName("UTF-8")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httppost.setEntity(entity); + } + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + + responseContent = HttpMethed.parseResponseContent(response); + Integer times = 0; + + while (times++ <= 10 && responseContent.getString("code") != null && responseContent + .getString("code").equalsIgnoreCase("SERVER_BUSY")) { + logger.info("retry num are " + times); + try { + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseResponseContent(response); + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } httppost.releaseConnection(); - } - return duration; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return -1L; - } - } - - - /** - * constructor. - */ - public static HttpResponse createConnect1(String url, JSONObject requestBody) { - try { - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout * 10000); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout * 10000); - httppost = new HttpPost(url); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - if (requestBody != null) { - StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); - entity.setContentEncoding("UTF-8"); - entity.setContentType("application/json"); - httppost.setEntity(entity); - } - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getAssetissueList(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getassetissuelist"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static Long getAssetIssueValue(String httpNode, byte[] accountAddress, - String assetIssueId) { - response = HttpMethed.getAccount(httpNode, accountAddress); - responseContent = HttpMethed.parseResponseContent(response); - JSONArray assetV2 = responseContent.getJSONArray("assetV2"); - if (assetV2 != null && assetV2.size() > 0) { - for (int i = 0; i < assetV2.size(); i++) { - String assetString = assetV2.get(i).toString(); - logger.info("assetString:" + assetString); - String assetKey = HttpMethed.parseStringContent(assetString).getString("key"); - if (assetKey.equals(assetIssueId)) { - return HttpMethed.parseStringContent(assetString).getLong("value"); - } - } - } - return 0L; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueListFromSolidity(String httpSolidityNode) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuelist"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueListFromPbft(String httpSolidityNode) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getassetissuelist"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getPaginatedAssetissueList(String httpNode, Integer offset, - Integer limit) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getpaginatedassetissuelist"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("offset", offset); - userBaseObj2.addProperty("limit", limit); - userBaseObj2.addProperty("visible", "true"); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getPaginatedAssetissueListFromSolidity(String httpSolidityNode, - Integer offset, Integer limit) { - try { - String requestUrl = - "http://" + httpSolidityNode + "/walletsolidity/getpaginatedassetissuelist"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("offset", offset); - userBaseObj2.addProperty("limit", limit); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getPaginatedAssetissueListFromPbft(String httpSolidityNode, - Integer offset, Integer limit) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getpaginatedassetissuelist"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("offset", offset); - userBaseObj2.addProperty("limit", limit); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getPaginatedProposalList(String httpNode, Integer offset, - Integer limit) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getpaginatedproposallist"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("offset", offset); - userBaseObj2.addProperty("limit", limit); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getPaginatedExchangeList(String httpNode, Integer offset, - Integer limit) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getpaginatedexchangelist"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("offset", offset); - userBaseObj2.addProperty("limit", limit); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse updateSetting(String httpNode, byte[] ownerAddress, - String contractAddress, Integer consumeUserResourcePercent, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/updatesetting"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("contract_address", contractAddress); - userBaseObj2.addProperty("consume_user_resource_percent", consumeUserResourcePercent); - logger.info(userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse updateEnergyLimit(String httpNode, byte[] ownerAddress, - String contractAddress, Integer originEnergyLimit, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/updateenergylimit"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("contract_address", contractAddress); - userBaseObj2.addProperty("origin_energy_limit", originEnergyLimit); - logger.info(userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse createAddress(String httpNode, String value) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createaddress"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", str2hex(value)); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse generateAddress(String httpNode) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/generateaddress"; - JsonObject userBaseObj2 = new JsonObject(); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionCountByBlocknum(String httpNode, long blocknum) { - try { - String requestUrl = - "http://" + httpNode + "/wallet/gettransactioncountbyblocknum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blocknum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse validateAddress(String httpNode, String address) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/validateaddress"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", address); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse easyTransfer(String httpNode, String value, byte[] toAddress, - Long amount) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/easytransfer"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("passPhrase", str2hex(value)); - userBaseObj2.addProperty("amount", amount); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse easyTransferByPrivate(String httpNode, String privateKey, - byte[] toAddress, Long amount) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/easytransferbyprivate"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("privateKey", privateKey); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("amount", amount); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse easyTransferAsset(String httpNode, String value, byte[] toAddress, - Long amount, String assetId) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/easytransferasset"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("passPhrase", str2hex(value)); - userBaseObj2.addProperty("amount", amount); - userBaseObj2.addProperty("assetId", assetId); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse easyTransferAssetByPrivate(String httpNode, String privateKey, - byte[] toAddress, Long amount, String assetId) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/easytransferassetbyprivate"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("privateKey", privateKey); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("amount", amount); - userBaseObj2.addProperty("assetId", assetId); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getContractInfo(String httpNode, String contractAddress) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getcontractinfo"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", contractAddress); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static void disConnect() { - httppost.releaseConnection(); - } - - /** - * constructor. - */ - public static JSONObject parseResponseContent(HttpResponse response) { - try { - String result = EntityUtils.toString(response.getEntity()); - StringEntity entity = new StringEntity(result, Charset.forName("UTF-8")); - response.setEntity(entity); - JSONObject obj = JSONObject.parseObject(result); - return obj; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /** - * constructor. - */ - public static List parseResponseContentArray(HttpResponse response) { - try { - String result = EntityUtils.toString(response.getEntity()); - StringEntity entity = new StringEntity(result, Charset.forName("UTF-8")); - response.setEntity(entity); - List list = new ArrayList(); - JSONArray objects = JSONArray.parseArray(result); - for (int i = 0; i < objects.size(); i++) { - list.add(objects.getJSONObject(i)); - } - return list; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /** - * constructor. - */ - public static JSONObject parseStringContent(String content) { - try { - JSONObject obj = JSONObject.parseObject(content); - return obj; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /** - * constructor. - */ - public static void printJsonContent(JSONObject responseContent) { - logger.info("----------------------------Print JSON Start---------------------------"); - for (String str : responseContent.keySet()) { - logger.info(str + ":" + responseContent.get(str)); - } - logger.info("JSON content size are: " + responseContent.size()); - logger.info("----------------------------Print JSON End-----------------------------"); - } - - /** - * constructor. - */ - public static String str2hex(String str) { - char[] chars = "0123456789ABCDEF".toCharArray(); - StringBuilder sb = new StringBuilder(); - byte[] bs = str.getBytes(); - int bit; - for (int i = 0; i < bs.length; i++) { - bit = (bs[i] & 0x0f0) >> 4; - sb.append(chars[bit]); - bit = bs[i] & 0x0f; - sb.append(chars[bit]); - // sb.append(' '); - } - return sb.toString().trim(); - } - - - /** - * constructor. - */ - public static HttpResponse clearABiGetTxid(String httpNode, byte[] ownerAddress, - String contractAddress, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/clearabi"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("contract_address", contractAddress); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); + return response; + } + + /** + * constructor. + */ + public static HttpResponse broadcasthex(String httpNode, String transactionHex) { + try { + String requestUrl = "http://" + httpNode + "/wallet/broadcasthex"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("transaction", transactionHex); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getAccountById(String httpNode, String accountId, Boolean visable) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getaccountbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("account_id", accountId); + userBaseObj2.addProperty("visible", visable); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getAccountByIdFromSolidity(String httpSolidityNode, String accountId, + Boolean visable) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getaccountbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("account_id", accountId); + userBaseObj2.addProperty("visible", visable); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getAccountByIdFromPbft(String httpSolidityNode, String accountId, + Boolean visable) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getaccountbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("account_id", accountId); + userBaseObj2.addProperty("visible", visable); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getAccount(String httpNode, byte[] queryAddress) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getaccount"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static Long getAccountForResponse(String httpNode, byte[] queryAddress, Integer times) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getaccount"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); + Long duration = createConnectForResponse(requestUrl, userBaseObj2, times); + return duration; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return -1L; + } + } - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - - - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static Optional generateShieldAddress(String httpnode) { - ShieldAddressInfo addressInfo = new ShieldAddressInfo(); - String sk; - String d; - String ask; - String nsk; - String ovk; - String ak; - String nk; - String ivk; - String pkD; - try { - response = HttpMethed.getSpendingKey(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - sk = responseContent.getString("value"); - - response = HttpMethed.getDiversifier(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - d = responseContent.getString("d"); - - response = HttpMethed.getExpandedSpendingKey(httpnode, sk); - responseContent = HttpMethed.parseResponseContent(response); - ask = responseContent.getString("ask"); - nsk = responseContent.getString("nsk"); - ovk = responseContent.getString("ovk"); - - response = HttpMethed.getAkFromAsk(httpnode, ask); - responseContent = HttpMethed.parseResponseContent(response); - ak = responseContent.getString("value"); - - response = HttpMethed.getNkFromNsk(httpnode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - nk = responseContent.getString("value"); - - response = HttpMethed.getIncomingViewingKey(httpnode, ak, nk); - responseContent = HttpMethed.parseResponseContent(response); - ivk = responseContent.getString("ivk"); - - response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d); - responseContent = HttpMethed.parseResponseContent(response); - pkD = responseContent.getString("pkD"); - - addressInfo.setSk(ByteArray.fromHexString(sk)); - addressInfo.setD(new DiversifierT(ByteArray.fromHexString(d))); - addressInfo.setIvk(ByteArray.fromHexString(ivk)); - addressInfo.setOvk(ByteArray.fromHexString(ovk)); - addressInfo.setPkD(ByteArray.fromHexString(pkD)); - logger.info("sk:" + sk); - - if (addressInfo.validateCheck()) { - return Optional.of(addressInfo); - } - } catch (Exception e) { - e.printStackTrace(); - } - - return Optional.empty(); - } - - /** - * constructor. - */ - public static List addShieldOutputList(String httpNode, - List shieldOutList, String shieldToAddress, String toAmountString, - String menoString) { - String shieldAddress = shieldToAddress; - String amountString = toAmountString; - if (menoString.equals("null")) { - menoString = ""; - } - long shieldAmount = 0; - if (!StringUtil.isNullOrEmpty(amountString)) { - shieldAmount = Long.valueOf(amountString); - } - - GrpcAPI.Note.Builder noteBuild = GrpcAPI.Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setValue(shieldAmount); - - response = HttpMethed.getRcm(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - String rcm = responseContent.getString("value"); - - noteBuild.setRcm(ByteString.copyFrom(rcm.getBytes())); - noteBuild.setMemo(ByteString.copyFrom(menoString.getBytes())); - shieldOutList.add(noteBuild.build()); - return shieldOutList; - } - - /** - * constructor. - */ - public static HttpResponse getSpendingKey(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getspendingkey"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getDiversifier(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getdiversifier"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getRcm(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getrcm"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getExpandedSpendingKey(String httpNode, String spendingKey) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getexpandedspendingkey"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", spendingKey); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAkFromAsk(String httpNode, String ask) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getakfromask"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", ask); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getNkFromNsk(String httpNode, String nsk) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnkfromnsk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", nsk); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getIncomingViewingKey(String httpNode, String ak, String nk) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getincomingviewingkey"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("ak", ak); - userBaseObj2.addProperty("nk", nk); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getNewShieldedAddress(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnewshieldedaddress"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getZenPaymentAddress(String httpNode, String ivk, String d) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getzenpaymentaddress"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("ivk", ivk); - userBaseObj2.addProperty("d", d); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMerkleTreeVoucherInfo(String httpNode, String hash, Integer index, - int blockNum) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getmerkletreevoucherinfo"; - JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); - jsonObjectWarp.put("out_points", - Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) - .put("block_num", blockNum); - String jsonStr = jsonObjectWarp.toJSONString(); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - logger.info("jsonObj:" + jsonObj.toString()); - response = createConnect(requestUrl, jsonObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMerkleTreeVoucherInfoFromSolidity(String httpSolidityNode, - String hash, Integer index, int blockNum) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmerkletreevoucherinfo"; - JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); - jsonObjectWarp.put("out_points", - Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) - .put("block_num", blockNum); - String jsonStr = jsonObjectWarp.toJSONString(); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - logger.info("jsonObj:" + jsonObj.toString()); - response = createConnect(requestUrl, jsonObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMerkleTreeVoucherInfoFromPbft(String httpSolidityNode, String hash, - Integer index, int blockNum) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getmerkletreevoucherinfo"; - JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); - jsonObjectWarp.put("out_points", - Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) - .put("block_num", blockNum); - String jsonStr = jsonObjectWarp.toJSONString(); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - logger.info("jsonObj:" + jsonObj.toString()); - response = createConnect(requestUrl, jsonObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse sendShieldCoin(String httpNode, byte[] publicZenTokenOwnerAddress, - long fromAmount, ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx, - List shieldOutputList, byte[] publicZenTokenToAddress, long toAmount, - String zenTokenOwnerKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createshieldedtransaction"; - - Map map = new HashMap(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - map.put("transparent_from_address", ByteArray.toHexString(publicZenTokenOwnerAddress)); - map.put("from_amount", fromAmount); - } - if (shieldAddressInfo != null) { - HttpResponse expandedSpendingKey = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.getSk())); - responseContent = HttpMethed.parseResponseContent(expandedSpendingKey); - HttpMethed.printJsonContent(responseContent); - String ovk = responseContent.getString("ovk"); - map.put("ask", responseContent.getString("ask")); - map.put("nsk", responseContent.getString("nsk")); - map.put("ovk", ovk); - - response = HttpMethed - .getMerkleTreeVoucherInfo(httpNode, noteTx.getTrxId(), noteTx.getIndex(), 1); + /** + * constructor. + */ + public static HttpResponse getAccountFromSolidity(String httpSolidityNode, byte[] queryAddress) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getaccount"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); + response = createConnect(requestUrl, userBaseObj2); + logger.info(requestUrl); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getAccountFromPbft(String httpSolidityNode, byte[] queryAddress) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getaccount"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getContract(String httpNode, String contractAddress) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getcontract"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", contractAddress); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getSignWeight(String httpNode, String transactionSignString) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getsignweight"; + httpClient.getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + httppost = new HttpPost(requestUrl); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + if (transactionSignString != null) { + StringEntity entity = new StringEntity(transactionSignString, Charset.forName("UTF-8")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httppost.setEntity(entity); + } + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + //httppost.releaseConnection(); + return response; + } + + /** + * constructor. + */ + public static HttpResponse getTransactionApprovedList(String httpNode, + String transactionSignString) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getapprovedlist"; + httpClient.getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + httppost = new HttpPost(requestUrl); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + if (transactionSignString != null) { + StringEntity entity = new StringEntity(transactionSignString, Charset.forName("UTF-8")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httppost.setEntity(entity); + } + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + //httppost.releaseConnection(); + return response; + } + + + /** + * constructor. + */ + public static HttpResponse listExchanges(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/listexchanges"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse listExchangesFromSolidity(String httpSolidityNode) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/listexchanges"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse listExchangesFromPbft(String httpSolidityNode) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/listexchanges"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse listNodes(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/listnodes"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getStatsInfo(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/monitor/getstatsinfo"; + response = createConnectForGet(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getNextmaintenanceTime(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getnextmaintenancetime"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getChainParameter(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getchainparameters"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getNodeInfo(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getnodeinfo"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse listwitnesses(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/listwitnesses"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse listwitnessesFromSolidity(String httpSolidityNode) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/listwitnesses"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse listwitnessesFromPbft(String httpSolidityNode) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/listwitnesses"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse listProposals(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/listproposals"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getExchangeById(String httpNode, Integer exchangeId) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getexchangebyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("id", exchangeId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getExchangeByIdFromSolidity(String httpSolidityNode, + Integer exchangeId) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getexchangebyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("id", exchangeId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getExchangeByIdFromPbft(String httpSolidityNode, Integer exchangeId) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getexchangebyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("id", exchangeId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getProposalById(String httpNode, Integer proposalId) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getproposalbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("id", proposalId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getAssetIssueListByName(String httpNode, String name) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getassetissuelistbyname"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", str2hex(name)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getAssetIssueListByNameFromSolidity(String httpSolidityNode, + String name) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuelistbyname"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", str2hex(name)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getAssetIssueListByNameFromPbft(String httpPbftNode, + String name) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getassetissuelistbyname"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", str2hex(name)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getAssetIssueById(String httpNode, String assetIssueId) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getassetissuebyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", assetIssueId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getAssetIssueByIdFromSolidity(String httpSolidityNode, + String assetIssueId) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuebyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", assetIssueId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getAssetIssueByIdFromPbft(String httpSolidityNode, + String assetIssueId) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getassetissuebyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", assetIssueId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getTransactionById(String httpNode, String txid) { + try { + String requestUrl = "http://" + httpNode + "/wallet/gettransactionbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", txid); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static Long getTransactionByIdForResponse(String httpNode, String txid, Integer times) { + try { + String requestUrl = "http://" + httpNode + "/wallet/gettransactionbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", txid); + Long duration = createConnectForResponse(requestUrl, userBaseObj2, times); + return duration; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + + /** + * constructor. + */ + public static HttpResponse getTransactionByIdFromSolidity(String httpSolidityNode, String txid) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/gettransactionbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", txid); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getTransactionByIdFromPbft(String httpSolidityNode, String txid) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/gettransactionbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", txid); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getTransactionInfoById(String httpNode, String txid) { + return getTransactionInfoById(httpNode, txid, false); + } + + /** + * constructor. + */ + public static HttpResponse getTransactionInfoById(String httpNode, String txid, Boolean visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/gettransactioninfobyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", txid); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getTransactionInfoByIdFromSolidity(String httpSolidityNode, + String txid) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/gettransactioninfobyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", txid); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getTransactionInfoByIdFromPbft(String httpSolidityNode, String txid) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/gettransactioninfobyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", txid); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getTransactionInfoByBlocknum(String httpNode, long blocknum) { + try { + String requestUrl = "http://" + httpNode + "/wallet/gettransactioninfobyblocknum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blocknum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getTransactionInfoByBlocknumFromSolidity(String httpSolidityNode, + long blocknum) { + try { + String requestUrl = + "http://" + httpSolidityNode + "/walletsolidity/gettransactioninfobyblocknum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blocknum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getTransactionCountByBlocknumFromSolidity(String httpSolidityNode, + long blocknum) { + try { + String requestUrl = + "http://" + httpSolidityNode + "/walletsolidity/gettransactioncountbyblocknum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blocknum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getTransactionCountByBlocknumFromPbft(String httpSolidityNode, + long blocknum) { + try { + String requestUrl = + "http://" + httpSolidityNode + "/walletpbft/gettransactioncountbyblocknum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blocknum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getTransactionsFromThisFromSolidity(String httpSolidityNode, + byte[] fromAddress, long offset, long limit) { + try { + Map map1 = new HashMap(); + Map map = new HashMap(); + map1.put("address", ByteArray.toHexString(fromAddress)); + map.put("account", map1); + map.put("offset", offset); + map.put("limit", limit); + String requestUrl = "http://" + httpSolidityNode + "/walletextension/gettransactionsfromthis"; + String jsonStr = new Gson().toJson(map); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + response = createConnect(requestUrl, jsonObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getTransactionsToThisFromSolidity(String httpSolidityNode, + byte[] toAddress, long offset, long limit) { + try { + Map map1 = new HashMap(); + Map map = new HashMap(); + map1.put("address", ByteArray.toHexString(toAddress)); + map.put("account", map1); + map.put("offset", offset); + map.put("limit", limit); + String requestUrl = "http://" + httpSolidityNode + "/walletextension/gettransactionstothis"; + String jsonStr = new Gson().toJson(map); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + response = createConnect(requestUrl, jsonObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getAssetIssueByName(String httpNode, String name) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getassetissuebyname"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", str2hex(name)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getAssetIssueByNameFromSolidity(String httpSolidityNode, String name) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuebyname"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", str2hex(name)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getAssetIssueByNameFromPbft(String httpSolidityNode, String name) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getassetissuebyname"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", str2hex(name)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static Long getBalance(String httpNode, byte[] queryAddress) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getaccount"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } responseContent = HttpMethed.parseResponseContent(response); - JSONArray vouchers = responseContent.getJSONArray("vouchers"); - JSONArray paths = responseContent.getJSONArray("paths"); - - List shieldedSpends = Lists.newArrayList(new JSONObjectWarp().put("note", - new JSONObjectWarp().put("value", noteTx.getValue()) - .put("payment_address", noteTx.getPaymentAddress()) - .put("rcm", ByteArray.toHexString(noteTx.getR())) - .put("memo", ByteArray.toHexString(noteTx.getMemo()))) - .put("alpha", ByteArray.toHexString(org.tron.core.zen.note.Note.generateR())) - .put("voucher", Lists.newArrayList(vouchers)).put("path", Lists.newArrayList(paths))); - - map.put("shielded_spends", shieldedSpends); - } else { - map.put("ovk", "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - } - - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - map.put("transparent_to_address", ByteArray.toHexString(publicZenTokenToAddress)); - map.put("to_amount", toAmount); - } - - if (shieldOutputList.size() > 0) { - ArrayList noteList = new ArrayList<>(); - for (int i = 0; i < shieldOutputList.size(); ++i) { - - Map noteInfo = new HashMap(); - noteInfo.put("value", shieldOutputList.get(i).getValue()); - noteInfo.put("payment_address", shieldOutputList.get(i).getPaymentAddress()); - noteInfo.put("rcm", shieldOutputList.get(i).getRcm().toStringUtf8()); - noteInfo.put("memo", - ByteArray.toHexString(shieldOutputList.get(i).getMemo().toStringUtf8().getBytes())); - final Map note = new HashMap(); - note.put("note", noteInfo); - noteList.add(note); - } - map.put("shielded_receives", noteList); - } - - String jsonStr = new Gson().toJson(map); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - logger.info("jsonObj:" + jsonObj.toString()); - response = createConnect(requestUrl, jsonObj); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - transactionSignString = gettransactionsign(httpNode, transactionString, zenTokenOwnerKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } else { - response = broadcastTransaction(httpNode, transactionString); - } - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static Boolean getSpendResult(String httpNode, ShieldAddressInfo shieldAddressInfo, - ShieldNoteInfo noteTx) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/isspend"; - - response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); - responseContent = HttpMethed.parseResponseContent(response); - String ask = responseContent.getString("ask"); - response = HttpMethed.getAkFromAsk(httpNode, ask); - responseContent = HttpMethed.parseResponseContent(response); - JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); - jsonObjectWarp.put("ak", responseContent.getString("value")); - - String nsk = responseContent.getString("nsk"); - response = HttpMethed.getNkFromNsk(httpNode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - jsonObjectWarp.put("nk", responseContent.getString("value")); - - jsonObjectWarp.put("note", new JSONObjectWarp().put("value", noteTx.getValue()) - .put("payment_address", noteTx.getPaymentAddress()) - .put("rcm", ByteArray.toHexString(noteTx.getR())) - .put("memo", ByteArray.toHexString(noteTx.getMemo()))).put("txid", noteTx.getTrxId()); - - String jsonStr = jsonObjectWarp.toJSONString(); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - logger.info("jsonObj:" + jsonObj.toString()); - HttpMethed.response = createConnect(requestUrl, jsonObj); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String jsonString = responseContent.toJSONString(); - if (jsonString.contains("result") && (responseContent.getString("result").equals("true") - && responseContent.getString("message").equals("Input note has been spent"))) { - return Boolean.TRUE; - } else { - return Boolean.FALSE; - } - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static Boolean getSpendResultFromSolidity(String httpNode, String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx) { - try { - final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/isspend"; - - response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); - responseContent = HttpMethed.parseResponseContent(response); - String ask = responseContent.getString("ask"); - response = HttpMethed.getAkFromAsk(httpNode, ask); - responseContent = HttpMethed.parseResponseContent(response); - JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); - jsonObjectWarp.put("ak", responseContent.getString("value")); - - String nsk = responseContent.getString("nsk"); - response = HttpMethed.getNkFromNsk(httpNode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - jsonObjectWarp.put("nk", responseContent.getString("value")); - - jsonObjectWarp.put("note", new JSONObjectWarp().put("value", noteTx.getValue()) - .put("payment_address", noteTx.getPaymentAddress()) - .put("rcm", ByteArray.toHexString(noteTx.getR())) - .put("memo", ByteArray.toHexString(noteTx.getMemo()))).put("txid", noteTx.getTrxId()); - - String jsonStr = jsonObjectWarp.toJSONString(); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - logger.info("jsonObj:" + jsonObj.toString()); - HttpMethed.response = createConnect(requestUrl, jsonObj); - responseContent = HttpMethed.parseResponseContent(response); - - HttpMethed.printJsonContent(responseContent); - String jsonString = responseContent.toJSONString(); - if (jsonString.contains("result") && (responseContent.getString("result").equals("true") - && responseContent.getString("message").equals("Input note has been spent"))) { - return Boolean.TRUE; - } else { - return Boolean.FALSE; - } - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static Boolean getSpendResultFromPbft(String httpNode, String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx) { - try { - final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/isspend"; - final JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); - - response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); - responseContent = HttpMethed.parseResponseContent(response); - String ask = responseContent.getString("ask"); - final String nsk = responseContent.getString("nsk"); - response = HttpMethed.getAkFromAsk(httpNode, ask); - responseContent = HttpMethed.parseResponseContent(response); - jsonObjectWarp.put("ak", responseContent.getString("value")); - response = HttpMethed.getNkFromNsk(httpNode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - jsonObjectWarp.put("nk", responseContent.getString("value")); - jsonObjectWarp.put("note", new JSONObjectWarp().put("value", noteTx.getValue()) - .put("payment_address", noteTx.getPaymentAddress()) - .put("rcm", ByteArray.toHexString(noteTx.getR())) - .put("memo", ByteArray.toHexString(noteTx.getMemo()))).put("txid", noteTx.getTrxId()); - String jsonStr = jsonObjectWarp.toJSONString(); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - logger.info("jsonObj:" + jsonObj.toString()); - HttpMethed.response = createConnect(requestUrl, jsonObj); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String jsonString = responseContent.toJSONString(); - if (jsonString.contains("result") && (responseContent.getString("result").equals("true") - && responseContent.getString("message").equals("Input note has been spent"))) { - return Boolean.TRUE; - } else { - return Boolean.FALSE; - } - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static List scanNoteByOvkFromPbft(String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed.getNowBlockFromPbft(httpSolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - - final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/scannotebyovk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ovk", ByteArray.toHexString(shieldAddressInfo.getOvk())); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(0).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - - /** - * constructor. - */ - public static List scanNoteByIvk(String httpNode, - ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - - final String requestUrl = "http://" + httpNode + "/wallet/scannotebyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - if (jsonArray != null) { - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(i).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static List scanNoteByIvkFromSolidity(String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed.getNowBlockFromSolidity(httpSolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - - final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/scannotebyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(i).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static List scanNoteByIvkFromPbft(String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed.getNowBlockFromPbft(httpSolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - - final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/scannotebyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(i).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - - /** - * constructor. - */ - public static List scanAndMarkNoteByIvk(String httpNode, - ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); - responseContent = HttpMethed.parseResponseContent(response); - String ask = responseContent.getString("ask"); - String nsk = responseContent.getString("nsk"); - response = HttpMethed.getAkFromAsk(httpNode, ask); - responseContent = HttpMethed.parseResponseContent(response); - final String ak = responseContent.getString("value"); - - response = HttpMethed.getNkFromNsk(httpNode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - final String nk = responseContent.getString("value"); - - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - - final String requestUrl = "http://" + httpNode + "/wallet/scanandmarknotebyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); - userBaseObj2.addProperty("ak", ak); - userBaseObj2.addProperty("nk", nk); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - logger.info("jsonArray:" + jsonArray.toJSONString()); - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(i).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIsSpend(HttpMethed.parseStringContent(noteTxs).getBoolean("is_spend")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static List scanAndMarkNoteByIvkFromSolidity(String httpNode, - String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); - responseContent = HttpMethed.parseResponseContent(response); - String ask = responseContent.getString("ask"); - String nsk = responseContent.getString("nsk"); - response = HttpMethed.getAkFromAsk(httpNode, ask); - responseContent = HttpMethed.parseResponseContent(response); - final String ak = responseContent.getString("value"); - - response = HttpMethed.getNkFromNsk(httpNode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - final String nk = responseContent.getString("value"); - - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - - final String requestUrl = - "http://" + httpSolidityNode + "/walletsolidity/scanandmarknotebyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); - userBaseObj2.addProperty("ak", ak); - userBaseObj2.addProperty("nk", nk); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - logger.info("jsonArray:" + jsonArray.toJSONString()); - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(i).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIsSpend(HttpMethed.parseStringContent(noteTxs).getBoolean("is_spend")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static List scanAndMarkNoteByIvkFromPbft(String httpNode, - String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); - responseContent = HttpMethed.parseResponseContent(response); - String ask = responseContent.getString("ask"); - String nsk = responseContent.getString("nsk"); - response = HttpMethed.getAkFromAsk(httpNode, ask); - responseContent = HttpMethed.parseResponseContent(response); - final String ak = responseContent.getString("value"); - - response = HttpMethed.getNkFromNsk(httpNode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - final String nk = responseContent.getString("value"); - - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/scanandmarknotebyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); - userBaseObj2.addProperty("ak", ak); - userBaseObj2.addProperty("nk", nk); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - logger.info("jsonArray:" + jsonArray.toJSONString()); - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(i).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIsSpend(HttpMethed.parseStringContent(noteTxs).getBoolean("is_spend")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - - /** - * constructor. - */ - public static List scanNoteByOvk(String httpNode, - ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - - final String requestUrl = "http://" + httpNode + "/wallet/scannotebyovk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ovk", ByteArray.toHexString(shieldAddressInfo.getOvk())); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(i).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static List scanNoteByOvkFromSolidity(String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed.getNowBlockFromSolidity(httpSolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - - final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/scannotebyovk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ovk", ByteArray.toHexString(shieldAddressInfo.getOvk())); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(0).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String httpSolidityNode, - String httpPbftNode, byte[] publicZenTokenOwnerAddress, long fromAmount, - ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx, - List shieldOutputList, byte[] publicZenTokenToAddress, long toAmount, - String zenTokenOwnerKey) { - try { - final String requestUrl = - "http://" + httpNode + "/wallet/createshieldedtransactionwithoutspendauthsig"; - - Map map = new HashMap(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - map.put("transparent_from_address", ByteArray.toHexString(publicZenTokenOwnerAddress)); - map.put("from_amount", fromAmount); - } - String ask = ""; - byte[] alpha = null; - if (shieldAddressInfo != null) { - HttpResponse expandedSpendingKey = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.getSk())); - responseContent = HttpMethed.parseResponseContent(expandedSpendingKey); - HttpMethed.printJsonContent(responseContent); - map.put("nsk", responseContent.getString("nsk")); - map.put("ovk", responseContent.getString("ovk")); - ask = responseContent.getString("ask"); - response = HttpMethed.getAkFromAsk(httpNode, ask); + //HttpMethed.printJsonContent(responseContent); + //httppost.releaseConnection(); + if (!responseContent.containsKey("balance")) { + return 0L; + } + return Long.parseLong(responseContent.get("balance").toString()); + } + + + /** + * constructor. + */ + public static HttpResponse getAccountNet(String httpNode, byte[] queryAddress) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getaccountnet"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getAccountReource(String httpNode, byte[] queryAddress) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getaccountresource"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getAccountBalance(String httpNode, + byte[] queryAddress, Integer blockNum, String blockHash) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getaccountbalance"; + JsonObject addressObj = new JsonObject(); + addressObj.addProperty("address", Base58.encode58Check(queryAddress)); + JsonObject blockObj = new JsonObject(); + blockObj.addProperty("hash", blockHash); + blockObj.addProperty("number", blockNum); + JsonObject accountBalanceObj = new JsonObject(); + accountBalanceObj.add("account_identifier", addressObj); + accountBalanceObj.add("block_identifier", blockObj); + accountBalanceObj.addProperty("visible", true); + logger.info(accountBalanceObj.toString()); + response = createConnect(requestUrl, accountBalanceObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getBlockBalance(String httpNode, Integer blockNum, String blockHash) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getblockbalance"; + JsonObject blockObj = new JsonObject(); + blockObj.addProperty("hash", blockHash); + blockObj.addProperty("number", blockNum); + blockObj.addProperty("visible", true); + response = createConnect(requestUrl, blockObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static Long getBurnTrx(String httpNode) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getburntrx"; + JsonObject blockObj = new JsonObject(); + response = createConnect(requestUrl, blockObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - map.put("ak", responseContent.getString("value")); - - logger.info("noteTx.getTrxId():" + noteTx.getTrxId()); - HttpMethed.response = HttpMethed - .getMerkleTreeVoucherInfoFromSolidity(httpSolidityNode, noteTx.getTrxId(), - noteTx.getIndex(), 1); - HttpMethed.responseContent = HttpMethed.parseResponseContent(HttpMethed.response); - HttpMethed.printJsonContent(responseContent); - final JSONArray vouchers = HttpMethed.responseContent.getJSONArray("vouchers"); - final JSONArray paths = HttpMethed.responseContent.getJSONArray("paths"); - - HttpMethed.response = HttpMethed - .getMerkleTreeVoucherInfoFromPbft(httpPbftNode, noteTx.getTrxId(), noteTx.getIndex(), - 1); - HttpMethed.responseContent = HttpMethed.parseResponseContent(HttpMethed.response); - HttpMethed.printJsonContent(responseContent); - JSONArray vouchersPbft = HttpMethed.responseContent.getJSONArray("vouchers"); - JSONArray pathsPbft = HttpMethed.responseContent.getJSONArray("paths"); - Assert.assertTrue(pathsPbft.equals(paths)); - alpha = org.tron.core.zen.note.Note.generateR(); - - List shieldedSpends = Lists.newArrayList(new JSONObjectWarp().put("note", - new JSONObjectWarp().put("value", noteTx.getValue()) - .put("payment_address", noteTx.getPaymentAddress()) - .put("rcm", ByteArray.toHexString(noteTx.getR())) - .put("memo", ByteArray.toHexString(noteTx.getMemo()))) - .put("alpha", ByteArray.toHexString(alpha)).put("voucher", Lists.newArrayList(vouchers)) - .put("path", Lists.newArrayList(paths))); - - map.put("shielded_spends", shieldedSpends); - } else { - map.put("ovk", "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - } - - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - map.put("transparent_to_address", ByteArray.toHexString(publicZenTokenToAddress)); - map.put("to_amount", toAmount); - } - - if (shieldOutputList.size() > 0) { - ArrayList noteList = new ArrayList<>(); - for (int i = 0; i < shieldOutputList.size(); ++i) { - Map noteInfo = new HashMap(); - noteInfo.put("value", shieldOutputList.get(i).getValue()); - noteInfo.put("payment_address", shieldOutputList.get(i).getPaymentAddress()); - noteInfo.put("rcm", shieldOutputList.get(i).getRcm().toStringUtf8()); - noteInfo.put("memo", - ByteArray.toHexString(shieldOutputList.get(i).getMemo().toStringUtf8().getBytes())); - final Map note = new HashMap(); - note.put("note", noteInfo); - noteList.add(note); - } - map.put("shielded_receives", noteList); - } - - String jsonStr = new Gson().toJson(map); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - logger.info("jsonObj:" + jsonObj.toString()); - response = createConnect(requestUrl, jsonObj); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info("transactionString1:" + transactionString); - - if (shieldAddressInfo != null) { - String getHashUrl = "http://" + httpNode + "/wallet/getshieldtransactionhash"; - JsonObject gethashObject = new JsonParser().parse(transactionString).getAsJsonObject(); - logger.info("gethashObject:" + gethashObject); - response = createConnect(getHashUrl, gethashObject); + return responseContent.getLong("burnTrxAmount"); + } + + /** + * constructor. + */ + public static Long getBurnTrxFromSolidity(String httpNode) { + try { + final String requestUrl = "http://" + httpNode + "/walletsolidity/getburntrx"; + JsonObject blockObj = new JsonObject(); + response = createConnect(requestUrl, blockObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String hash = responseContent.getString("value"); - - String spendauthsigUrl = "http://" + httpNode + "/wallet/createspendauthsig"; - JSONObjectWarp spendauthsigJson = new JSONObjectWarp().put("ask", ask) - .put("alpha", ByteArray.toHexString(alpha)).put("tx_hash", hash); - String spendauthsigStr = spendauthsigJson.toJSONString(); - JsonObject spendauthsigObj = new JsonParser().parse(spendauthsigStr).getAsJsonObject(); - logger.info("spendauthsigObj:" + spendauthsigObj.toString()); - response = createConnect(spendauthsigUrl, spendauthsigObj); + return responseContent.getLong("burnTrxAmount"); + } + + /** + * constructor. + */ + public static Long getBurnTrxFromPbft(String httpNode) { + try { + final String requestUrl = "http://" + httpNode + "/walletpbft/getburntrx"; + JsonObject blockObj = new JsonObject(); + response = createConnect(requestUrl, blockObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String spendauthsig = responseContent.getString("value"); - - JSONObject jsonObject = HttpMethed.parseStringContent(transactionString); - jsonObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0) - .getJSONObject("parameter").getJSONObject("value").getJSONArray("spend_description") - .getJSONObject(0).put("spend_authority_signature", spendauthsig); - transactionString = jsonObject.toString(); - logger.info("transactionString2:" + transactionString); - } - - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - transactionSignString = gettransactionsign(httpNode, transactionString, zenTokenOwnerKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } else { - response = broadcastTransaction(httpNode, transactionString); - } - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static void freedResource(String httpNode, byte[] fromAddress, byte[] toAddress, - String fromKey) { - long balance = HttpMethed.getBalance(httpNode, fromAddress); - //System.out.println("剩余资源:" + balance); - sendCoin(httpNode, fromAddress, toAddress, balance - 50000, fromKey); - balance = HttpMethed.getBalance(httpNode, fromAddress); - //System.out.println("之后资源:" + balance); - } - - /** - * constructor. - */ - public static HttpResponse updateBrokerage(String httpNode, byte[] ownerAddress, Long brokerage, - String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/updateBrokerage"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("brokerage", brokerage); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse updateBrokerageOnVisible(String httpNode, byte[] ownerAddress, - Long brokerage, String fromKey, String visible) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/updateBrokerage"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("brokerage", brokerage); - if (visible.equals("true")) { - userBaseObj2.addProperty("owner_address", Base58.encode58Check(ownerAddress)); - } else if (visible.equals("false")) { - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - logger.info("userBaseObj2:" + userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getReward(String httpNode, byte[] address) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getReward"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getRewardFromSolidity(String httpSolidityNode, byte[] address) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getReward"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getRewardFromPbft(String httpSolidityNode, byte[] address) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getReward"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getBrokerage(String httpNode, byte[] address) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getBrokerage"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBrokerageFromSolidity(String httpSolidityNode, byte[] address) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getBrokerage"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getRewardOnVisible(String httpNode, byte[] address, String visible) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getReward"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("address", Base58.encode58Check(address)); - } else if (visible.equals("false")) { - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - } - userBaseObj2.addProperty("visible", visible); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getRewardFromSolidityOnVisible(String httpSolidityNode, byte[] address, - String visible) { - try { - final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getReward"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("address", Base58.encode58Check(address)); - } else if (visible.equals("false")) { - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - } - userBaseObj2.addProperty("visible", visible); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBrokerageOnVisible(String httpNode, byte[] address, - String visible) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getBrokerage"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("address", Base58.encode58Check(address)); - } else if (visible.equals("false")) { - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - } - userBaseObj2.addProperty("visible", visible); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBrokerageFromSolidityOnVisible(String httpSolidityNode, - byte[] address, String visible) { - try { - final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getBrokerage"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("address", Base58.encode58Check(address)); - } else if (visible.equals("false")) { - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - } - userBaseObj2.addProperty("visible", visible); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBrokerageFromPbft(String httpSolidityNode, byte[] address) { - try { - final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getBrokerage"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static String marketSellAssetGetTxId(String httpNode, byte[] ownerAddress, - String sellTokenId, - Long sellTokenQuantity, String buyTokenId, Long buyTokenQuantity, String fromKey, - String visible) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/marketsellasset"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("owner_address", Base58.encode58Check(ownerAddress)); - userBaseObj2.addProperty("sell_token_id", sellTokenId); - userBaseObj2.addProperty("buy_token_id", buyTokenId); - } else { - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); - userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); - } - userBaseObj2.addProperty("sell_token_quantity", sellTokenQuantity); - userBaseObj2.addProperty("buy_token_quantity", buyTokenQuantity); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - System.out.println("userBaseObj2: " + userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - System.out.println("transactionString: " + transactionString); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseStringContent(transactionSignString); - return responseContent.getString("txID"); - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderById(String httpNode, String orderId, String visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getmarketorderbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", orderId); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderByIdFromSolidity(String httpSolidityNode, String orderId, - String visible) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", orderId); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderByIdFromPbft(String httpPbftNode, String orderId, - String visible) { - try { - String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", orderId); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static String marketCancelOrder(String httpNode, byte[] ownerAddress, String orderId, - String fromKey, String visible) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/marketcancelorder"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("owner_address", Base58.encode58Check(ownerAddress)); - } else { - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - } - userBaseObj2.addProperty("order_id", orderId); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - System.out.println("userBaseObj2: " + userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - System.out.println("transactionString: " + transactionString); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseStringContent(transactionSignString); - return responseContent.getString("txID"); - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderByAccount(String httpNode, byte[] ownerAddress, - String visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getmarketorderbyaccount"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("value", Base58.encode58Check(ownerAddress)); - } else { - userBaseObj2.addProperty("value", ByteArray.toHexString(ownerAddress)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderByAccountFromSolidity(String httpSolidityNode, - byte[] ownerAddress, String visible) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderbyaccount"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("value", Base58.encode58Check(ownerAddress)); - } else { - userBaseObj2.addProperty("value", ByteArray.toHexString(ownerAddress)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderByAccountFromPbft(String httpPbftNode, - byte[] ownerAddress, String visible) { - try { - String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderbyaccount"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("value", Base58.encode58Check(ownerAddress)); - } else { - userBaseObj2.addProperty("value", ByteArray.toHexString(ownerAddress)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketPairList(String httpNode, String visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getmarketpairlist"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketPairListFromSolidity(String httpSolidityNode, - String visible) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketpairlist"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketPairListFromPbft(String httpPbftNode, String visible) { - try { - String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketpairlist"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderListByPair(String httpNode, String sellTokenId, - String buyTokenId, String visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getmarketorderlistbypair"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("sell_token_id", sellTokenId); - userBaseObj2.addProperty("buy_token_id", buyTokenId); - } else { - userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); - userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderListByPairFromSolidity(String httpSolidityNode, - String sellTokenId, - String buyTokenId, String visible) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderlistbypair"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("sell_token_id", sellTokenId); - userBaseObj2.addProperty("buy_token_id", buyTokenId); - } else { - userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); - userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderListByPairFromPbft(String httpPbftNode, - String sellTokenId, String buyTokenId, String visible) { - try { - String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderlistbypair"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("sell_token_id", sellTokenId); - userBaseObj2.addProperty("buy_token_id", buyTokenId); - } else { - userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); - userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketPriceByPair(String httpNode, String sellTokenId, - String buyTokenId, String visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getmarketpricebypair"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("sell_token_id", sellTokenId); - userBaseObj2.addProperty("buy_token_id", buyTokenId); - } else { - userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); - userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketPriceByPairFromSolidity(String httpSolidityNode, - String sellTokenId, - String buyTokenId, String visible) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketpricebypair"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("sell_token_id", sellTokenId); - userBaseObj2.addProperty("buy_token_id", buyTokenId); - } else { - userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); - userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketPriceByPairFromPbft(String httpPbftNode, - String sellTokenId, String buyTokenId, String visible) { - try { - String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketpricebypair"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("sell_token_id", sellTokenId); - userBaseObj2.addProperty("buy_token_id", buyTokenId); - } else { - userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); - userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static int getTransactionPendingSize(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getpendingsize"; - JsonObject userBaseObj2 = new JsonObject(); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return 0; - } - responseContent = HttpMethed.parseResponseContent(response); - return responseContent.getInteger("pendingSize"); - } - - /** - * constructor. - */ - public static HttpResponse getTransactionListFromPending(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/gettransactionlistfrompending"; - JsonObject userBaseObj2 = new JsonObject(); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getTransactionFromPending(String httpNode, String txid) { - try { - String requestUrl = "http://" + httpNode + "/wallet/gettransactionfrompending"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", txid); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } + return responseContent.getLong("burnTrxAmount"); + } + + + /** + * constructor. + */ + public static HttpResponse getNowBlock(String httpNode) { + return getNowBlock(httpNode, false); + } + + /** + * constructor. + */ + public static HttpResponse getNowBlock(String httpNode, Boolean visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static Long getNowBlockNum(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return parseResponseContent(response).getJSONObject("block_header").getJSONObject("raw_data") + .getLong("number"); + } + + /** + * constructor. + */ + public static Long getNowBlockNumOnSolidity(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/walletsolidity/getnowblock"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return parseResponseContent(response).getJSONObject("block_header").getJSONObject("raw_data") + .getLong("number"); + } + + + /** + * constructor. + */ + public static HttpResponse getNowBlockFromSolidity(String httpSolidityNode) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getnowblock"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getNowBlockFromPbft(String httpSolidityNode) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getnowblock"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static void waitToProduceOneBlock(String httpNode) { + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); + responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); + Integer currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); + Integer nextBlockNum = 0; + Integer times = 0; + while (nextBlockNum <= currentBlockNum + 1 && times++ <= 10) { + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + responseContent = HttpMethed + .parseStringContent(responseContent.get("block_header").toString()); + responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); + nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); + try { + Thread.sleep(1200); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + /** + * constructor. + */ + public static void waitToProduceOneBlockFromSolidity(String httpNode, String httpSolidityNode) { + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); + responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); + Integer currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); + Integer nextBlockNum = 0; + Integer times = 0; + while (nextBlockNum <= currentBlockNum && times++ <= ((getWitnessNum() >= 27) + ? 27 : getWitnessNum() + 1)) { + response = HttpMethed.getNowBlockFromSolidity(httpSolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + responseContent = HttpMethed + .parseStringContent(responseContent.get("block_header").toString()); + responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); + nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); + try { + Thread.sleep(3500); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + logger.info("currentBlockNum2:" + currentBlockNum); + logger.info("nextBlockNum2:" + nextBlockNum); + } + + /** + * constructor. + */ + public static void waitToProduceOneBlockFromPbft(String httpNode, String httpSolidityNode) { + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); + responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); + Integer currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); + Integer nextBlockNum = 0; + Integer times = 0; + while (nextBlockNum <= currentBlockNum && times++ <= 3) { + response = HttpMethed.getNowBlockFromPbft(httpSolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + responseContent = HttpMethed + .parseStringContent(responseContent.get("block_header").toString()); + responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); + nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); + try { + Thread.sleep(3500); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + + /** + * constructor. + */ + public static HttpResponse getBlockByNum(String httpNode, Integer blockNUm) { + return getBlockByNum(httpNode, blockNUm, false); + } + + /** + * constructor. + */ + public static HttpResponse getBlockByNum(String httpNode, Integer blockNUm, Boolean visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getblockbynum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blockNUm); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static Long getBlockByNumForResponse(String httpNode, Integer blockNUm, Integer times) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getblockbynum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blockNUm); + Long duration = createConnectForResponse(requestUrl, userBaseObj2, times); + return duration; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return -1L; + } + } + + + /** + * constructor. + */ + public static HttpResponse getBlockByNumFromSolidity(String httpSolidityNode, Integer blockNum) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getblockbynum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blockNum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getBlockByNumFromPbft(String httpSolidityNode, Integer blockNum) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getblockbynum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blockNum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getBlockByLimitNext(String httpNode, Integer startNum, + Integer endNum) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getblockbylimitnext"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("startNum", startNum); + userBaseObj2.addProperty("endNum", endNum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getBlockByLimitNextFromSolidity(String httpNode, Integer startNum, + Integer endNum) { + try { + String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbylimitnext"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("startNum", startNum); + userBaseObj2.addProperty("endNum", endNum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getBlockByLimitNextFromPbft(String httpNode, Integer startNum, + Integer endNum) { + try { + String requestUrl = "http://" + httpNode + "/walletpbft/getblockbylimitnext"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("startNum", startNum); + userBaseObj2.addProperty("endNum", endNum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getBlockByLastNum(String httpNode, Integer num) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getblockbylatestnum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", num); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getBlockByLastNum2(String httpNode, Integer num) { + try { + String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbylatestnum2"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", num); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getBlockByLastNumFromSolidity(String httpNode, Integer num) { + try { + String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbylatestnum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", num); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getBlockByLastNumFromPbft(String httpNode, Integer num) { + try { + String requestUrl = "http://" + httpNode + "/walletpbft/getblockbylatestnum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", num); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getBlockById(String httpNode, String blockId) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getblockbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", blockId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getBlockByIdFromSolidity(String httpNode, String blockId) { + try { + String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", blockId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getBlockByIdFromPbft(String httpNode, String blockId) { + try { + String requestUrl = "http://" + httpNode + "/walletpbft/getblockbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", blockId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getDelegatedResource(String httpNode, byte[] fromAddress, + byte[] toAddress) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getdelegatedresource"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("fromAddress", ByteArray.toHexString(fromAddress)); + userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getDelegatedResourceFromSolidity(String httpSolidityNode, + byte[] fromAddress, byte[] toAddress) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getdelegatedresource"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("fromAddress", ByteArray.toHexString(fromAddress)); + userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getDelegatedResourceFromPbft(String httpSolidityNode, + byte[] fromAddress, byte[] toAddress) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getdelegatedresource"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("fromAddress", ByteArray.toHexString(fromAddress)); + userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getDelegatedResourceAccountIndex(String httpNode, + byte[] queryAddress) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getdelegatedresourceaccountindex"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", ByteArray.toHexString(queryAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getDelegatedResourceAccountIndexFromSolidity(String httpSolidityNode, + byte[] queryAddress) { + try { + String requestUrl = + "http://" + httpSolidityNode + "/walletsolidity/getdelegatedresourceaccountindex"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", ByteArray.toHexString(queryAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getDelegatedResourceAccountIndexFromPbft(String httpSolidityNode, + byte[] queryAddress) { + try { + String requestUrl = + "http://" + httpSolidityNode + "/walletpbft/getdelegatedresourceaccountindex"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", ByteArray.toHexString(queryAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse createConnect(String url) { + return createConnect(url, null); + } + + /** + * constructor. + */ + public static HttpResponse createConnect(String url, JsonObject requestBody) { + try { + httpClient.getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + httppost = new HttpPost(url); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + if (requestBody != null) { + StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httppost.setEntity(entity); + } + + logger.info(httppost.toString()); + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse createConnectForGet(String url) { + try { + httpClient.getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + HttpGet httppost; + httppost = new HttpGet(url); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + + logger.info(httppost.toString()); + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse createConnectForShieldTrc20(String url, JSONObject requestBody) { + try { + httpClient.getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + httppost = new HttpPost(url); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + if (requestBody != null) { + StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httppost.setEntity(entity); + } + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static Long createConnectForResponse(String url, JsonObject requestBody, Integer times) { + try { + + Long start = 0L; + Long end = 0L; + Long duration = 0L; + while (times-- > 0) { + httpClient.getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + httppost = new HttpPost(url); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + if (requestBody != null) { + StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httppost.setEntity(entity); + } + + start = System.currentTimeMillis(); + response = httpClient.execute(httppost); + /* responseContent = HttpMethed.parseResponseContent(response); + logger.info(responseContent.toString());*/ + end = System.currentTimeMillis(); + duration = duration + end - start; + httppost.releaseConnection(); + } + return duration; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return -1L; + } + } + + + /** + * constructor. + */ + public static HttpResponse createConnect1(String url, JSONObject requestBody) { + try { + httpClient.getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + httpClient.getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout * 10000); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout * 10000); + httppost = new HttpPost(url); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + if (requestBody != null) { + StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httppost.setEntity(entity); + } + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getAssetissueList(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getassetissuelist"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static Long getAssetIssueValue(String httpNode, byte[] accountAddress, + String assetIssueId) { + response = HttpMethed.getAccount(httpNode, accountAddress); + responseContent = HttpMethed.parseResponseContent(response); + JSONArray assetV2 = responseContent.getJSONArray("assetV2"); + if (assetV2 != null && assetV2.size() > 0) { + for (int i = 0; i < assetV2.size(); i++) { + String assetString = assetV2.get(i).toString(); + logger.info("assetString:" + assetString); + String assetKey = HttpMethed.parseStringContent(assetString).getString("key"); + if (assetKey.equals(assetIssueId)) { + return HttpMethed.parseStringContent(assetString).getLong("value"); + } + } + } + return 0L; + } + + /** + * constructor. + */ + public static HttpResponse getAssetIssueListFromSolidity(String httpSolidityNode) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuelist"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getAssetIssueListFromPbft(String httpSolidityNode) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getassetissuelist"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getPaginatedAssetissueList(String httpNode, Integer offset, + Integer limit) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getpaginatedassetissuelist"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("offset", offset); + userBaseObj2.addProperty("limit", limit); + userBaseObj2.addProperty("visible", "true"); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getPaginatedAssetissueListFromSolidity(String httpSolidityNode, + Integer offset, Integer limit) { + try { + String requestUrl = + "http://" + httpSolidityNode + "/walletsolidity/getpaginatedassetissuelist"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("offset", offset); + userBaseObj2.addProperty("limit", limit); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getPaginatedAssetissueListFromPbft(String httpSolidityNode, + Integer offset, Integer limit) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getpaginatedassetissuelist"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("offset", offset); + userBaseObj2.addProperty("limit", limit); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getPaginatedProposalList(String httpNode, Integer offset, + Integer limit) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getpaginatedproposallist"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("offset", offset); + userBaseObj2.addProperty("limit", limit); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getPaginatedExchangeList(String httpNode, Integer offset, + Integer limit) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getpaginatedexchangelist"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("offset", offset); + userBaseObj2.addProperty("limit", limit); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse updateSetting(String httpNode, byte[] ownerAddress, + String contractAddress, Integer consumeUserResourcePercent, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/updatesetting"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("consume_user_resource_percent", consumeUserResourcePercent); + logger.info(userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse updateEnergyLimit(String httpNode, byte[] ownerAddress, + String contractAddress, Integer originEnergyLimit, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/updateenergylimit"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("origin_energy_limit", originEnergyLimit); + logger.info(userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse createAddress(String httpNode, String value) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createaddress"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", str2hex(value)); + response = createConnect(requestUrl, userBaseObj2); + logger.info(userBaseObj2.toString()); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse generateAddress(String httpNode) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/generateaddress"; + JsonObject userBaseObj2 = new JsonObject(); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getTransactionCountByBlocknum(String httpNode, long blocknum) { + try { + String requestUrl = + "http://" + httpNode + "/wallet/gettransactioncountbyblocknum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blocknum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse validateAddress(String httpNode, String address) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/validateaddress"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", address); + response = createConnect(requestUrl, userBaseObj2); + logger.info(userBaseObj2.toString()); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse easyTransfer(String httpNode, String value, byte[] toAddress, + Long amount) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/easytransfer"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("passPhrase", str2hex(value)); + userBaseObj2.addProperty("amount", amount); + response = createConnect(requestUrl, userBaseObj2); + logger.info(userBaseObj2.toString()); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse easyTransferByPrivate(String httpNode, String privateKey, + byte[] toAddress, Long amount) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/easytransferbyprivate"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("privateKey", privateKey); + userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("amount", amount); + response = createConnect(requestUrl, userBaseObj2); + logger.info(userBaseObj2.toString()); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse easyTransferAsset(String httpNode, String value, byte[] toAddress, + Long amount, String assetId) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/easytransferasset"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("passPhrase", str2hex(value)); + userBaseObj2.addProperty("amount", amount); + userBaseObj2.addProperty("assetId", assetId); + response = createConnect(requestUrl, userBaseObj2); + logger.info(userBaseObj2.toString()); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse easyTransferAssetByPrivate(String httpNode, String privateKey, + byte[] toAddress, Long amount, String assetId) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/easytransferassetbyprivate"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("privateKey", privateKey); + userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("amount", amount); + userBaseObj2.addProperty("assetId", assetId); + response = createConnect(requestUrl, userBaseObj2); + logger.info(userBaseObj2.toString()); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getContractInfo(String httpNode, String contractAddress) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getcontractinfo"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", contractAddress); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static void disConnect() { + httppost.releaseConnection(); + } + + /** + * constructor. + */ + public static JSONObject parseResponseContent(HttpResponse response) { + try { + String result = EntityUtils.toString(response.getEntity()); + StringEntity entity = new StringEntity(result, Charset.forName("UTF-8")); + response.setEntity(entity); + JSONObject obj = JSONObject.parseObject(result); + return obj; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * constructor. + */ + public static List parseResponseContentArray(HttpResponse response) { + try { + String result = EntityUtils.toString(response.getEntity()); + StringEntity entity = new StringEntity(result, Charset.forName("UTF-8")); + response.setEntity(entity); + List list = new ArrayList(); + JSONArray objects = JSONArray.parseArray(result); + for (int i = 0; i < objects.size(); i++) { + list.add(objects.getJSONObject(i)); + } + return list; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * constructor. + */ + public static JSONObject parseStringContent(String content) { + try { + JSONObject obj = JSONObject.parseObject(content); + return obj; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + /** + * constructor. + */ + public static void printJsonContent(JSONObject responseContent) { + logger.info("----------------------------Print JSON Start---------------------------"); + for (String str : responseContent.keySet()) { + logger.info(str + ":" + responseContent.get(str)); + } + logger.info("JSON content size are: " + responseContent.size()); + logger.info("----------------------------Print JSON End-----------------------------"); + } + + /** + * constructor. + */ + public static String str2hex(String str) { + char[] chars = "0123456789ABCDEF".toCharArray(); + StringBuilder sb = new StringBuilder(); + byte[] bs = str.getBytes(); + int bit; + for (int i = 0; i < bs.length; i++) { + bit = (bs[i] & 0x0f0) >> 4; + sb.append(chars[bit]); + bit = bs[i] & 0x0f; + sb.append(chars[bit]); + // sb.append(' '); + } + return sb.toString().trim(); + } + + + /** + * constructor. + */ + public static HttpResponse clearABiGetTxid(String httpNode, byte[] ownerAddress, + String contractAddress, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/clearabi"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + + + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static Optional generateShieldAddress(String httpnode) { + ShieldAddressInfo addressInfo = new ShieldAddressInfo(); + String sk; + String d; + String ask; + String nsk; + String ovk; + String ak; + String nk; + String ivk; + String pkD; + try { + response = HttpMethed.getSpendingKey(httpnode); + responseContent = HttpMethed.parseResponseContent(response); + sk = responseContent.getString("value"); + + response = HttpMethed.getDiversifier(httpnode); + responseContent = HttpMethed.parseResponseContent(response); + d = responseContent.getString("d"); + + response = HttpMethed.getExpandedSpendingKey(httpnode, sk); + responseContent = HttpMethed.parseResponseContent(response); + ask = responseContent.getString("ask"); + nsk = responseContent.getString("nsk"); + ovk = responseContent.getString("ovk"); + + response = HttpMethed.getAkFromAsk(httpnode, ask); + responseContent = HttpMethed.parseResponseContent(response); + ak = responseContent.getString("value"); + + response = HttpMethed.getNkFromNsk(httpnode, nsk); + responseContent = HttpMethed.parseResponseContent(response); + nk = responseContent.getString("value"); + + response = HttpMethed.getIncomingViewingKey(httpnode, ak, nk); + responseContent = HttpMethed.parseResponseContent(response); + ivk = responseContent.getString("ivk"); + + response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d); + responseContent = HttpMethed.parseResponseContent(response); + pkD = responseContent.getString("pkD"); + + addressInfo.setSk(ByteArray.fromHexString(sk)); + addressInfo.setD(new DiversifierT(ByteArray.fromHexString(d))); + addressInfo.setIvk(ByteArray.fromHexString(ivk)); + addressInfo.setOvk(ByteArray.fromHexString(ovk)); + addressInfo.setPkD(ByteArray.fromHexString(pkD)); + logger.info("sk:" + sk); + + if (addressInfo.validateCheck()) { + return Optional.of(addressInfo); + } + } catch (Exception e) { + e.printStackTrace(); + } + + return Optional.empty(); + } + + /** + * constructor. + */ + public static List addShieldOutputList(String httpNode, + List shieldOutList, String shieldToAddress, String toAmountString, + String menoString) { + String shieldAddress = shieldToAddress; + String amountString = toAmountString; + if (menoString.equals("null")) { + menoString = ""; + } + long shieldAmount = 0; + if (!StringUtil.isNullOrEmpty(amountString)) { + shieldAmount = Long.valueOf(amountString); + } + + GrpcAPI.Note.Builder noteBuild = GrpcAPI.Note.newBuilder(); + noteBuild.setPaymentAddress(shieldAddress); + noteBuild.setPaymentAddress(shieldAddress); + noteBuild.setValue(shieldAmount); + + response = HttpMethed.getRcm(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + String rcm = responseContent.getString("value"); + + noteBuild.setRcm(ByteString.copyFrom(rcm.getBytes())); + noteBuild.setMemo(ByteString.copyFrom(menoString.getBytes())); + shieldOutList.add(noteBuild.build()); + return shieldOutList; + } + + /** + * constructor. + */ + public static HttpResponse getSpendingKey(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getspendingkey"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getDiversifier(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getdiversifier"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getRcm(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getrcm"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getExpandedSpendingKey(String httpNode, String spendingKey) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getexpandedspendingkey"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", spendingKey); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getAkFromAsk(String httpNode, String ask) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getakfromask"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", ask); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getNkFromNsk(String httpNode, String nsk) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getnkfromnsk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", nsk); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getIncomingViewingKey(String httpNode, String ak, String nk) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getincomingviewingkey"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("ak", ak); + userBaseObj2.addProperty("nk", nk); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getNewShieldedAddress(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getnewshieldedaddress"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getZenPaymentAddress(String httpNode, String ivk, String d) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getzenpaymentaddress"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("ivk", ivk); + userBaseObj2.addProperty("d", d); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMerkleTreeVoucherInfo(String httpNode, String hash, Integer index, + int blockNum) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getmerkletreevoucherinfo"; + JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); + jsonObjectWarp.put("out_points", + Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) + .put("block_num", blockNum); + String jsonStr = jsonObjectWarp.toJSONString(); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + logger.info("jsonObj:" + jsonObj.toString()); + response = createConnect(requestUrl, jsonObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMerkleTreeVoucherInfoFromSolidity(String httpSolidityNode, + String hash, Integer index, int blockNum) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmerkletreevoucherinfo"; + JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); + jsonObjectWarp.put("out_points", + Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) + .put("block_num", blockNum); + String jsonStr = jsonObjectWarp.toJSONString(); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + logger.info("jsonObj:" + jsonObj.toString()); + response = createConnect(requestUrl, jsonObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMerkleTreeVoucherInfoFromPbft(String httpSolidityNode, String hash, + Integer index, int blockNum) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getmerkletreevoucherinfo"; + JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); + jsonObjectWarp.put("out_points", + Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) + .put("block_num", blockNum); + String jsonStr = jsonObjectWarp.toJSONString(); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + logger.info("jsonObj:" + jsonObj.toString()); + response = createConnect(requestUrl, jsonObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse sendShieldCoin(String httpNode, byte[] publicZenTokenOwnerAddress, + long fromAmount, ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx, + List shieldOutputList, byte[] publicZenTokenToAddress, long toAmount, + String zenTokenOwnerKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createshieldedtransaction"; + + Map map = new HashMap(); + if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { + map.put("transparent_from_address", ByteArray.toHexString(publicZenTokenOwnerAddress)); + map.put("from_amount", fromAmount); + } + if (shieldAddressInfo != null) { + HttpResponse expandedSpendingKey = HttpMethed + .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.getSk())); + responseContent = HttpMethed.parseResponseContent(expandedSpendingKey); + HttpMethed.printJsonContent(responseContent); + String ovk = responseContent.getString("ovk"); + map.put("ask", responseContent.getString("ask")); + map.put("nsk", responseContent.getString("nsk")); + map.put("ovk", ovk); + + response = HttpMethed + .getMerkleTreeVoucherInfo(httpNode, noteTx.getTrxId(), noteTx.getIndex(), 1); + responseContent = HttpMethed.parseResponseContent(response); + JSONArray vouchers = responseContent.getJSONArray("vouchers"); + JSONArray paths = responseContent.getJSONArray("paths"); + + List shieldedSpends = Lists.newArrayList(new JSONObjectWarp().put("note", + new JSONObjectWarp().put("value", noteTx.getValue()) + .put("payment_address", noteTx.getPaymentAddress()) + .put("rcm", ByteArray.toHexString(noteTx.getR())) + .put("memo", ByteArray.toHexString(noteTx.getMemo()))) + .put("alpha", ByteArray.toHexString(org.tron.core.zen.note.Note.generateR())) + .put("voucher", Lists.newArrayList(vouchers)).put("path", Lists.newArrayList(paths))); + + map.put("shielded_spends", shieldedSpends); + } else { + map.put("ovk", "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); + } + + if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { + map.put("transparent_to_address", ByteArray.toHexString(publicZenTokenToAddress)); + map.put("to_amount", toAmount); + } + + if (shieldOutputList.size() > 0) { + ArrayList noteList = new ArrayList<>(); + for (int i = 0; i < shieldOutputList.size(); ++i) { + + Map noteInfo = new HashMap(); + noteInfo.put("value", shieldOutputList.get(i).getValue()); + noteInfo.put("payment_address", shieldOutputList.get(i).getPaymentAddress()); + noteInfo.put("rcm", shieldOutputList.get(i).getRcm().toStringUtf8()); + noteInfo.put("memo", + ByteArray.toHexString(shieldOutputList.get(i).getMemo().toStringUtf8().getBytes())); + final Map note = new HashMap(); + note.put("note", noteInfo); + noteList.add(note); + } + map.put("shielded_receives", noteList); + } + + String jsonStr = new Gson().toJson(map); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + logger.info("jsonObj:" + jsonObj.toString()); + response = createConnect(requestUrl, jsonObj); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { + transactionSignString = gettransactionsign(httpNode, transactionString, zenTokenOwnerKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } else { + response = broadcastTransaction(httpNode, transactionString); + } + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static Boolean getSpendResult(String httpNode, ShieldAddressInfo shieldAddressInfo, + ShieldNoteInfo noteTx) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/isspend"; + + response = HttpMethed + .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + responseContent = HttpMethed.parseResponseContent(response); + String ask = responseContent.getString("ask"); + response = HttpMethed.getAkFromAsk(httpNode, ask); + responseContent = HttpMethed.parseResponseContent(response); + JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); + jsonObjectWarp.put("ak", responseContent.getString("value")); + + String nsk = responseContent.getString("nsk"); + response = HttpMethed.getNkFromNsk(httpNode, nsk); + responseContent = HttpMethed.parseResponseContent(response); + jsonObjectWarp.put("nk", responseContent.getString("value")); + + jsonObjectWarp.put("note", new JSONObjectWarp().put("value", noteTx.getValue()) + .put("payment_address", noteTx.getPaymentAddress()) + .put("rcm", ByteArray.toHexString(noteTx.getR())) + .put("memo", ByteArray.toHexString(noteTx.getMemo()))).put("txid", noteTx.getTrxId()); + + String jsonStr = jsonObjectWarp.toJSONString(); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + logger.info("jsonObj:" + jsonObj.toString()); + HttpMethed.response = createConnect(requestUrl, jsonObj); + + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String jsonString = responseContent.toJSONString(); + if (jsonString.contains("result") && (responseContent.getString("result").equals("true") + && responseContent.getString("message").equals("Input note has been spent"))) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + /** + * constructor. + */ + public static Boolean getSpendResultFromSolidity(String httpNode, String httpSolidityNode, + ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx) { + try { + final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/isspend"; + + response = HttpMethed + .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + responseContent = HttpMethed.parseResponseContent(response); + String ask = responseContent.getString("ask"); + response = HttpMethed.getAkFromAsk(httpNode, ask); + responseContent = HttpMethed.parseResponseContent(response); + JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); + jsonObjectWarp.put("ak", responseContent.getString("value")); + + String nsk = responseContent.getString("nsk"); + response = HttpMethed.getNkFromNsk(httpNode, nsk); + responseContent = HttpMethed.parseResponseContent(response); + jsonObjectWarp.put("nk", responseContent.getString("value")); + + jsonObjectWarp.put("note", new JSONObjectWarp().put("value", noteTx.getValue()) + .put("payment_address", noteTx.getPaymentAddress()) + .put("rcm", ByteArray.toHexString(noteTx.getR())) + .put("memo", ByteArray.toHexString(noteTx.getMemo()))).put("txid", noteTx.getTrxId()); + + String jsonStr = jsonObjectWarp.toJSONString(); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + logger.info("jsonObj:" + jsonObj.toString()); + HttpMethed.response = createConnect(requestUrl, jsonObj); + responseContent = HttpMethed.parseResponseContent(response); + + HttpMethed.printJsonContent(responseContent); + String jsonString = responseContent.toJSONString(); + if (jsonString.contains("result") && (responseContent.getString("result").equals("true") + && responseContent.getString("message").equals("Input note has been spent"))) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + /** + * constructor. + */ + public static Boolean getSpendResultFromPbft(String httpNode, String httpSolidityNode, + ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx) { + try { + final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/isspend"; + final JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); + + response = HttpMethed + .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + responseContent = HttpMethed.parseResponseContent(response); + String ask = responseContent.getString("ask"); + final String nsk = responseContent.getString("nsk"); + response = HttpMethed.getAkFromAsk(httpNode, ask); + responseContent = HttpMethed.parseResponseContent(response); + jsonObjectWarp.put("ak", responseContent.getString("value")); + response = HttpMethed.getNkFromNsk(httpNode, nsk); + responseContent = HttpMethed.parseResponseContent(response); + jsonObjectWarp.put("nk", responseContent.getString("value")); + jsonObjectWarp.put("note", new JSONObjectWarp().put("value", noteTx.getValue()) + .put("payment_address", noteTx.getPaymentAddress()) + .put("rcm", ByteArray.toHexString(noteTx.getR())) + .put("memo", ByteArray.toHexString(noteTx.getMemo()))).put("txid", noteTx.getTrxId()); + String jsonStr = jsonObjectWarp.toJSONString(); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + logger.info("jsonObj:" + jsonObj.toString()); + HttpMethed.response = createConnect(requestUrl, jsonObj); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String jsonString = responseContent.toJSONString(); + if (jsonString.contains("result") && (responseContent.getString("result").equals("true") + && responseContent.getString("message").equals("Input note has been spent"))) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** + * constructor. + */ + public static List scanNoteByOvkFromPbft(String httpSolidityNode, + ShieldAddressInfo shieldAddressInfo) { + try { + response = HttpMethed.getNowBlockFromPbft(httpSolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") + .toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + + final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/scannotebyovk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ovk", ByteArray.toHexString(shieldAddressInfo.getOvk())); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(0).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + + /** + * constructor. + */ + public static List scanNoteByIvk(String httpNode, + ShieldAddressInfo shieldAddressInfo) { + try { + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") + .toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + + final String requestUrl = "http://" + httpNode + "/wallet/scannotebyivk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + if (jsonArray != null) { + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(i).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** + * constructor. + */ + public static List scanNoteByIvkFromSolidity(String httpSolidityNode, + ShieldAddressInfo shieldAddressInfo) { + try { + response = HttpMethed.getNowBlockFromSolidity(httpSolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") + .toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + + final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/scannotebyivk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(i).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** + * constructor. + */ + public static List scanNoteByIvkFromPbft(String httpSolidityNode, + ShieldAddressInfo shieldAddressInfo) { + try { + response = HttpMethed.getNowBlockFromPbft(httpSolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") + .toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + + final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/scannotebyivk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(i).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + + /** + * constructor. + */ + public static List scanAndMarkNoteByIvk(String httpNode, + ShieldAddressInfo shieldAddressInfo) { + try { + response = HttpMethed + .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + responseContent = HttpMethed.parseResponseContent(response); + String ask = responseContent.getString("ask"); + String nsk = responseContent.getString("nsk"); + response = HttpMethed.getAkFromAsk(httpNode, ask); + responseContent = HttpMethed.parseResponseContent(response); + final String ak = responseContent.getString("value"); + + response = HttpMethed.getNkFromNsk(httpNode, nsk); + responseContent = HttpMethed.parseResponseContent(response); + final String nk = responseContent.getString("value"); + + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") + .toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + + final String requestUrl = "http://" + httpNode + "/wallet/scanandmarknotebyivk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); + userBaseObj2.addProperty("ak", ak); + userBaseObj2.addProperty("nk", nk); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + logger.info("jsonArray:" + jsonArray.toJSONString()); + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(i).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIsSpend(HttpMethed.parseStringContent(noteTxs).getBoolean("is_spend")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** + * constructor. + */ + public static List scanAndMarkNoteByIvkFromSolidity(String httpNode, + String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { + try { + response = HttpMethed + .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + responseContent = HttpMethed.parseResponseContent(response); + String ask = responseContent.getString("ask"); + String nsk = responseContent.getString("nsk"); + response = HttpMethed.getAkFromAsk(httpNode, ask); + responseContent = HttpMethed.parseResponseContent(response); + final String ak = responseContent.getString("value"); + + response = HttpMethed.getNkFromNsk(httpNode, nsk); + responseContent = HttpMethed.parseResponseContent(response); + final String nk = responseContent.getString("value"); + + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") + .toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + + final String requestUrl = + "http://" + httpSolidityNode + "/walletsolidity/scanandmarknotebyivk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); + userBaseObj2.addProperty("ak", ak); + userBaseObj2.addProperty("nk", nk); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + logger.info("jsonArray:" + jsonArray.toJSONString()); + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(i).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIsSpend(HttpMethed.parseStringContent(noteTxs).getBoolean("is_spend")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** + * constructor. + */ + public static List scanAndMarkNoteByIvkFromPbft(String httpNode, + String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { + try { + response = HttpMethed + .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + responseContent = HttpMethed.parseResponseContent(response); + String ask = responseContent.getString("ask"); + String nsk = responseContent.getString("nsk"); + response = HttpMethed.getAkFromAsk(httpNode, ask); + responseContent = HttpMethed.parseResponseContent(response); + final String ak = responseContent.getString("value"); + + response = HttpMethed.getNkFromNsk(httpNode, nsk); + responseContent = HttpMethed.parseResponseContent(response); + final String nk = responseContent.getString("value"); + + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") + .toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/scanandmarknotebyivk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); + userBaseObj2.addProperty("ak", ak); + userBaseObj2.addProperty("nk", nk); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + logger.info("jsonArray:" + jsonArray.toJSONString()); + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(i).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIsSpend(HttpMethed.parseStringContent(noteTxs).getBoolean("is_spend")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + + /** + * constructor. + */ + public static List scanNoteByOvk(String httpNode, + ShieldAddressInfo shieldAddressInfo) { + try { + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") + .toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + + final String requestUrl = "http://" + httpNode + "/wallet/scannotebyovk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ovk", ByteArray.toHexString(shieldAddressInfo.getOvk())); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(i).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** + * constructor. + */ + public static List scanNoteByOvkFromSolidity(String httpSolidityNode, + ShieldAddressInfo shieldAddressInfo) { + try { + response = HttpMethed.getNowBlockFromSolidity(httpSolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") + .toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + + final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/scannotebyovk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ovk", ByteArray.toHexString(shieldAddressInfo.getOvk())); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(0).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** + * constructor. + */ + public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String httpSolidityNode, + String httpPbftNode, byte[] publicZenTokenOwnerAddress, long fromAmount, + ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx, + List shieldOutputList, byte[] publicZenTokenToAddress, long toAmount, + String zenTokenOwnerKey) { + try { + final String requestUrl = + "http://" + httpNode + "/wallet/createshieldedtransactionwithoutspendauthsig"; + + Map map = new HashMap(); + if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { + map.put("transparent_from_address", ByteArray.toHexString(publicZenTokenOwnerAddress)); + map.put("from_amount", fromAmount); + } + String ask = ""; + byte[] alpha = null; + if (shieldAddressInfo != null) { + HttpResponse expandedSpendingKey = HttpMethed + .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.getSk())); + responseContent = HttpMethed.parseResponseContent(expandedSpendingKey); + HttpMethed.printJsonContent(responseContent); + map.put("nsk", responseContent.getString("nsk")); + map.put("ovk", responseContent.getString("ovk")); + ask = responseContent.getString("ask"); + response = HttpMethed.getAkFromAsk(httpNode, ask); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + map.put("ak", responseContent.getString("value")); + + logger.info("noteTx.getTrxId():" + noteTx.getTrxId()); + HttpMethed.response = HttpMethed + .getMerkleTreeVoucherInfoFromSolidity(httpSolidityNode, noteTx.getTrxId(), + noteTx.getIndex(), 1); + HttpMethed.responseContent = HttpMethed.parseResponseContent(HttpMethed.response); + HttpMethed.printJsonContent(responseContent); + final JSONArray vouchers = HttpMethed.responseContent.getJSONArray("vouchers"); + final JSONArray paths = HttpMethed.responseContent.getJSONArray("paths"); + + HttpMethed.response = HttpMethed + .getMerkleTreeVoucherInfoFromPbft(httpPbftNode, noteTx.getTrxId(), noteTx.getIndex(), + 1); + HttpMethed.responseContent = HttpMethed.parseResponseContent(HttpMethed.response); + HttpMethed.printJsonContent(responseContent); + JSONArray vouchersPbft = HttpMethed.responseContent.getJSONArray("vouchers"); + JSONArray pathsPbft = HttpMethed.responseContent.getJSONArray("paths"); + Assert.assertTrue(pathsPbft.equals(paths)); + alpha = org.tron.core.zen.note.Note.generateR(); + + List shieldedSpends = Lists.newArrayList(new JSONObjectWarp().put("note", + new JSONObjectWarp().put("value", noteTx.getValue()) + .put("payment_address", noteTx.getPaymentAddress()) + .put("rcm", ByteArray.toHexString(noteTx.getR())) + .put("memo", ByteArray.toHexString(noteTx.getMemo()))) + .put("alpha", ByteArray.toHexString(alpha)).put("voucher", Lists.newArrayList(vouchers)) + .put("path", Lists.newArrayList(paths))); + + map.put("shielded_spends", shieldedSpends); + } else { + map.put("ovk", "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); + } + + if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { + map.put("transparent_to_address", ByteArray.toHexString(publicZenTokenToAddress)); + map.put("to_amount", toAmount); + } + + if (shieldOutputList.size() > 0) { + ArrayList noteList = new ArrayList<>(); + for (int i = 0; i < shieldOutputList.size(); ++i) { + Map noteInfo = new HashMap(); + noteInfo.put("value", shieldOutputList.get(i).getValue()); + noteInfo.put("payment_address", shieldOutputList.get(i).getPaymentAddress()); + noteInfo.put("rcm", shieldOutputList.get(i).getRcm().toStringUtf8()); + noteInfo.put("memo", + ByteArray.toHexString(shieldOutputList.get(i).getMemo().toStringUtf8().getBytes())); + final Map note = new HashMap(); + note.put("note", noteInfo); + noteList.add(note); + } + map.put("shielded_receives", noteList); + } + + String jsonStr = new Gson().toJson(map); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + logger.info("jsonObj:" + jsonObj.toString()); + response = createConnect(requestUrl, jsonObj); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info("transactionString1:" + transactionString); + + if (shieldAddressInfo != null) { + String getHashUrl = "http://" + httpNode + "/wallet/getshieldtransactionhash"; + JsonObject gethashObject = new JsonParser().parse(transactionString).getAsJsonObject(); + logger.info("gethashObject:" + gethashObject); + response = createConnect(getHashUrl, gethashObject); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String hash = responseContent.getString("value"); + + String spendauthsigUrl = "http://" + httpNode + "/wallet/createspendauthsig"; + JSONObjectWarp spendauthsigJson = new JSONObjectWarp().put("ask", ask) + .put("alpha", ByteArray.toHexString(alpha)).put("tx_hash", hash); + String spendauthsigStr = spendauthsigJson.toJSONString(); + JsonObject spendauthsigObj = new JsonParser().parse(spendauthsigStr).getAsJsonObject(); + logger.info("spendauthsigObj:" + spendauthsigObj.toString()); + response = createConnect(spendauthsigUrl, spendauthsigObj); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String spendauthsig = responseContent.getString("value"); + + JSONObject jsonObject = HttpMethed.parseStringContent(transactionString); + jsonObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0) + .getJSONObject("parameter").getJSONObject("value").getJSONArray("spend_description") + .getJSONObject(0).put("spend_authority_signature", spendauthsig); + transactionString = jsonObject.toString(); + logger.info("transactionString2:" + transactionString); + } + + if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { + transactionSignString = gettransactionsign(httpNode, transactionString, zenTokenOwnerKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } else { + response = broadcastTransaction(httpNode, transactionString); + } + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static void freedResource(String httpNode, byte[] fromAddress, byte[] toAddress, + String fromKey) { + long balance = HttpMethed.getBalance(httpNode, fromAddress); + //System.out.println("剩余资源:" + balance); + sendCoin(httpNode, fromAddress, toAddress, balance - 50000, fromKey); + balance = HttpMethed.getBalance(httpNode, fromAddress); + //System.out.println("之后资源:" + balance); + } + + /** + * constructor. + */ + public static HttpResponse updateBrokerage(String httpNode, byte[] ownerAddress, Long brokerage, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/updateBrokerage"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("brokerage", brokerage); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse updateBrokerageOnVisible(String httpNode, byte[] ownerAddress, + Long brokerage, String fromKey, String visible) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/updateBrokerage"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("brokerage", brokerage); + if (visible.equals("true")) { + userBaseObj2.addProperty("owner_address", Base58.encode58Check(ownerAddress)); + } else if (visible.equals("false")) { + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + logger.info("userBaseObj2:" + userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getReward(String httpNode, byte[] address) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getReward"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getRewardFromSolidity(String httpSolidityNode, byte[] address) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getReward"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getRewardFromPbft(String httpSolidityNode, byte[] address) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getReward"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getBrokerage(String httpNode, byte[] address) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getBrokerage"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getBrokerageFromSolidity(String httpSolidityNode, byte[] address) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getBrokerage"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getRewardOnVisible(String httpNode, byte[] address, String visible) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getReward"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("address", Base58.encode58Check(address)); + } else if (visible.equals("false")) { + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + } + userBaseObj2.addProperty("visible", visible); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getRewardFromSolidityOnVisible(String httpSolidityNode, byte[] address, + String visible) { + try { + final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getReward"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("address", Base58.encode58Check(address)); + } else if (visible.equals("false")) { + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + } + userBaseObj2.addProperty("visible", visible); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getBrokerageOnVisible(String httpNode, byte[] address, + String visible) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getBrokerage"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("address", Base58.encode58Check(address)); + } else if (visible.equals("false")) { + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + } + userBaseObj2.addProperty("visible", visible); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getBrokerageFromSolidityOnVisible(String httpSolidityNode, + byte[] address, String visible) { + try { + final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getBrokerage"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("address", Base58.encode58Check(address)); + } else if (visible.equals("false")) { + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + } + userBaseObj2.addProperty("visible", visible); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getBrokerageFromPbft(String httpSolidityNode, byte[] address) { + try { + final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getBrokerage"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static String marketSellAssetGetTxId(String httpNode, byte[] ownerAddress, + String sellTokenId, + Long sellTokenQuantity, String buyTokenId, Long buyTokenQuantity, String fromKey, + String visible) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/marketsellasset"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("owner_address", Base58.encode58Check(ownerAddress)); + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("sell_token_quantity", sellTokenQuantity); + userBaseObj2.addProperty("buy_token_quantity", buyTokenQuantity); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + System.out.println("userBaseObj2: " + userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + System.out.println("transactionString: " + transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseStringContent(transactionSignString); + return responseContent.getString("txID"); + } + + /** + * constructor. + */ + public static HttpResponse getMarketOrderById(String httpNode, String orderId, String visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getmarketorderbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", orderId); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketOrderByIdFromSolidity(String httpSolidityNode, String orderId, + String visible) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", orderId); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketOrderByIdFromPbft(String httpPbftNode, String orderId, + String visible) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", orderId); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static String marketCancelOrder(String httpNode, byte[] ownerAddress, String orderId, + String fromKey, String visible) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/marketcancelorder"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("owner_address", Base58.encode58Check(ownerAddress)); + } else { + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + } + userBaseObj2.addProperty("order_id", orderId); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + System.out.println("userBaseObj2: " + userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + System.out.println("transactionString: " + transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseStringContent(transactionSignString); + return responseContent.getString("txID"); + } + + /** + * constructor. + */ + public static HttpResponse getMarketOrderByAccount(String httpNode, byte[] ownerAddress, + String visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getmarketorderbyaccount"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("value", Base58.encode58Check(ownerAddress)); + } else { + userBaseObj2.addProperty("value", ByteArray.toHexString(ownerAddress)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketOrderByAccountFromSolidity(String httpSolidityNode, + byte[] ownerAddress, String visible) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderbyaccount"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("value", Base58.encode58Check(ownerAddress)); + } else { + userBaseObj2.addProperty("value", ByteArray.toHexString(ownerAddress)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketOrderByAccountFromPbft(String httpPbftNode, + byte[] ownerAddress, String visible) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderbyaccount"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("value", Base58.encode58Check(ownerAddress)); + } else { + userBaseObj2.addProperty("value", ByteArray.toHexString(ownerAddress)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketPairList(String httpNode, String visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getmarketpairlist"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketPairListFromSolidity(String httpSolidityNode, + String visible) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketpairlist"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketPairListFromPbft(String httpPbftNode, String visible) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketpairlist"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketOrderListByPair(String httpNode, String sellTokenId, + String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getmarketorderlistbypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketOrderListByPairFromSolidity(String httpSolidityNode, + String sellTokenId, + String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderlistbypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketOrderListByPairFromPbft(String httpPbftNode, + String sellTokenId, String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderlistbypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketPriceByPair(String httpNode, String sellTokenId, + String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getmarketpricebypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketPriceByPairFromSolidity(String httpSolidityNode, + String sellTokenId, + String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketpricebypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static HttpResponse getMarketPriceByPairFromPbft(String httpPbftNode, + String sellTokenId, String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketpricebypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** + * constructor. + */ + public static int getTransactionPendingSize(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getpendingsize"; + JsonObject userBaseObj2 = new JsonObject(); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return 0; + } + responseContent = HttpMethed.parseResponseContent(response); + return responseContent.getInteger("pendingSize"); + } + + /** + * constructor. + */ + public static HttpResponse getTransactionListFromPending(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/gettransactionlistfrompending"; + JsonObject userBaseObj2 = new JsonObject(); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + + /** + * constructor. + */ + public static HttpResponse getTransactionFromPending(String httpNode, String txid) { + try { + String requestUrl = "http://" + httpNode + "/wallet/gettransactionfrompending"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", txid); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } } diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java index f861cb7a738..396cd730ea7 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java @@ -12,6 +12,7 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; import io.netty.util.internal.StringUtil; + import java.io.BufferedReader; import java.io.File; import java.io.FileReader; @@ -29,6 +30,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; + import org.apache.commons.lang3.StringUtils; import org.bouncycastle.util.encoders.Hex; import org.slf4j.Logger; @@ -139,650 +141,649 @@ public class PublicMethed { - //Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - private static final String FilePath = "Wallet"; - private static final Logger logger = LoggerFactory.getLogger("TestLogger"); - //private WalletGrpc.WalletBlockingStub blockingStubFull = null; - //private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - public static Map utxoMapNote = new ConcurrentHashMap(); - public static List spendUtxoList = new ArrayList<>(); - private static List walletFile = new ArrayList<>(); - private static ShieldWrapper shieldWrapper = new ShieldWrapper(); - Wallet wallet = new Wallet(); - public static volatile Integer witnessNum; - - /** - * constructor. - */ - - + //Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + private static final String FilePath = "Wallet"; + private static final Logger logger = LoggerFactory.getLogger("TestLogger"); + //private WalletGrpc.WalletBlockingStub blockingStubFull = null; + //private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; + public static Map utxoMapNote = new ConcurrentHashMap(); + public static List spendUtxoList = new ArrayList<>(); + private static List walletFile = new ArrayList<>(); + private static ShieldWrapper shieldWrapper = new ShieldWrapper(); + Wallet wallet = new Wallet(); + public static volatile Integer witnessNum; + + /** + * constructor. + */ + + + public static Integer getWitnessNum(WalletGrpc.WalletBlockingStub blockingStubFull) { + if (null == witnessNum) { + witnessNum = PublicMethed.listWitnesses(blockingStubFull) + .get().getWitnessesList().size(); + } - public static Integer getWitnessNum(WalletGrpc.WalletBlockingStub blockingStubFull) { - if (null == witnessNum) { - witnessNum =PublicMethed.listWitnesses(blockingStubFull) - .get().getWitnessesList().size(); + return witnessNum; } - return witnessNum; - } - - public static String createAssetIssueGetTxid(byte[] address, String name, String abbreviation, - Long totalSupply, Integer trxNum, Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setAbbr(ByteString.copyFrom(abbreviation.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return null; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } catch (Exception ex) { - ex.printStackTrace(); - return null; + public static String createAssetIssueGetTxid(byte[] address, String name, String abbreviation, + Long totalSupply, Integer trxNum, Integer icoNum, Long startTime, Long endTime, + Integer voteScore, String description, String url, Long freeAssetNetLimit, + Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; + try { + AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(address)); + builder.setName(ByteString.copyFrom(name.getBytes())); + builder.setAbbr(ByteString.copyFrom(abbreviation.getBytes())); + builder.setTotalSupply(totalSupply); + builder.setTrxNum(trxNum); + builder.setNum(icoNum); + builder.setStartTime(startTime); + builder.setEndTime(endTime); + builder.setVoteScore(voteScore); + builder.setDescription(ByteString.copyFrom(description.getBytes())); + builder.setUrl(ByteString.copyFrom(url.getBytes())); + builder.setFreeAssetNetLimit(freeAssetNetLimit); + builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); + AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply + .newBuilder(); + frozenBuilder.setFrozenAmount(fronzenAmount); + frozenBuilder.setFrozenDays(frozenDay); + builder.addFrozenSupply(0, frozenBuilder); + + Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); + return null; + } + transaction = signTransaction(ecKey, transaction); + + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } catch (Exception ex) { + ex.printStackTrace(); + return null; + } } - } - /** - * constructor. - */ - public static Boolean createAssetIssue(byte[] address, String name, Long totalSupply, - Integer trxNum, Integer icoNum, Long startTime, Long endTime, Integer voteScore, - String description, String url, Long freeAssetNetLimit, Long publicFreeAssetNetLimit, - Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); + /** + * constructor. + */ + public static Boolean createAssetIssue(byte[] address, String name, Long totalSupply, + Integer trxNum, Integer icoNum, Long startTime, Long endTime, Integer voteScore, + String description, String url, Long freeAssetNetLimit, Long publicFreeAssetNetLimit, + Long fronzenAmount, Long frozenDay, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; + try { + AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(address)); + builder.setName(ByteString.copyFrom(name.getBytes())); + builder.setTotalSupply(totalSupply); + builder.setTrxNum(trxNum); + builder.setNum(icoNum); + builder.setStartTime(startTime); + builder.setEndTime(endTime); + builder.setVoteScore(voteScore); + builder.setDescription(ByteString.copyFrom(description.getBytes())); + builder.setUrl(ByteString.copyFrom(url.getBytes())); + builder.setFreeAssetNetLimit(freeAssetNetLimit); + builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); + AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply + .newBuilder(); + frozenBuilder.setFrozenAmount(fronzenAmount); + frozenBuilder.setFrozenDays(frozenDay); + builder.addFrozenSupply(0, frozenBuilder); + + Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); + return false; + } + transaction = signTransaction(ecKey, transaction); + + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + + return response.getResult(); + } catch (Exception ex) { + ex.printStackTrace(); + return false; + } + } - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + /** + * constructor. + */ - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; + public static Boolean createAssetIssue(byte[] address, String name, String abbreviation, + Long totalSupply, Integer trxNum, Integer icoNum, Long startTime, Long endTime, + Integer voteScore, String description, String url, Long freeAssetNetLimit, + Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; + try { + AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(address)); + builder.setName(ByteString.copyFrom(name.getBytes())); + builder.setAbbr(ByteString.copyFrom(abbreviation.getBytes())); + builder.setTotalSupply(totalSupply); + builder.setTrxNum(trxNum); + builder.setNum(icoNum); + builder.setStartTime(startTime); + builder.setEndTime(endTime); + builder.setVoteScore(voteScore); + builder.setDescription(ByteString.copyFrom(description.getBytes())); + builder.setUrl(ByteString.copyFrom(url.getBytes())); + builder.setFreeAssetNetLimit(freeAssetNetLimit); + builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); + AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply + .newBuilder(); + frozenBuilder.setFrozenAmount(fronzenAmount); + frozenBuilder.setFrozenDays(frozenDay); + builder.addFrozenSupply(0, frozenBuilder); + + Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); + return false; + } + transaction = signTransaction(ecKey, transaction); + + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + + return response.getResult(); + } catch (Exception ex) { + ex.printStackTrace(); + return false; + } } - } - /** - * constructor. - */ + /** + * constructor. + */ - public static Boolean createAssetIssue(byte[] address, String name, String abbreviation, - Long totalSupply, Integer trxNum, Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setAbbr(ByteString.copyFrom(abbreviation.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); + public static Boolean createAssetIssue(byte[] address, String name, Long totalSupply, + Integer trxNum, Integer icoNum, int precision, Long startTime, Long endTime, + Integer voteScore, String description, String url, Long freeAssetNetLimit, + Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; + try { + AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(address)); + builder.setName(ByteString.copyFrom(name.getBytes())); + builder.setTotalSupply(totalSupply); + builder.setTrxNum(trxNum); + builder.setNum(icoNum); + builder.setStartTime(startTime); + builder.setEndTime(endTime); + builder.setVoteScore(voteScore); + builder.setPrecision(precision); + builder.setDescription(ByteString.copyFrom(description.getBytes())); + builder.setUrl(ByteString.copyFrom(url.getBytes())); + builder.setFreeAssetNetLimit(freeAssetNetLimit); + builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); + AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply + .newBuilder(); + frozenBuilder.setFrozenAmount(fronzenAmount); + frozenBuilder.setFrozenDays(frozenDay); + builder.addFrozenSupply(0, frozenBuilder); + + Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); + return false; + } + transaction = signTransaction(ecKey, transaction); + + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + + return response.getResult(); + } catch (Exception ex) { + ex.printStackTrace(); + return false; + } + } - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + /** + * constructor. + */ - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; + public static Return createAssetIssue2(byte[] address, String name, Long totalSupply, + Integer trxNum, Integer icoNum, Long startTime, Long endTime, Integer voteScore, + String description, String url, Long freeAssetNetLimit, Long publicFreeAssetNetLimit, + Long fronzenAmount, Long frozenDay, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; + //Protocol.Account search = queryAccount(ecKey, blockingStubFull); + try { + AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(address)); + builder.setName(ByteString.copyFrom(name.getBytes())); + builder.setTotalSupply(totalSupply); + builder.setTrxNum(trxNum); + builder.setNum(icoNum); + builder.setStartTime(startTime); + builder.setEndTime(endTime); + builder.setVoteScore(voteScore); + builder.setDescription(ByteString.copyFrom(description.getBytes())); + builder.setUrl(ByteString.copyFrom(url.getBytes())); + builder.setFreeAssetNetLimit(freeAssetNetLimit); + builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); + //builder.setPublicFreeAssetNetUsage(); + //builder.setPublicLatestFreeNetTime(); + AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply + .newBuilder(); + frozenBuilder.setFrozenAmount(fronzenAmount); + frozenBuilder.setFrozenDays(frozenDay); + builder.addFrozenSupply(0, frozenBuilder); + + TransactionExtention transactionExtention = blockingStubFull + .createAssetIssue2(builder.build()); + + if (transactionExtention == null) { + return transactionExtention.getResult(); + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return ret; + } else { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return transactionExtention.getResult(); + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return response; + } else { + try { + Thread.sleep(3000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + return ret; + } catch (Exception ex) { + ex.printStackTrace(); + //return false; + return Return.getDefaultInstance(); + } } - } - /** - * constructor. - */ + /** + * constructor. + */ - public static Boolean createAssetIssue(byte[] address, String name, Long totalSupply, - Integer trxNum, Integer icoNum, int precision, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setPrecision(precision); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); + public static Account queryAccountByAddress(byte[] address, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString addressBs = ByteString.copyFrom(address); + Account request = Account.newBuilder().setAddress(addressBs).build(); + return blockingStubFull.getAccount(request); + } - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + /** + * constructor. + */ - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; + public static Account queryAccount(byte[] address, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString addressBs = ByteString.copyFrom(address); + Account request = Account.newBuilder().setAddress(addressBs).build(); + return blockingStubFull.getAccount(request); } - } - /** - * constructor. - */ - public static Return createAssetIssue2(byte[] address, String name, Long totalSupply, - Integer trxNum, Integer icoNum, Long startTime, Long endTime, Integer voteScore, - String description, String url, Long freeAssetNetLimit, Long publicFreeAssetNetLimit, - Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(ecKey, blockingStubFull); - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - //builder.setPublicFreeAssetNetUsage(); - //builder.setPublicLatestFreeNetTime(); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - TransactionExtention transactionExtention = blockingStubFull - .createAssetIssue2(builder.build()); - - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); + /** + * constructor. + */ - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return response; - } else { + public static Protocol.Account queryAccount(String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + byte[] address; + ECKey temKey = null; try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; + if (ecKey == null) { + String pubKey = loadPubKey(); //04 PubKey[128] + if (StringUtils.isEmpty(pubKey)) { + logger.warn("Warning: QueryAccount failed, no wallet address !!"); + return null; + } + byte[] pubKeyAsc = pubKey.getBytes(); + byte[] pubKeyHex = Hex.decode(pubKeyAsc); + ecKey = ECKey.fromPublicOnly(pubKeyHex); } - } - return ret; - } catch (Exception ex) { - ex.printStackTrace(); - //return false; - return Return.getDefaultInstance(); + return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); } - } - - /** - * constructor. - */ - public static Account queryAccountByAddress(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } + /** + * constructor. + */ + public static Account queryAccount(byte[] address, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString addressBs = ByteString.copyFrom(address); + Account request = Account.newBuilder().setAddress(addressBs).build(); + return blockingStubFull.getAccount(request); + } - /** - * constructor. - */ + /** + * constructor. + */ - public static Account queryAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } + public static Account getAccountById(String accountId, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString bsAccountId = ByteString.copyFromUtf8(accountId); + Account request = Account.newBuilder().setAccountId(bsAccountId).build(); + return blockingStubFull.getAccountById(request); + } + /** + * constructor. + */ - /** - * constructor. - */ + public static Account getAccountByIdFromSolidity(String accountId, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString bsAccountId = ByteString.copyFromUtf8(accountId); + Account request = Account.newBuilder().setAccountId(bsAccountId).build(); + return blockingStubFull.getAccountById(request); + } - public static Protocol.Account queryAccount(String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); + /** + * constructor. + */ + public static String loadPubKey() { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + char[] buf = new char[0x100]; + return String.valueOf(buf, 32, 130); } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - /** - * constructor. - */ - public static Account queryAccount(byte[] address, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } + /** + * constructor. + */ - /** - * constructor. - */ + public static byte[] getAddress(ECKey ecKey) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - public static Account getAccountById(String accountId, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString bsAccountId = ByteString.copyFromUtf8(accountId); - Account request = Account.newBuilder().setAccountId(bsAccountId).build(); - return blockingStubFull.getAccountById(request); - } + return ecKey.getAddress(); + } - /** - * constructor. - */ + /** + * constructor. + */ - public static Account getAccountByIdFromSolidity(String accountId, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString bsAccountId = ByteString.copyFromUtf8(accountId); - Account request = Account.newBuilder().setAccountId(bsAccountId).build(); - return blockingStubFull.getAccountById(request); - } + public static Protocol.Account grpcQueryAccount(byte[] address, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString addressBs = ByteString.copyFrom(address); + Protocol.Account request = Protocol.Account.newBuilder().setAddress(addressBs).build(); + return blockingStubFull.getAccount(request); + } - /** - * constructor. - */ - public static String loadPubKey() { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } + /** + * constructor. + */ - /** - * constructor. - */ + public static Protocol.Block getBlock(long blockNum, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); + builder.setNum(blockNum); + return blockingStubFull.getBlockByNum(builder.build()); + } - public static byte[] getAddress(ECKey ecKey) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + /** + * constructor. + */ - return ecKey.getAddress(); - } + public static BlockExtention getBlock2(long blockNum, + WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); + builder.setNum(blockNum); + return blockingStubFull.getBlockByNum2(builder.build()); + } - /** - * constructor. - */ + /** + * constructor. + */ - public static Protocol.Account grpcQueryAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Protocol.Account request = Protocol.Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } + public static Protocol.Transaction signTransaction(ECKey ecKey, + Protocol.Transaction transaction) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + if (ecKey == null || ecKey.getPrivKey() == null) { + //logger.warn("Warning: Can't sign,there is no private key !!"); + return null; + } + transaction = TransactionUtils.setTimestamp(transaction); + logger.info("Txid in sign is " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + return TransactionUtils.sign(transaction, ecKey); + } - /** - * constructor. - */ + /** + * constructor. + */ - public static Protocol.Block getBlock(long blockNum, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } + public static Protocol.Transaction signTransactionForShield(ECKey ecKey, + Protocol.Transaction transaction) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + if (ecKey == null || ecKey.getPrivKey() == null) { + //logger.warn("Warning: Can't sign,there is no private key !!"); + return null; + } + logger.info("Txid in sign is " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + return TransactionUtils.sign(transaction, ecKey); + } - /** - * constructor. - */ - public static BlockExtention getBlock2(long blockNum, - WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum2(builder.build()); - } + /** + * constructor. + */ - /** - * constructor. - */ - - public static Protocol.Transaction signTransaction(ECKey ecKey, - Protocol.Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - //logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - logger.info("Txid in sign is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - return TransactionUtils.sign(transaction, ecKey); - } + public static boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, + byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsName = ByteString.copyFrom(assertName); + ByteString bsOwner = ByteString.copyFrom(from); + builder.setToAddress(bsTo); + builder.setAssetName(bsName); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + ParticipateAssetIssueContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } + + /** + * constructor. + */ + + public static Return participateAssetIssue2(byte[] to, byte[] assertName, long amount, + byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsName = ByteString.copyFrom(assertName); + ByteString bsOwner = ByteString.copyFrom(from); + builder.setToAddress(bsTo); + builder.setAssetName(bsName); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + ParticipateAssetIssueContract contract = builder.build(); + + TransactionExtention transactionExtention = blockingStubFull.participateAssetIssue2(contract); + if (transactionExtention == null) { + return transactionExtention.getResult(); + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return ret; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return transactionExtention.getResult(); + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - /** - * constructor. - */ - - public static Protocol.Transaction signTransactionForShield(ECKey ecKey, - Protocol.Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - //logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - logger.info("Txid in sign is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - return TransactionUtils.sign(transaction, ecKey); - } + //Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return response; + } else { + return ret; + } + } - /** - * constructor. - */ - - public static boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, - byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } + /** + * constructor. + */ - /** - * constructor. - */ - - public static Return participateAssetIssue2(byte[] to, byte[] assertName, long amount, - byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.participateAssetIssue2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + byte[] address = addRess; + long frozenBalance = freezeBalance; + long frozenDuration = freezeDuration; + //String priKey = testKey002; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + Protocol.Block currentBlock = blockingStubFull + .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Protocol.Account beforeFronzen = queryAccount(priKey, blockingStubFull); + Long beforeFrozenBalance = 0L; + //Long beforeBandwidth = beforeFronzen.getBandwidth(); + if (beforeFronzen.getFrozenCount() != 0) { + beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); + //beforeBandwidth = beforeFronzen.getBandwidth(); + //logger.info(Long.toString(beforeFronzen.getBandwidth())); + logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); + } - //Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); + FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); + ByteString byteAddreess = ByteString.copyFrom(address); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return response; - } else { - return ret; - } - } + builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) + .setFrozenDuration(frozenDuration); - /** - * constructor. - */ - - public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Protocol.Block currentBlock = blockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Protocol.Account beforeFronzen = queryAccount(priKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); + FreezeBalanceContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction = null"); + return false; + } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + transaction = TransactionUtils.setTimestamp(transaction); + transaction = TransactionUtils.sign(transaction, ecKey); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); + return response.getResult(); /* Long afterBlockNum = 0L; while (afterBlockNum < beforeBlockNum) { @@ -797,219 +798,219 @@ public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long fre logger.info("beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" + afterFrozenBalance.toString()); Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance);*/ - } - - /** - * constructor. - */ - - public static Return freezeBalance2(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Protocol.Block currentBlock = blockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Protocol.Account beforeFronzen = queryAccount(priKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.freezeBalance2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + /** + * constructor. + */ - if (response.getResult() == false) { - return response; - } + public static Return freezeBalance2(byte[] addRess, long freezeBalance, long freezeDuration, + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + byte[] address = addRess; + long frozenBalance = freezeBalance; + long frozenDuration = freezeDuration; + //String priKey = testKey002; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + Protocol.Block currentBlock = blockingStubFull + .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Protocol.Account beforeFronzen = queryAccount(priKey, blockingStubFull); + Long beforeFrozenBalance = 0L; + //Long beforeBandwidth = beforeFronzen.getBandwidth(); + if (beforeFronzen.getFrozenCount() != 0) { + beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); + //beforeBandwidth = beforeFronzen.getBandwidth(); + //logger.info(Long.toString(beforeFronzen.getBandwidth())); + logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); + } - Long afterBlockNum = 0L; + FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); + ByteString byteAddreess = ByteString.copyFrom(address); - while (afterBlockNum < beforeBlockNum) { - Protocol.Block currentBlock1 = blockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); + builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) + .setFrozenDuration(frozenDuration); + + FreezeBalanceContract contract = builder.build(); + + GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.freezeBalance2(contract); + if (transactionExtention == null) { + return transactionExtention.getResult(); + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return ret; + } else { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return transactionExtention.getResult(); + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + + transaction = TransactionUtils.setTimestamp(transaction); + transaction = TransactionUtils.sign(transaction, ecKey); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + + if (response.getResult() == false) { + return response; + } + + Long afterBlockNum = 0L; + + while (afterBlockNum < beforeBlockNum) { + Protocol.Block currentBlock1 = blockingStubFull + .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); + } + + Protocol.Account afterFronzen = queryAccount(priKey, blockingStubFull); + Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); + logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); + logger.info( + "beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" + afterFrozenBalance + .toString()); + Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); + return ret; } - Protocol.Account afterFronzen = queryAccount(priKey, blockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - logger.info( - "beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" + afterFrozenBalance - .toString()); - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - return ret; - } + /** + * constructor. + */ - /** - * constructor. - */ - - public static Boolean unFreezeBalance(byte[] address, String priKey, int resourceCode, - byte[] receiverAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess).setResourceValue(resourceCode); - if (receiverAddress != null) { - ByteString receiverAddressBytes = ByteString.copyFrom(receiverAddress); - builder.setReceiverAddress(receiverAddressBytes); - } - - UnfreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + public static Boolean unFreezeBalance(byte[] address, String priKey, int resourceCode, + byte[] receiverAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract.newBuilder(); + ByteString byteAddreess = ByteString.copyFrom(address); + builder.setOwnerAddress(byteAddreess).setResourceValue(resourceCode); + if (receiverAddress != null) { + ByteString receiverAddressBytes = ByteString.copyFrom(receiverAddress); + builder.setReceiverAddress(receiverAddressBytes); + } - return response.getResult(); - } + UnfreezeBalanceContract contract = builder.build(); + Transaction transaction = blockingStubFull.unfreezeBalance(contract); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - /** - * constructor. - */ - - public static Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - Integer times = 0; - while (times++ <= 2) { - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - continue; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - return false; - } + return response.getResult(); + } - /** - * constructor. - */ - - public static String sendcoinGetTransactionHex(byte[] to, long amount, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - Integer times = 0; - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; + /** + * constructor. + */ + public static Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + //String priKey = testKey002; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + Integer times = 0; + while (times++ <= 2) { + + TransferContract.Builder builder = TransferContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsOwner = ByteString.copyFrom(owner); + builder.setToAddress(bsTo); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction ==null"); + continue; + } + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } + return false; } - transaction = signTransaction(ecKey, transaction); - logger.info("HEX transaction is : " + "transaction hex string is " + ByteArray - .toHexString(transaction.toByteArray())); - return ByteArray.toHexString(transaction.toByteArray()); - } + /** + * constructor. + */ - /** - * constructor. - */ + public static String sendcoinGetTransactionHex(byte[] to, long amount, byte[] owner, + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + Integer times = 0; + TransferContract.Builder builder = TransferContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsOwner = ByteString.copyFrom(owner); + builder.setToAddress(bsTo); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction ==null"); + return null; - public static Boolean cancelDeferredTransactionById(String txid, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + } + transaction = signTransaction(ecKey, transaction); + logger.info("HEX transaction is : " + "transaction hex string is " + ByteArray + .toHexString(transaction.toByteArray())); + return ByteArray.toHexString(transaction.toByteArray()); + } + + + /** + * constructor. + */ + + public static Boolean cancelDeferredTransactionById(String txid, byte[] owner, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; /*Contract.CancelDeferredTransactionContract.Builder builder = Contract .CancelDeferredTransactionContract.newBuilder(); builder.setTransactionId(ByteString.copyFrom(ByteArray.fromHexString(txid))); @@ -1043,549 +1044,549 @@ public static Boolean cancelDeferredTransactionById(String txid, byte[] owner, S .getTxid().toByteArray())); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response.getResult();*/ - return null; - } - - /** - * constructor. - */ - - public static String cancelDeferredTransactionByIdGetTxid(String txid, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - return null; - } - + return null; + } - /** - * constructor. - */ + /** + * constructor. + */ - public static Boolean sendcoinDelayed(byte[] to, long amount, long delaySeconds, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); + public static String cancelDeferredTransactionByIdGetTxid(String txid, byte[] owner, + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + return null; } - final ECKey ecKey = temKey; - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); + /** + * constructor. + */ - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + public static Boolean sendcoinDelayed(byte[] to, long amount, long delaySeconds, byte[] owner, + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } + TransferContract.Builder builder = TransferContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsOwner = ByteString.copyFrom(owner); + builder.setToAddress(bsTo); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); - /** - * constructor. - */ + TransferContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - public static boolean transferAssetDelay(byte[] to, byte[] assertName, long amount, - long delaySeconds, byte[] address, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - logger.info("transaction == null"); - } else { - logger.info("transaction.getRawData().getContractCount() == 0"); - } - return false; + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction ==null"); + return false; + } + transaction = signTransaction(ecKey, transaction); + logger.info("Txid is " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); } - transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - public static String createAccountDelayGetTxid(byte[] ownerAddress, byte[] newAddress, - Long delaySeconds, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + /** + * constructor. + */ - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - Transaction transaction = blockingStubFull.createAccount(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); + public static boolean transferAssetDelay(byte[] to, byte[] assertName, long amount, + long delaySeconds, byte[] address, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsName = ByteString.copyFrom(assertName); + ByteString bsOwner = ByteString.copyFrom(address); + builder.setToAddress(bsTo); + builder.setAssetName(bsName); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferAssetContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); + //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + if (transaction == null) { + logger.info("transaction == null"); + } else { + logger.info("transaction.getRawData().getContractCount() == 0"); + } + return false; + } + transaction = signTransaction(ecKey, transaction); + logger.info("Txid is " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); } - transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - /** - * constructor. - */ - - public static String updateAccountDelayGetTxid(byte[] addressBytes, byte[] accountNameBytes, - Long delaySeconds, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + /** + * constructor. + */ - AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(addressBytes); - ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); + public static String createAccountDelayGetTxid(byte[] ownerAddress, byte[] newAddress, + Long delaySeconds, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setAccountAddress(ByteString.copyFrom(newAddress)); + AccountCreateContract contract = builder.build(); + Transaction transaction = blockingStubFull.createAccount(contract); + //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); + } + transaction = signTransaction(ecKey, transaction); + logger.info("Txid is " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } - builder.setAccountName(bsAccountName); - builder.setOwnerAddress(basAddreess); + /** + * constructor. + */ - AccountUpdateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateAccount(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return null; - } - transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } + public static String updateAccountDelayGetTxid(byte[] addressBytes, byte[] accountNameBytes, + Long delaySeconds, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - /** - * constructor. - */ + AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); + ByteString basAddreess = ByteString.copyFrom(addressBytes); + ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); - public static String unfreezeAssetDelayGetTxid(byte[] address, Long delaySeconds, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess); - - UnfreezeAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.unfreezeAsset(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return null; + builder.setAccountName(bsAccountName); + builder.setOwnerAddress(basAddreess); + + AccountUpdateContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.updateAccount(contract); + //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("Please check!!! transaction == null"); + return null; + } + transaction = signTransaction(ecKey, transaction); + logger.info("Txid is " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } - transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } + /** + * constructor. + */ - /** - * constructor. - */ + public static String unfreezeAssetDelayGetTxid(byte[] address, Long delaySeconds, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - public static String transferAssetDelayGetTxid(byte[] to, byte[] assertName, long amount, - long delaySeconds, byte[] address, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + UnfreezeAssetContract.Builder builder = UnfreezeAssetContract.newBuilder(); + ByteString byteAddreess = ByteString.copyFrom(address); + builder.setOwnerAddress(byteAddreess); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - logger.info("transaction == null"); - } else { - logger.info("transaction.getRawData().getContractCount() == 0"); - } - return null; + UnfreezeAssetContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.unfreezeAsset(contract); + //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("Please check!!! transaction == null"); + return null; + } + transaction = signTransaction(ecKey, transaction); + logger.info("Txid is " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } - transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - /** - * constructor. - */ + /** + * constructor. + */ - public static String sendcoinDelayedGetTxid(byte[] to, long amount, long delaySeconds, - byte[] owner, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); + public static String transferAssetDelayGetTxid(byte[] to, byte[] assertName, long amount, + long delaySeconds, byte[] address, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsName = ByteString.copyFrom(assertName); + ByteString bsOwner = ByteString.copyFrom(address); + builder.setToAddress(bsTo); + builder.setAssetName(bsName); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferAssetContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); + //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + if (transaction == null) { + logger.info("transaction == null"); + } else { + logger.info("transaction.getRawData().getContractCount() == 0"); + } + return null; + } + transaction = signTransaction(ecKey, transaction); + logger.info("Txid is " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } - final ECKey ecKey = temKey; - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); + /** + * constructor. + */ - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + public static String sendcoinDelayedGetTxid(byte[] to, long amount, long delaySeconds, + byte[] owner, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } + TransferContract.Builder builder = TransferContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsOwner = ByteString.copyFrom(owner); + builder.setToAddress(bsTo); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); - /** - * constructor. - */ - - public static String setAccountIdDelayGetTxid(byte[] accountIdBytes, long delaySeconds, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SetAccountIdContract.Builder builder = SetAccountIdContract.newBuilder(); - ByteString bsAddress = ByteString.copyFrom(owner); - ByteString bsAccountId = ByteString.copyFrom(accountIdBytes); - builder.setAccountId(bsAccountId); - builder.setOwnerAddress(bsAddress); - SetAccountIdContract contract = builder.build(); - Transaction transaction = blockingStubFull.setAccountId(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + TransferContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - transaction = signTransaction(ecKey, transaction); + //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction ==null"); + return null; + } + transaction = signTransaction(ecKey, transaction); + logger.info("Txid is " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } + /** + * constructor. + */ - /** - * constructor. - */ + public static String setAccountIdDelayGetTxid(byte[] accountIdBytes, long delaySeconds, + byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + SetAccountIdContract.Builder builder = SetAccountIdContract.newBuilder(); + ByteString bsAddress = ByteString.copyFrom(owner); + ByteString bsAccountId = ByteString.copyFrom(accountIdBytes); + builder.setAccountId(bsAccountId); + builder.setOwnerAddress(bsAddress); + SetAccountIdContract contract = builder.build(); + Transaction transaction = blockingStubFull.setAccountId(contract); + //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); + } + transaction = signTransaction(ecKey, transaction); - public static String updateAssetDelay(byte[] address, byte[] description, byte[] url, - long newLimit, long newPublicLimit, long delaySeconds, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(address); - builder.setDescription(ByteString.copyFrom(description)); - builder.setUrl(ByteString.copyFrom(url)); - builder.setNewLimit(newLimit); - builder.setNewPublicLimit(newPublicLimit); - builder.setOwnerAddress(basAddreess); - - UpdateAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateAsset(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return null; + logger.info("Txid is " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } - transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } + /** + * constructor. + */ - /** - * constructor. - */ - - public static Return sendcoin2(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.createTransaction2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } + public static String updateAssetDelay(byte[] address, byte[] description, byte[] url, + long newLimit, long newPublicLimit, long delaySeconds, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); + ByteString basAddreess = ByteString.copyFrom(address); + builder.setDescription(ByteString.copyFrom(description)); + builder.setUrl(ByteString.copyFrom(url)); + builder.setNewLimit(newLimit); + builder.setNewPublicLimit(newPublicLimit); + builder.setOwnerAddress(basAddreess); + + UpdateAssetContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.updateAsset(contract); + //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + return null; + } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); + transaction = signTransaction(ecKey, transaction); + logger.info("Txid is " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } - return ret; - } + /** + * constructor. + */ - /** - * constructor. - */ + public static Return sendcoin2(byte[] to, long amount, byte[] owner, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + //Protocol.Account search = queryAccount(priKey, blockingStubFull); + + TransferContract.Builder builder = TransferContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsOwner = ByteString.copyFrom(owner); + builder.setToAddress(bsTo); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.createTransaction2(contract); + if (transactionExtention == null) { + return transactionExtention.getResult(); + } - public static String sendcoinGetTransactionId(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return ret; + } else { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + } + + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return transactionExtention.getResult(); + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); + return response; + } + return ret; } - //Test raw data + + /** + * constructor. + */ + + public static String sendcoinGetTransactionId(byte[] to, long amount, byte[] owner, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + //String priKey = testKey002; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + //Protocol.Account search = queryAccount(priKey, blockingStubFull); + + TransferContract.Builder builder = TransferContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsOwner = ByteString.copyFrom(owner); + builder.setToAddress(bsTo); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction ==null"); + return null; + } + //Test raw data /* Protocol.Transaction.raw.Builder builder1 = transaction.getRawData().toBuilder(); builder1.setData(ByteString.copyFromUtf8("12345678")); Transaction.Builder builder2 = transaction.toBuilder(); builder2.setRawData(builder1); transaction = builder2.build();*/ - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - //logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return null; - } else { - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + //logger.info(ByteArray.toStr(response.getMessage().toByteArray())); + return null; + } else { + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } } - } - /** - * constructor. - */ + /** + * constructor. + */ - public static Optional getTransactionById(String txId, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction = blockingStubFull.getTransactionById(request); + public static Optional getTransactionById(String txId, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); + BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); + Transaction transaction = blockingStubFull.getTransactionById(request); - return Optional.ofNullable(transaction); - } + return Optional.ofNullable(transaction); + } - /** - * constructor. - */ + /** + * constructor. + */ - public static Optional getTransactionById(String txId, - WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction = blockingStubFull.getTransactionById(request); - return Optional.ofNullable(transaction); - } + public static Optional getTransactionById(String txId, + WalletGrpc.WalletBlockingStub blockingStubFull) { + ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); + BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); + Transaction transaction = blockingStubFull.getTransactionById(request); + return Optional.ofNullable(transaction); + } - /** - * constructor. - */ - public static Long getAssetBalanceByAssetId(ByteString assetId, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Account assetOwnerAccount = queryAccount(priKey, blockingStubFull); - Long assetOwnerAssetBalance = 0L; - for (String id : assetOwnerAccount.getAssetV2Map().keySet()) { - if (assetId.toStringUtf8().equalsIgnoreCase(id)) { - assetOwnerAssetBalance = assetOwnerAccount.getAssetV2Map().get(id); - } - } - logger.info("asset balance is " + assetOwnerAssetBalance); - return assetOwnerAssetBalance; - } + /** + * constructor. + */ + public static Long getAssetBalanceByAssetId(ByteString assetId, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Account assetOwnerAccount = queryAccount(priKey, blockingStubFull); + Long assetOwnerAssetBalance = 0L; + for (String id : assetOwnerAccount.getAssetV2Map().keySet()) { + if (assetId.toStringUtf8().equalsIgnoreCase(id)) { + assetOwnerAssetBalance = assetOwnerAccount.getAssetV2Map().get(id); + } + } + logger.info("asset balance is " + assetOwnerAssetBalance); + return assetOwnerAssetBalance; + } /* @@ -1602,307 +1603,307 @@ public static Optional getDeferredTransactionById(String tx */ - /** - * constructor. - */ + /** + * constructor. + */ + + public static Optional getTransactionByIdSolidity(String txId, + WalletGrpc.WalletBlockingStub blockingStubSolidity) { + ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); + BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); + Transaction transaction = blockingStubSolidity.getTransactionById(request); + return Optional.ofNullable(transaction); + } + + /** + * constructor. + */ + + public static String printTransaction(Transaction transaction) { + String result = ""; + result += "hash: "; + result += "\n"; + result += ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.toByteArray())); + result += "\n"; + result += "txid: "; + result += "\n"; + result += ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + result += "\n"; + + if (transaction.getRawData() != null) { + result += "raw_data: "; + result += "\n"; + result += "{"; + result += "\n"; + result += printTransactionRow(transaction.getRawData()); + result += "}"; + result += "\n"; + } - public static Optional getTransactionByIdSolidity(String txId, - WalletGrpc.WalletBlockingStub blockingStubSolidity) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction = blockingStubSolidity.getTransactionById(request); - return Optional.ofNullable(transaction); - } + return result; + } - /** - * constructor. - */ - - public static String printTransaction(Transaction transaction) { - String result = ""; - result += "hash: "; - result += "\n"; - result += ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.toByteArray())); - result += "\n"; - result += "txid: "; - result += "\n"; - result += ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - result += "\n"; - - if (transaction.getRawData() != null) { - result += "raw_data: "; - result += "\n"; - result += "{"; - result += "\n"; - result += printTransactionRow(transaction.getRawData()); - result += "}"; - result += "\n"; - } - - return result; - } + /** + * constructor. + */ - /** - * constructor. - */ + public static long printTransactionRow(Transaction.raw raw) { + long timestamp = raw.getTimestamp(); - public static long printTransactionRow(Transaction.raw raw) { - long timestamp = raw.getTimestamp(); + return timestamp; + } - return timestamp; - } + /** + * constructor. + */ - /** - * constructor. - */ - - public static boolean updateAsset(byte[] address, byte[] description, byte[] url, long newLimit, - long newPublicLimit, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(address); - builder.setDescription(ByteString.copyFrom(description)); - builder.setUrl(ByteString.copyFrom(url)); - builder.setNewLimit(newLimit); - builder.setNewPublicLimit(newPublicLimit); - builder.setOwnerAddress(basAddreess); - - UpdateAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateAsset(contract); + public static boolean updateAsset(byte[] address, byte[] description, byte[] url, long newLimit, + long newPublicLimit, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); + ByteString basAddreess = ByteString.copyFrom(address); + builder.setDescription(ByteString.copyFrom(description)); + builder.setUrl(ByteString.copyFrom(url)); + builder.setNewLimit(newLimit); + builder.setNewPublicLimit(newPublicLimit); + builder.setOwnerAddress(basAddreess); + + UpdateAssetContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.updateAsset(contract); + + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + return false; + } - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } + /** + * constructor. + */ - /** - * constructor. - */ - - public static Return updateAsset2(byte[] address, byte[] description, byte[] url, long newLimit, - long newPublicLimit, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(address); - builder.setDescription(ByteString.copyFrom(description)); - builder.setUrl(ByteString.copyFrom(url)); - builder.setNewLimit(newLimit); - builder.setNewPublicLimit(newPublicLimit); - builder.setOwnerAddress(basAddreess); - - UpdateAssetContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.updateAsset2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); + public static Return updateAsset2(byte[] address, byte[] description, byte[] url, long newLimit, + long newPublicLimit, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); + ByteString basAddreess = ByteString.copyFrom(address); + builder.setDescription(ByteString.copyFrom(description)); + builder.setUrl(ByteString.copyFrom(url)); + builder.setNewLimit(newLimit); + builder.setNewPublicLimit(newPublicLimit); + builder.setOwnerAddress(basAddreess); + + UpdateAssetContract contract = builder.build(); + + TransactionExtention transactionExtention = blockingStubFull.updateAsset2(contract); + if (transactionExtention == null) { + return transactionExtention.getResult(); + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return ret; + } else { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return transactionExtention.getResult(); + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + //logger.info(ByteArray.toStr(response.getMessage().toByteArray())); + return response; + } + return ret; } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - //logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } - return ret; - } + /** + * constructor. + */ - /** - * constructor. - */ - - public static boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); + public static boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsName = ByteString.copyFrom(assertName); + ByteString bsOwner = ByteString.copyFrom(address); + builder.setToAddress(bsTo); + builder.setAssetName(bsName); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferAssetContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); + + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + if (transaction == null) { + logger.info("transaction == null"); + } else { + logger.info("transaction.getRawData().getContractCount() == 0"); + } + return false; + } + transaction = signTransaction(ecKey, transaction); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - logger.info("transaction == null"); - } else { - logger.info("transaction.getRawData().getContractCount() == 0"); - } - return false; + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } + /** + * constructor. + */ - /** - * constructor. - */ - - public static boolean updateAccount(byte[] addressBytes, byte[] accountNameBytes, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + public static boolean updateAccount(byte[] addressBytes, byte[] accountNameBytes, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(addressBytes); - ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); + AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); + ByteString basAddreess = ByteString.copyFrom(addressBytes); + ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); - builder.setAccountName(bsAccountName); - builder.setOwnerAddress(basAddreess); + builder.setAccountName(bsAccountName); + builder.setOwnerAddress(basAddreess); - AccountUpdateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateAccount(contract); + AccountUpdateContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.updateAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return false; + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("Please check!!! transaction == null"); + return false; + } + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } + + /** + * constructor. + */ + + public static boolean waitSolidityNodeSynFullNodeData( + WalletGrpc.WalletBlockingStub blockingStubFull, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Block solidityCurrentBlock = blockingStubSolidity + .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Integer wait = 0; + logger.info("Fullnode block num is " + currentBlock.getBlockHeader().getRawData().getNumber()); + + while (solidityCurrentBlock.getBlockHeader().getRawData().getNumber() + < currentBlock.getBlockHeader().getRawData().getNumber() + 1 && wait < ((getWitnessNum(blockingStubFull) >= 27) + ? 27 : getWitnessNum(blockingStubFull) + 1)) { + try { + Thread.sleep(3000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("Soliditynode num is " + solidityCurrentBlock.getBlockHeader().getRawData() + .getNumber()); + solidityCurrentBlock = blockingStubSolidity + .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + if (wait == 24) { + logger.info("Didn't syn,skip to next case."); + return false; + } + wait++; + } + return true; + } + + /** + * constructor. + */ + + public static boolean waitProduceNextBlock(WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + final Long currentNum = currentBlock.getBlockHeader().getRawData().getNumber(); + + Block nextBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); + + Integer wait = 0; + logger.info( + "Block num is " + currentBlock.getBlockHeader().getRawData().getNumber()); + while (nextNum <= currentNum + 1 && wait <= 45) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //logger.info("Wait to produce next block"); + nextBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); + if (wait == 45) { + logger.info("These 45 second didn't produce a block,please check."); + return false; + } + wait++; + } + logger.info("quit normally"); + return true; } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - /** - * constructor. - */ - - public static boolean waitSolidityNodeSynFullNodeData( - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Block solidityCurrentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Integer wait = 0; - logger.info("Fullnode block num is " + currentBlock.getBlockHeader().getRawData().getNumber()); - - while (solidityCurrentBlock.getBlockHeader().getRawData().getNumber() - < currentBlock.getBlockHeader().getRawData().getNumber() + 1 && wait <((getWitnessNum(blockingStubFull) >= 27) - ? 18 : (getWitnessNum(blockingStubFull) * 70 / 100)) ) { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - logger.info("Soliditynode num is " + solidityCurrentBlock.getBlockHeader().getRawData() - .getNumber()); - solidityCurrentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - if (wait == 24) { - logger.info("Didn't syn,skip to next case."); - return false; - } - wait++; - } - return true; - } + /** + * constructor. + */ - /** - * constructor. - */ - - public static boolean waitProduceNextBlock(WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - final Long currentNum = currentBlock.getBlockHeader().getRawData().getNumber(); - - Block nextBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); - - Integer wait = 0; - logger.info( - "Block num is " + currentBlock.getBlockHeader().getRawData().getNumber()); - while (nextNum <= currentNum + 1 && wait <= 45) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - //logger.info("Wait to produce next block"); - nextBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); - if (wait == 45) { - logger.info("These 45 second didn't produce a block,please check."); - return false; - } - wait++; + public static AccountNetMessage getAccountNet(byte[] address, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString addressBs = ByteString.copyFrom(address); + Account request = Account.newBuilder().setAddress(addressBs).build(); + return blockingStubFull.getAccountNet(request); } - logger.info("quit normally"); - return true; - } - - /** - * constructor. - */ - - public static AccountNetMessage getAccountNet(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccountNet(request); - } /* public static byte[] addPreFix(byte[] address) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); @@ -1924,2114 +1925,1545 @@ public static AccountNetMessage getAccountNet(byte[] address, }*/ - /** - * constructor. - */ + /** + * constructor. + */ - public static byte[] getFinalAddress(String priKey) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - WalletClient walletClient; - walletClient = new WalletClient(priKey); - //walletClient.init(0); - return walletClient.getAddress(); - } + public static byte[] getFinalAddress(String priKey) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + WalletClient walletClient; + walletClient = new WalletClient(priKey); + //walletClient.init(0); + return walletClient.getAddress(); + } - /** - * constructor. - */ + /** + * constructor. + */ - public static String createAccountGetTxid(byte[] ownerAddress, byte[] newAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - Transaction transaction = blockingStubFull.createAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - //logger.info("brodacast succesfully"); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + public static String createAccountGetTxid(byte[] ownerAddress, byte[] newAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setAccountAddress(ByteString.copyFrom(newAddress)); + AccountCreateContract contract = builder.build(); + Transaction transaction = blockingStubFull.createAccount(contract); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); + } + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + //logger.info("brodacast succesfully"); + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } } - } - /** - * constructor. - */ + /** + * constructor. + */ - public static boolean createAccount(byte[] ownerAddress, byte[] newAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - Transaction transaction = blockingStubFull.createAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); + public static boolean createAccount(byte[] ownerAddress, byte[] newAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setAccountAddress(ByteString.copyFrom(newAddress)); + AccountCreateContract contract = builder.build(); + Transaction transaction = blockingStubFull.createAccount(contract); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); + } + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - /** - * constructor. - */ + /** + * constructor. + */ - public static Return createAccount2(byte[] ownerAddress, byte[] newAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); + public static Return createAccount2(byte[] ownerAddress, byte[] newAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - TransactionExtention transactionExtention = blockingStubFull.createAccount2(contract); + byte[] owner = ownerAddress; + AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setAccountAddress(ByteString.copyFrom(newAddress)); + AccountCreateContract contract = builder.build(); - if (transactionExtention == null) { - return transactionExtention.getResult(); + TransactionExtention transactionExtention = blockingStubFull.createAccount2(contract); + + if (transactionExtention == null) { + return transactionExtention.getResult(); + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return ret; + } else { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return transactionExtention.getResult(); + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + //logger.info(ByteArray.toStr(response.getMessage().toByteArray())); + return response; + } + return ret; } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - //logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } - return ret; - } + /** + * constructor. + */ - /** - * constructor. - */ + public static boolean voteWitness(byte[] ownerAddress, String priKey, + HashMap witnessMap, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - public static boolean voteWitness(byte[] ownerAddress, String priKey, - HashMap witnessMap, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + byte[] owner = ownerAddress; + VoteWitnessContract.Builder builder = VoteWitnessContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + for (byte[] address : witnessMap.keySet()) { + VoteWitnessContract.Vote.Builder voteBuilder = VoteWitnessContract.Vote.newBuilder(); + voteBuilder.setVoteAddress(ByteString.copyFrom(address)); + voteBuilder.setVoteCount(witnessMap.get(address)); + builder.addVotes(voteBuilder.build()); + } - byte[] owner = ownerAddress; - VoteWitnessContract.Builder builder = VoteWitnessContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - for (byte[] address : witnessMap.keySet()) { - VoteWitnessContract.Vote.Builder voteBuilder = VoteWitnessContract.Vote.newBuilder(); - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(witnessMap.get(address)); - builder.addVotes(voteBuilder.build()); - } + VoteWitnessContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.voteWitnessAccount2(contract); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - VoteWitnessContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.voteWitnessAccount2(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; + return response.getResult(); } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } + /** + * constructor. + */ - /** - * constructor. - */ + public static boolean createProposal(byte[] ownerAddress, String priKey, + HashMap parametersMap, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - public static boolean createProposal(byte[] ownerAddress, String priKey, - HashMap parametersMap, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + byte[] owner = ownerAddress; + ProposalCreateContract.Builder builder = ProposalCreateContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.putAllParameters(parametersMap); - byte[] owner = ownerAddress; - ProposalCreateContract.Builder builder = ProposalCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.putAllParameters(parametersMap); + ProposalCreateContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.proposalCreate(contract); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - ProposalCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalCreate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; + return response.getResult(); } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ + /** + * constructor. + */ - public static boolean approveProposal(byte[] ownerAddress, String priKey, long id, - boolean isAddApproval, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); + public static boolean approveProposal(byte[] ownerAddress, String priKey, long id, + boolean isAddApproval, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + ProposalApproveContract.Builder builder = ProposalApproveContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setProposalId(id); + builder.setIsAddApproval(isAddApproval); + ProposalApproveContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.proposalApprove(contract); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - ProposalApproveContract.Builder builder = ProposalApproveContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setProposalId(id); - builder.setIsAddApproval(isAddApproval); - ProposalApproveContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalApprove(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } + /** + * constructor. + */ - /** - * constructor. - */ + public static boolean deleteProposal(byte[] ownerAddress, String priKey, long id, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - public static boolean deleteProposal(byte[] ownerAddress, String priKey, long id, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalDeleteContract.Builder builder = ProposalDeleteContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setProposalId(id); + byte[] owner = ownerAddress; + ProposalDeleteContract.Builder builder = ProposalDeleteContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setProposalId(id); - ProposalDeleteContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalDelete(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; + ProposalDeleteContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.proposalDelete(contract); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - public static boolean printAddress(String key) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - logger.info(key); - logger.info(ByteArray.toHexString(getFinalAddress(key))); - logger.info(Base58.encode58Check(getFinalAddress(key))); - return true; - } - - /** - * constructor. - */ - - public static String getAddressString(String key) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - return Base58.encode58Check(getFinalAddress(key)); - } - - /** - * constructor. - */ + /** + * constructor. + */ + public static boolean printAddress(String key) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + logger.info(key); + logger.info(ByteArray.toHexString(getFinalAddress(key))); + logger.info(Base58.encode58Check(getFinalAddress(key))); + return true; + } - public static ArrayList getAddressInfo(String key) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ArrayList accountList = new ArrayList(); - accountList.add(key); - accountList.add(ByteArray.toHexString(getFinalAddress(key))); - accountList.add(Base58.encode58Check(getFinalAddress(key))); - return accountList; - } - - /** - * constructor. - */ + /** + * constructor. + */ - public static boolean setAccountId(byte[] accountIdBytes, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SetAccountIdContract.Builder builder = SetAccountIdContract.newBuilder(); - ByteString bsAddress = ByteString.copyFrom(owner); - ByteString bsAccountId = ByteString.copyFrom(accountIdBytes); - builder.setAccountId(bsAccountId); - builder.setOwnerAddress(bsAddress); - SetAccountIdContract contract = builder.build(); - Transaction transaction = blockingStubFull.setAccountId(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); + public static String getAddressString(String key) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + return Base58.encode58Check(getFinalAddress(key)); } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - /** - * constructor. - */ + /** + * constructor. + */ - public static Boolean freezeBalanceGetTronPower(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, ByteString receiverAddress,String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return freezeBalanceForReceiver(addRess,freezeBalance, - freezeDuration,resourceCode,receiverAddress,priKey,blockingStubFull); - } - - /** - * constructor. - */ - public static Boolean freezeBalanceGetEnergy(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); + public static ArrayList getAddressInfo(String key) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ArrayList accountList = new ArrayList(); + accountList.add(key); + accountList.add(ByteArray.toHexString(getFinalAddress(key))); + accountList.add(Base58.encode58Check(getFinalAddress(key))); + return accountList; } - final ECKey ecKey = temKey; - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); + /** + * constructor. + */ - FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; + public static boolean setAccountId(byte[] accountIdBytes, byte[] ownerAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + SetAccountIdContract.Builder builder = SetAccountIdContract.newBuilder(); + ByteString bsAddress = ByteString.copyFrom(owner); + ByteString bsAccountId = ByteString.copyFrom(accountIdBytes); + builder.setAccountId(bsAccountId); + builder.setOwnerAddress(bsAddress); + SetAccountIdContract contract = builder.build(); + Transaction transaction = blockingStubFull.setAccountId(contract); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); + } + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - /** - * constructor. - */ - public static AccountResourceMessage getAccountResource(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccountResource(request); - } + /** + * constructor. + */ - /** - * constructor. - */ - - public static boolean buyStorage(long quantity, byte[] address, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BuyStorageContract.Builder builder = BuyStorageContract.newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddress).setQuant(quantity); - BuyStorageContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.buyStorage(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; + public static Boolean freezeBalanceGetTronPower(byte[] addRess, long freezeBalance, + long freezeDuration, int resourceCode, ByteString receiverAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + return freezeBalanceForReceiver(addRess, freezeBalance, + freezeDuration, resourceCode, receiverAddress, priKey, blockingStubFull); } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - /** - * constructor. - */ - public static boolean sellStorage(long quantity, byte[] address, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - SellStorageContract.Builder builder = SellStorageContract.newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddress).setStorageBytes(quantity); - SellStorageContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.sellStorage(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } + /** + * constructor. + */ - /** - * constructor. - */ - public static byte[] deployContractFallbackReceive(String contractName, String abiString, - String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, - byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi2(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + public static Boolean freezeBalanceGetEnergy(byte[] addRess, long freezeBalance, + long freezeDuration, int resourceCode, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + byte[] address = addRess; + long frozenBalance = freezeBalance; + long frozenDuration = freezeDuration; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); + ByteString byteAddreess = ByteString.copyFrom(address); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - //logger.info("brodacast succesfully"); - return contractAddress; - } - } + builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) + .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); - /** - * constructor. - */ - public static byte[] deployContract(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, - byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + FreezeBalanceContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction = null"); + return false; + } + transaction = TransactionUtils.setTimestamp(transaction); + transaction = TransactionUtils.sign(transaction, ecKey); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); } - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - //logger.info("brodacast succesfully"); - return contractAddress; + /** + * constructor. + */ + public static AccountResourceMessage getAccountResource(byte[] address, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString addressBs = ByteString.copyFrom(address); + Account request = Account.newBuilder().setAddress(addressBs).build(); + return blockingStubFull.getAccountResource(request); } - } - - /** - * constructor. - */ - public static byte[] deployContract(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContract(contractName, abiString, code, data, feeLimit, value, - consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, - blockingStubFull); - } - /** - * constructor. - */ - public static byte[] deployContractFallback(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContractFallbackReceive(contractName, abiString, code, data, feeLimit, value, - consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, - blockingStubFull); - } + /** + * constructor. + */ - /** - * constructor. - */ - - public static byte[] deployContractForLibrary(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - String libraryAddress, String priKey, byte[] ownerAddress, String compilerVersion, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(1000L); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - if (compilerVersion.equals("v5") || compilerVersion.equals("V5")) { - byteCode = replaceLibraryAddresscompilerVersion(code, libraryAddress, "v5"); - } else { - //old version - byteCode = replaceLibraryAddresscompilerVersion(code, libraryAddress, null); - } - - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(0); - contractBuilder.setTokenId(Long.parseLong("0")); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + public static boolean buyStorage(long quantity, byte[] address, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; + BuyStorageContract.Builder builder = BuyStorageContract.newBuilder(); + ByteString byteAddress = ByteString.copyFrom(address); + builder.setOwnerAddress(byteAddress).setQuant(quantity); + BuyStorageContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.buyStorage(contract); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); } - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - //logger.info("brodacast succesfully"); - return contractAddress; - } + /** + * constructor. + */ + public static boolean sellStorage(long quantity, byte[] address, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - } + SellStorageContract.Builder builder = SellStorageContract.newBuilder(); + ByteString byteAddress = ByteString.copyFrom(address); + builder.setOwnerAddress(byteAddress).setStorageBytes(quantity); + SellStorageContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.sellStorage(contract); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } + + /** + * constructor. + */ + public static byte[] deployContractFallbackReceive(String contractName, String abiString, + String code, + String data, Long feeLimit, long value, long consumeUserResourcePercent, + long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, + byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - /** - * constructor. - */ - - public static String deployContractAndGetTransactionInfoById(String contractName, - String abiString, String code, String data, Long feeLimit, long value, - long consumeUserResourcePercent, String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContractAndGetTransactionInfoById(contractName, abiString, code, data, feeLimit, - value, consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, - blockingStubFull); - } + byte[] owner = ownerAddress; + SmartContract.ABI abi = jsonStr2Abi2(abiString); + if (abi == null) { + logger.error("abi is null"); + return null; + } + //byte[] codeBytes = Hex.decode(code); + SmartContract.Builder builder = SmartContract.newBuilder(); + builder.setName(contractName); + builder.setOriginAddress(ByteString.copyFrom(owner)); + builder.setAbi(abi); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + builder.setOriginEnergyLimit(originEnergyLimit); - /** - * constructor. - */ - - public static String deployContractAndGetTransactionInfoById(String contractName, - String abiString, String code, String data, Long feeLimit, long value, - long consumeUserResourcePercent, long originEnergyLimit, String tokenId, long tokenValue, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + if (value != 0) { - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); + builder.setCallValue(value); + } - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - byte[] contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - //logger.info("brodacast succesfully"); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } + byte[] byteCode; + if (null != libraryAddress) { + byteCode = replaceLibraryAddress(code, libraryAddress); + } else { + byteCode = Hex.decode(code); + } + builder.setBytecode(ByteString.copyFrom(byteCode)); + + Builder contractBuilder = CreateSmartContract.newBuilder(); + contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); + contractBuilder.setCallTokenValue(tokenValue); + contractBuilder.setTokenId(Long.parseLong(tokenId)); + CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) + .build(); + + TransactionExtention transactionExtention = blockingStubFull + .deployContract(contractDeployContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return null; + } - /** - * constructor. - */ - - public static SmartContract.ABI jsonStr2Abi(String jsonStr) { - if (jsonStr == null) { - return null; - } - - JsonParser jsonParser = new JsonParser(); - JsonElement jsonElementRoot = jsonParser.parse(jsonStr); - JsonArray jsonRoot = jsonElementRoot.getAsJsonArray(); - SmartContract.ABI.Builder abiBuilder = SmartContract.ABI.newBuilder(); - for (int index = 0; index < jsonRoot.size(); index++) { - JsonElement abiItem = jsonRoot.get(index); - boolean anonymous = - abiItem.getAsJsonObject().get("anonymous") != null && abiItem.getAsJsonObject() - .get("anonymous").getAsBoolean(); - final boolean constant = - abiItem.getAsJsonObject().get("constant") != null && abiItem.getAsJsonObject() - .get("constant").getAsBoolean(); - final String name = - abiItem.getAsJsonObject().get("name") != null ? abiItem.getAsJsonObject().get("name") - .getAsString() : null; - JsonArray inputs = - abiItem.getAsJsonObject().get("inputs") != null ? abiItem.getAsJsonObject().get("inputs") - .getAsJsonArray() : null; - final JsonArray outputs = - abiItem.getAsJsonObject().get("outputs") != null ? abiItem.getAsJsonObject() - .get("outputs").getAsJsonArray() : null; - String type = - abiItem.getAsJsonObject().get("type") != null ? abiItem.getAsJsonObject().get("type") - .getAsString() : null; - final boolean payable = - abiItem.getAsJsonObject().get("payable") != null && abiItem.getAsJsonObject() - .get("payable").getAsBoolean(); - final String stateMutability = - abiItem.getAsJsonObject().get("stateMutability") != null ? abiItem.getAsJsonObject() - .get("stateMutability").getAsString() : null; - if (type == null) { - logger.error("No type!"); - return null; - } - if (!type.equalsIgnoreCase("fallback") && null == inputs) { - logger.error("No inputs!"); - return null; - } - - SmartContract.ABI.Entry.Builder entryBuilder = SmartContract.ABI.Entry.newBuilder(); - entryBuilder.setAnonymous(anonymous); - entryBuilder.setConstant(constant); - if (name != null) { - entryBuilder.setName(name); - } - - /* { inputs : optional } since fallback function not requires inputs*/ - if (inputs != null) { - for (int j = 0; j < inputs.size(); j++) { - JsonElement inputItem = inputs.get(j); - if (inputItem.getAsJsonObject().get("name") == null - || inputItem.getAsJsonObject().get("type") == null) { - logger.error("Input argument invalid due to no name or no type!"); + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() + .toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); + + byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + if (transactionExtention == null) { return null; - } - String inputName = inputItem.getAsJsonObject().get("name").getAsString(); - String inputType = inputItem.getAsJsonObject().get("type").getAsString(); - ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param.newBuilder(); - JsonElement indexed = inputItem.getAsJsonObject().get("indexed"); - - paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); - paramBuilder.setName(inputName); - paramBuilder.setType(inputType); - entryBuilder.addInputs(paramBuilder.build()); - } - } - - /* { outputs : optional } */ - if (outputs != null) { - for (int k = 0; k < outputs.size(); k++) { - JsonElement outputItem = outputs.get(k); - if (outputItem.getAsJsonObject().get("name") == null - || outputItem.getAsJsonObject().get("type") == null) { - logger.error("Output argument invalid due to no name or no type!"); + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); return null; - } - String outputName = outputItem.getAsJsonObject().get("name").getAsString(); - String outputType = outputItem.getAsJsonObject().get("type").getAsString(); - SmartContract.ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param - .newBuilder(); - JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); - - paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); - paramBuilder.setName(outputName); - paramBuilder.setType(outputType); - entryBuilder.addOutputs(paramBuilder.build()); } - } - - entryBuilder.setType(getEntryType(type)); - entryBuilder.setPayable(payable); - if (stateMutability != null) { - entryBuilder.setStateMutability(getStateMutability(stateMutability)); - } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println("txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + contractAddress = generateContractAddress(transaction, owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - abiBuilder.addEntrys(entryBuilder.build()); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + //logger.info("brodacast succesfully"); + return contractAddress; + } } - return abiBuilder.build(); - } + /** + * constructor. + */ + public static byte[] deployContract(String contractName, String abiString, String code, + String data, Long feeLimit, long value, long consumeUserResourcePercent, + long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, + byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - /** - * constructor. - */ - - public static SmartContract.ABI jsonStr2Abi2(String jsonStr) { - if (jsonStr == null) { - return null; - } - - JsonParser jsonParser = new JsonParser(); - JsonElement jsonElementRoot = jsonParser.parse(jsonStr); - JsonArray jsonRoot = jsonElementRoot.getAsJsonArray(); - SmartContract.ABI.Builder abiBuilder = SmartContract.ABI.newBuilder(); - for (int index = 0; index < jsonRoot.size(); index++) { - JsonElement abiItem = jsonRoot.get(index); - boolean anonymous = - abiItem.getAsJsonObject().get("anonymous") != null && abiItem.getAsJsonObject() - .get("anonymous").getAsBoolean(); - final boolean constant = - abiItem.getAsJsonObject().get("constant") != null && abiItem.getAsJsonObject() - .get("constant").getAsBoolean(); - final String name = - abiItem.getAsJsonObject().get("name") != null ? abiItem.getAsJsonObject().get("name") - .getAsString() : null; - JsonArray inputs = - abiItem.getAsJsonObject().get("inputs") != null ? abiItem.getAsJsonObject().get("inputs") - .getAsJsonArray() : null; - final JsonArray outputs = - abiItem.getAsJsonObject().get("outputs") != null ? abiItem.getAsJsonObject() - .get("outputs").getAsJsonArray() : null; - String type = - abiItem.getAsJsonObject().get("type") != null ? abiItem.getAsJsonObject().get("type") - .getAsString() : null; - final boolean payable = - abiItem.getAsJsonObject().get("payable") != null && abiItem.getAsJsonObject() - .get("payable").getAsBoolean(); - final String stateMutability = - abiItem.getAsJsonObject().get("stateMutability") != null ? abiItem.getAsJsonObject() - .get("stateMutability").getAsString() : null; - if (type == null) { - logger.error("No type!"); - return null; - } - if (!type.equalsIgnoreCase("fallback") && !type.equalsIgnoreCase("receive") - && null == inputs) { - logger.error("No inputs!"); - return null; - } - - SmartContract.ABI.Entry.Builder entryBuilder = SmartContract.ABI.Entry.newBuilder(); - entryBuilder.setAnonymous(anonymous); - entryBuilder.setConstant(constant); - if (name != null) { - entryBuilder.setName(name); - } - - /* { inputs : optional } since fallback function not requires inputs*/ - if (inputs != null) { - for (int j = 0; j < inputs.size(); j++) { - JsonElement inputItem = inputs.get(j); - if (inputItem.getAsJsonObject().get("name") == null - || inputItem.getAsJsonObject().get("type") == null) { - logger.error("Input argument invalid due to no name or no type!"); + byte[] owner = ownerAddress; + SmartContract.ABI abi = jsonStr2Abi(abiString); + if (abi == null) { + logger.error("abi is null"); return null; - } - String inputName = inputItem.getAsJsonObject().get("name").getAsString(); - String inputType = inputItem.getAsJsonObject().get("type").getAsString(); - ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param.newBuilder(); - JsonElement indexed = inputItem.getAsJsonObject().get("indexed"); - - paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); - paramBuilder.setName(inputName); - paramBuilder.setType(inputType); - entryBuilder.addInputs(paramBuilder.build()); - } - } - - /* { outputs : optional } */ - if (outputs != null) { - for (int k = 0; k < outputs.size(); k++) { - JsonElement outputItem = outputs.get(k); - if (outputItem.getAsJsonObject().get("name") == null - || outputItem.getAsJsonObject().get("type") == null) { - logger.error("Output argument invalid due to no name or no type!"); - return null; - } - String outputName = outputItem.getAsJsonObject().get("name").getAsString(); - String outputType = outputItem.getAsJsonObject().get("type").getAsString(); - SmartContract.ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param - .newBuilder(); - JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); - - paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); - paramBuilder.setName(outputName); - paramBuilder.setType(outputType); - entryBuilder.addOutputs(paramBuilder.build()); } - } - entryBuilder.setType(getEntryType2(type)); + //byte[] codeBytes = Hex.decode(code); + SmartContract.Builder builder = SmartContract.newBuilder(); + builder.setName(contractName); + builder.setOriginAddress(ByteString.copyFrom(owner)); + builder.setAbi(abi); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + builder.setOriginEnergyLimit(originEnergyLimit); - if (stateMutability != null) { - entryBuilder.setStateMutability(getStateMutability(stateMutability)); - } + if (value != 0) { - abiBuilder.addEntrys(entryBuilder.build()); - } + builder.setCallValue(value); + } - return abiBuilder.build(); - } + byte[] byteCode; + if (null != libraryAddress) { + byteCode = replaceLibraryAddress(code, libraryAddress); + } else { + byteCode = Hex.decode(code); + } + builder.setBytecode(ByteString.copyFrom(byteCode)); + + Builder contractBuilder = CreateSmartContract.newBuilder(); + contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); + contractBuilder.setCallTokenValue(tokenValue); + contractBuilder.setTokenId(Long.parseLong(tokenId)); + CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) + .build(); + + TransactionExtention transactionExtention = blockingStubFull + .deployContract(contractDeployContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return null; + } + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() + .toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); + + byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println("txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + contractAddress = generateContractAddress(transaction, owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - /** - * constructor. - */ - - public static SmartContract.ABI.Entry.EntryType getEntryType(String type) { - switch (type) { - case "constructor": - return SmartContract.ABI.Entry.EntryType.Constructor; - case "function": - return SmartContract.ABI.Entry.EntryType.Function; - case "event": - return SmartContract.ABI.Entry.EntryType.Event; - case "fallback": - return SmartContract.ABI.Entry.EntryType.Fallback; - case "error": - return SmartContract.ABI.Entry.EntryType.Error; - default: - return SmartContract.ABI.Entry.EntryType.UNRECOGNIZED; + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + //logger.info("brodacast succesfully"); + return contractAddress; + } } - } - /** - * constructor. - */ - public static SmartContract.ABI.Entry.EntryType getEntryType2(String type) { - switch (type) { - case "constructor": - return SmartContract.ABI.Entry.EntryType.Constructor; - case "function": - return SmartContract.ABI.Entry.EntryType.Function; - case "event": - return SmartContract.ABI.Entry.EntryType.Event; - case "fallback": - return SmartContract.ABI.Entry.EntryType.Fallback; - case "receive": - return SmartContract.ABI.Entry.EntryType.Receive; - default: - return SmartContract.ABI.Entry.EntryType.UNRECOGNIZED; + /** + * constructor. + */ + public static byte[] deployContract(String contractName, String abiString, String code, + String data, Long feeLimit, long value, long consumeUserResourcePercent, + String libraryAddress, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + return deployContract(contractName, abiString, code, data, feeLimit, value, + consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, + blockingStubFull); } - } - /** - * constructor. - */ - - public static SmartContract.ABI.Entry.StateMutabilityType getStateMutability( - String stateMutability) { - switch (stateMutability) { - case "pure": - return SmartContract.ABI.Entry.StateMutabilityType.Pure; - case "view": - return SmartContract.ABI.Entry.StateMutabilityType.View; - case "nonpayable": - return SmartContract.ABI.Entry.StateMutabilityType.Nonpayable; - case "payable": - return SmartContract.ABI.Entry.StateMutabilityType.Payable; - default: - return SmartContract.ABI.Entry.StateMutabilityType.UNRECOGNIZED; + /** + * constructor. + */ + public static byte[] deployContractFallback(String contractName, String abiString, String code, + String data, Long feeLimit, long value, long consumeUserResourcePercent, + String libraryAddress, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + return deployContractFallbackReceive(contractName, abiString, code, data, feeLimit, value, + consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, + blockingStubFull); } - } - - /** - * constructor. - */ - public static byte[] generateContractAddress(Transaction trx, byte[] owneraddress) { + /** + * constructor. + */ - // get owner address - // this address should be as same as the onweraddress in trx, DONNOT modify it - byte[] ownerAddress = owneraddress; - - // get tx hash - byte[] txRawDataHash = Sha256Hash - .of(CommonParameter.getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()) - .getBytes(); - - // combine - byte[] combined = new byte[txRawDataHash.length + ownerAddress.length]; - System.arraycopy(txRawDataHash, 0, combined, 0, txRawDataHash.length); - System.arraycopy(ownerAddress, 0, combined, txRawDataHash.length, ownerAddress.length); - - return sha3omit12(combined); - - } - - /** - * constructor. - */ + public static byte[] deployContractForLibrary(String contractName, String abiString, String code, + String data, Long feeLimit, long value, long consumeUserResourcePercent, + String libraryAddress, String priKey, byte[] ownerAddress, String compilerVersion, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - public static SmartContract getContract(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString byteString = ByteString.copyFrom(address); - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(byteString).build(); - logger.info("contract name is " + blockingStubFull.getContract(bytesMessage).getName()); - logger.info("contract address is " + WalletClient.encode58Check(address)); - return blockingStubFull.getContract(bytesMessage); - } + byte[] owner = ownerAddress; + SmartContract.ABI abi = jsonStr2Abi(abiString); + if (abi == null) { + logger.error("abi is null"); + return null; + } + //byte[] codeBytes = Hex.decode(code); + SmartContract.Builder builder = SmartContract.newBuilder(); + builder.setName(contractName); + builder.setOriginAddress(ByteString.copyFrom(owner)); + builder.setAbi(abi); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + builder.setOriginEnergyLimit(1000L); - /** - * constructor. - */ - - public static SmartContractDataWrapper getContractInfo(byte[] address, - WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString byteString = ByteString.copyFrom(address); - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(byteString).build(); - logger.info( - "contract name is " + blockingStubFull.getContractInfo(bytesMessage).getSmartContract() - .getName()); - logger.info("contract address is " + WalletClient.encode58Check(address)); - return blockingStubFull.getContractInfo(bytesMessage); - } + if (value != 0) { - private static byte[] replaceLibraryAddress(String code, String libraryAddressPair) { + builder.setCallValue(value); + } - String[] libraryAddressList = libraryAddressPair.split("[,]"); + byte[] byteCode; + if (null != libraryAddress) { + if (compilerVersion.equals("v5") || compilerVersion.equals("V5")) { + byteCode = replaceLibraryAddresscompilerVersion(code, libraryAddress, "v5"); + } else { + //old version + byteCode = replaceLibraryAddresscompilerVersion(code, libraryAddress, null); + } + + } else { + byteCode = Hex.decode(code); + } + builder.setBytecode(ByteString.copyFrom(byteCode)); + + Builder contractBuilder = CreateSmartContract.newBuilder(); + contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); + contractBuilder.setCallTokenValue(0); + contractBuilder.setTokenId(Long.parseLong("0")); + CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) + .build(); + + TransactionExtention transactionExtention = blockingStubFull + .deployContract(contractDeployContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return null; + } - for (int i = 0; i < libraryAddressList.length; i++) { - String cur = libraryAddressList[i]; + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() + .toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); + + byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println("txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + contractAddress = generateContractAddress(transaction, owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - int lastPosition = cur.lastIndexOf(":"); - if (-1 == lastPosition) { - throw new RuntimeException("libraryAddress delimit by ':'"); - } - String libraryName = cur.substring(0, lastPosition); - String addr = cur.substring(lastPosition + 1); - String libraryAddressHex = ByteArray.toHexString(Commons.decodeFromBase58Check(addr)) - .substring(2); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + //logger.info("brodacast succesfully"); + return contractAddress; + } - String repeated = new String(new char[40 - libraryName.length() - 2]).replace("\0", "_"); - String beReplaced = "__" + libraryName + repeated; - Matcher m = Pattern.compile(beReplaced).matcher(code); - code = m.replaceAll(libraryAddressHex); } - return Hex.decode(code); - } - - private static byte[] replaceLibraryAddress_1(String code, byte[] libraryAddress) { - - String libraryAddressHex = ByteArray.toHexString(libraryAddress).substring(2); + /** + * constructor. + */ - Matcher m = Pattern.compile("__.*__").matcher(code); - code = m.replaceAll(libraryAddressHex); - return Hex.decode(code); - } + public static String deployContractAndGetTransactionInfoById(String contractName, + String abiString, String code, String data, Long feeLimit, long value, + long consumeUserResourcePercent, String libraryAddress, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + return deployContractAndGetTransactionInfoById(contractName, abiString, code, data, feeLimit, + value, consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, + blockingStubFull); + } - private static byte[] replaceLibraryAddresscompilerVersion(String code, String libraryAddressPair, - String compilerVersion) { - - String[] libraryAddressList = libraryAddressPair.split("[,]"); - - for (int i = 0; i < libraryAddressList.length; i++) { - String cur = libraryAddressList[i]; - - int lastPosition = cur.lastIndexOf(":"); - if (-1 == lastPosition) { - throw new RuntimeException("libraryAddress delimit by ':'"); - } - String libraryName = cur.substring(0, lastPosition); - String addr = cur.substring(lastPosition + 1); - String libraryAddressHex; - libraryAddressHex = (new String(Hex.encode(Commons.decodeFromBase58Check(addr)), - StandardCharsets.US_ASCII)).substring(2); - - String beReplaced; - if (compilerVersion == null) { - //old version - String repeated = new String(new char[40 - libraryName.length() - 2]).replace("\0", "_"); - beReplaced = "__" + libraryName + repeated; - } else if (compilerVersion.equalsIgnoreCase("v5")) { - //0.5.4 version - String libraryNameKeccak256 = ByteArray.toHexString(sha3(ByteArray.fromString(libraryName))) - .substring(0, 34); - beReplaced = "__\\$" + libraryNameKeccak256 + "\\$__"; - } else { - throw new RuntimeException("unknown compiler version."); - } - - Matcher m = Pattern.compile(beReplaced).matcher(code); - code = m.replaceAll(libraryAddressHex); - } - - return Hex.decode(code); - } + /** + * constructor. + */ - /** - * constructor. - */ + public static String deployContractAndGetTransactionInfoById(String contractName, + String abiString, String code, String data, Long feeLimit, long value, + long consumeUserResourcePercent, long originEnergyLimit, String tokenId, long tokenValue, + String libraryAddress, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - public static boolean updateSetting(byte[] contractAddress, long consumeUserResourcePercent, - String priKey, byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + byte[] owner = ownerAddress; + SmartContract.ABI abi = jsonStr2Abi(abiString); + if (abi == null) { + logger.error("abi is null"); + return null; + } + //byte[] codeBytes = Hex.decode(code); + SmartContract.Builder builder = SmartContract.newBuilder(); + builder.setName(contractName); + builder.setOriginAddress(ByteString.copyFrom(owner)); + builder.setAbi(abi); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + builder.setOriginEnergyLimit(originEnergyLimit); - byte[] owner = ownerAddress; - UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + if (value != 0) { - UpdateSettingContract updateSettingContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateSetting(updateSettingContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } + builder.setCallValue(value); + } - /** - * constructor. - */ + byte[] byteCode; + if (null != libraryAddress) { + byteCode = replaceLibraryAddress(code, libraryAddress); + } else { + byteCode = Hex.decode(code); + } + builder.setBytecode(ByteString.copyFrom(byteCode)); + + Builder contractBuilder = CreateSmartContract.newBuilder(); + contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); + contractBuilder.setCallTokenValue(tokenValue); + contractBuilder.setTokenId(Long.parseLong(tokenId)); + CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) + .build(); + + TransactionExtention transactionExtention = blockingStubFull + .deployContract(contractDeployContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return null; + } - public static boolean updateSettingDelay(byte[] contractAddress, long consumeUserResourcePercent, - long delaySeconds, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() + .toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); - UpdateSettingContract updateSettingContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateSetting(updateSettingContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - /* transactionExtention = TransactionUtils.setDelaySecondsToExtension( - transactionExtention, delaySeconds); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println("txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + byte[] contractAddress = generateContractAddress(transaction, owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + //logger.info("brodacast succesfully"); + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult();*/ - return false; - } - - /** - * constructor. - */ - public static String updateSettingDelayGetTxid(byte[] contractAddress, - long consumeUserResourcePercent, long delaySeconds, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + /** + * constructor. + */ - UpdateSettingContract updateSettingContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateSetting(updateSettingContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - return null; - } + public static SmartContract.ABI jsonStr2Abi(String jsonStr) { + if (jsonStr == null) { + return null; + } - /** - * constructor. - */ - public static String updateEnergyLimitDelayGetTxid(byte[] contractAddress, long originEnergyLimit, - long delaySeconds, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateEnergyLimitContract.Builder builder = UpdateEnergyLimitContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setOriginEnergyLimit(originEnergyLimit); + JsonParser jsonParser = new JsonParser(); + JsonElement jsonElementRoot = jsonParser.parse(jsonStr); + JsonArray jsonRoot = jsonElementRoot.getAsJsonArray(); + SmartContract.ABI.Builder abiBuilder = SmartContract.ABI.newBuilder(); + for (int index = 0; index < jsonRoot.size(); index++) { + JsonElement abiItem = jsonRoot.get(index); + boolean anonymous = + abiItem.getAsJsonObject().get("anonymous") != null && abiItem.getAsJsonObject() + .get("anonymous").getAsBoolean(); + final boolean constant = + abiItem.getAsJsonObject().get("constant") != null && abiItem.getAsJsonObject() + .get("constant").getAsBoolean(); + final String name = + abiItem.getAsJsonObject().get("name") != null ? abiItem.getAsJsonObject().get("name") + .getAsString() : null; + JsonArray inputs = + abiItem.getAsJsonObject().get("inputs") != null ? abiItem.getAsJsonObject().get("inputs") + .getAsJsonArray() : null; + final JsonArray outputs = + abiItem.getAsJsonObject().get("outputs") != null ? abiItem.getAsJsonObject() + .get("outputs").getAsJsonArray() : null; + String type = + abiItem.getAsJsonObject().get("type") != null ? abiItem.getAsJsonObject().get("type") + .getAsString() : null; + final boolean payable = + abiItem.getAsJsonObject().get("payable") != null && abiItem.getAsJsonObject() + .get("payable").getAsBoolean(); + final String stateMutability = + abiItem.getAsJsonObject().get("stateMutability") != null ? abiItem.getAsJsonObject() + .get("stateMutability").getAsString() : null; + if (type == null) { + logger.error("No type!"); + return null; + } + if (!type.equalsIgnoreCase("fallback") && null == inputs) { + logger.error("No inputs!"); + return null; + } + + SmartContract.ABI.Entry.Builder entryBuilder = SmartContract.ABI.Entry.newBuilder(); + entryBuilder.setAnonymous(anonymous); + entryBuilder.setConstant(constant); + if (name != null) { + entryBuilder.setName(name); + } + + /* { inputs : optional } since fallback function not requires inputs*/ + if (inputs != null) { + for (int j = 0; j < inputs.size(); j++) { + JsonElement inputItem = inputs.get(j); + if (inputItem.getAsJsonObject().get("name") == null + || inputItem.getAsJsonObject().get("type") == null) { + logger.error("Input argument invalid due to no name or no type!"); + return null; + } + String inputName = inputItem.getAsJsonObject().get("name").getAsString(); + String inputType = inputItem.getAsJsonObject().get("type").getAsString(); + ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param.newBuilder(); + JsonElement indexed = inputItem.getAsJsonObject().get("indexed"); + + paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); + paramBuilder.setName(inputName); + paramBuilder.setType(inputType); + entryBuilder.addInputs(paramBuilder.build()); + } + } + + /* { outputs : optional } */ + if (outputs != null) { + for (int k = 0; k < outputs.size(); k++) { + JsonElement outputItem = outputs.get(k); + if (outputItem.getAsJsonObject().get("name") == null + || outputItem.getAsJsonObject().get("type") == null) { + logger.error("Output argument invalid due to no name or no type!"); + return null; + } + String outputName = outputItem.getAsJsonObject().get("name").getAsString(); + String outputType = outputItem.getAsJsonObject().get("type").getAsString(); + SmartContract.ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param + .newBuilder(); + JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); + + paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); + paramBuilder.setName(outputName); + paramBuilder.setType(outputType); + entryBuilder.addOutputs(paramBuilder.build()); + } + } + + entryBuilder.setType(getEntryType(type)); + entryBuilder.setPayable(payable); + if (stateMutability != null) { + entryBuilder.setStateMutability(getStateMutability(stateMutability)); + } + + abiBuilder.addEntrys(entryBuilder.build()); + } - UpdateEnergyLimitContract updateEnergyLimitContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateEnergyLimit(updateEnergyLimitContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - //transactionExtention = TransactionUtils.setDelaySecondsToExtension( - // transactionExtention, delaySeconds); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; + return abiBuilder.build(); } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - - - /** - * 61 constructor. - */ - - public static Optional getTransactionInfoById(String txId, - WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - TransactionInfo transactionInfo; - transactionInfo = blockingStubFull.getTransactionInfoById(request); - return Optional.ofNullable(transactionInfo); - } - /** - * 61 constructor. - */ - public static Optional getTransactionInfoByIdFromSolidity(String txId, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - TransactionInfo transactionInfo; - transactionInfo = blockingStubFull.getTransactionInfoById(request); - return Optional.ofNullable(transactionInfo); - } + /** + * constructor. + */ + public static SmartContract.ABI jsonStr2Abi2(String jsonStr) { + if (jsonStr == null) { + return null; + } - /** - * constructor. - */ - public static Optional getTransactionInfoByBlockNum(long blockNum, - WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - TransactionInfoList transactionInfoList; - transactionInfoList = blockingStubFull.getTransactionInfoByBlockNum(builder.build()); - return Optional.ofNullable(transactionInfoList); - } + JsonParser jsonParser = new JsonParser(); + JsonElement jsonElementRoot = jsonParser.parse(jsonStr); + JsonArray jsonRoot = jsonElementRoot.getAsJsonArray(); + SmartContract.ABI.Builder abiBuilder = SmartContract.ABI.newBuilder(); + for (int index = 0; index < jsonRoot.size(); index++) { + JsonElement abiItem = jsonRoot.get(index); + boolean anonymous = + abiItem.getAsJsonObject().get("anonymous") != null && abiItem.getAsJsonObject() + .get("anonymous").getAsBoolean(); + final boolean constant = + abiItem.getAsJsonObject().get("constant") != null && abiItem.getAsJsonObject() + .get("constant").getAsBoolean(); + final String name = + abiItem.getAsJsonObject().get("name") != null ? abiItem.getAsJsonObject().get("name") + .getAsString() : null; + JsonArray inputs = + abiItem.getAsJsonObject().get("inputs") != null ? abiItem.getAsJsonObject().get("inputs") + .getAsJsonArray() : null; + final JsonArray outputs = + abiItem.getAsJsonObject().get("outputs") != null ? abiItem.getAsJsonObject() + .get("outputs").getAsJsonArray() : null; + String type = + abiItem.getAsJsonObject().get("type") != null ? abiItem.getAsJsonObject().get("type") + .getAsString() : null; + final boolean payable = + abiItem.getAsJsonObject().get("payable") != null && abiItem.getAsJsonObject() + .get("payable").getAsBoolean(); + final String stateMutability = + abiItem.getAsJsonObject().get("stateMutability") != null ? abiItem.getAsJsonObject() + .get("stateMutability").getAsString() : null; + if (type == null) { + logger.error("No type!"); + return null; + } + if (!type.equalsIgnoreCase("fallback") && !type.equalsIgnoreCase("receive") + && null == inputs) { + logger.error("No inputs!"); + return null; + } + + SmartContract.ABI.Entry.Builder entryBuilder = SmartContract.ABI.Entry.newBuilder(); + entryBuilder.setAnonymous(anonymous); + entryBuilder.setConstant(constant); + if (name != null) { + entryBuilder.setName(name); + } + + /* { inputs : optional } since fallback function not requires inputs*/ + if (inputs != null) { + for (int j = 0; j < inputs.size(); j++) { + JsonElement inputItem = inputs.get(j); + if (inputItem.getAsJsonObject().get("name") == null + || inputItem.getAsJsonObject().get("type") == null) { + logger.error("Input argument invalid due to no name or no type!"); + return null; + } + String inputName = inputItem.getAsJsonObject().get("name").getAsString(); + String inputType = inputItem.getAsJsonObject().get("type").getAsString(); + ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param.newBuilder(); + JsonElement indexed = inputItem.getAsJsonObject().get("indexed"); + + paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); + paramBuilder.setName(inputName); + paramBuilder.setType(inputType); + entryBuilder.addInputs(paramBuilder.build()); + } + } + + /* { outputs : optional } */ + if (outputs != null) { + for (int k = 0; k < outputs.size(); k++) { + JsonElement outputItem = outputs.get(k); + if (outputItem.getAsJsonObject().get("name") == null + || outputItem.getAsJsonObject().get("type") == null) { + logger.error("Output argument invalid due to no name or no type!"); + return null; + } + String outputName = outputItem.getAsJsonObject().get("name").getAsString(); + String outputType = outputItem.getAsJsonObject().get("type").getAsString(); + SmartContract.ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param + .newBuilder(); + JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); + + paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); + paramBuilder.setName(outputName); + paramBuilder.setType(outputType); + entryBuilder.addOutputs(paramBuilder.build()); + } + } + entryBuilder.setType(getEntryType2(type)); + + if (stateMutability != null) { + entryBuilder.setStateMutability(getStateMutability(stateMutability)); + } + + abiBuilder.addEntrys(entryBuilder.build()); + } - /** - * constructor. - */ - public static Optional getTransactionInfoByBlockNumFromSolidity( - long blockNum, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - TransactionInfoList transactionInfoList; - transactionInfoList = blockingStubSolidity.getTransactionInfoByBlockNum(builder.build()); - return Optional.ofNullable(transactionInfoList); - } + return abiBuilder.build(); + } - /** - * constructor. - */ - public static String triggerContract(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return triggerContract(contractAddress, method, argsStr, isHex, callValue, feeLimit, "0", 0, - ownerAddress, priKey, blockingStubFull); - } - /** - * constructor. - */ + /** + * constructor. + */ - public static String triggerContract(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; + public static SmartContract.ABI.Entry.EntryType getEntryType(String type) { + switch (type) { + case "constructor": + return SmartContract.ABI.Entry.EntryType.Constructor; + case "function": + return SmartContract.ABI.Entry.EntryType.Function; + case "event": + return SmartContract.ABI.Entry.EntryType.Event; + case "fallback": + return SmartContract.ABI.Entry.EntryType.Fallback; + case "error": + return SmartContract.ABI.Entry.EntryType.Error; + default: + return SmartContract.ABI.Entry.EntryType.UNRECOGNIZED; + } } - byte[] owner = ownerAddress; - byte[] input = new byte[0]; - if (!method.equalsIgnoreCase("#")) { - input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); + /** + * constructor. + */ + public static SmartContract.ABI.Entry.EntryType getEntryType2(String type) { + switch (type) { + case "constructor": + return SmartContract.ABI.Entry.EntryType.Constructor; + case "function": + return SmartContract.ABI.Entry.EntryType.Function; + case "event": + return SmartContract.ABI.Entry.EntryType.Event; + case "fallback": + return SmartContract.ABI.Entry.EntryType.Fallback; + case "receive": + return SmartContract.ABI.Entry.EntryType.Receive; + default: + return SmartContract.ABI.Entry.EntryType.UNRECOGNIZED; + } } - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + /** + * constructor. + */ + + public static SmartContract.ABI.Entry.StateMutabilityType getStateMutability( + String stateMutability) { + switch (stateMutability) { + case "pure": + return SmartContract.ABI.Entry.StateMutabilityType.Pure; + case "view": + return SmartContract.ABI.Entry.StateMutabilityType.View; + case "nonpayable": + return SmartContract.ABI.Entry.StateMutabilityType.Nonpayable; + case "payable": + return SmartContract.ABI.Entry.StateMutabilityType.Payable; + default: + return SmartContract.ABI.Entry.StateMutabilityType.UNRECOGNIZED; + } } - } - - - /** - * constructor. - */ - public static String triggerContractBoth(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletGrpc.WalletBlockingStub blockingStubFull1) { - return triggerContractBoth(contractAddress, method, argsStr, isHex, callValue, feeLimit, "0", 0, - ownerAddress, priKey, blockingStubFull, blockingStubFull1); - } - - /** - * constructor. - */ - public static String triggerContractBoth(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - WalletGrpc.WalletBlockingStub blockingStubFull1) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } + /** + * constructor. + */ - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); + public static byte[] generateContractAddress(Transaction trx, byte[] owneraddress) { - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransactionBoth(transaction, blockingStubFull, - blockingStubFull1); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } + // get owner address + // this address should be as same as the onweraddress in trx, DONNOT modify it + byte[] ownerAddress = owneraddress; + // get tx hash + byte[] txRawDataHash = Sha256Hash + .of(CommonParameter.getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()) + .getBytes(); - /** - * constructor. - */ + // combine + byte[] combined = new byte[txRawDataHash.length + ownerAddress.length]; + System.arraycopy(txRawDataHash, 0, combined, 0, txRawDataHash.length); + System.arraycopy(ownerAddress, 0, combined, txRawDataHash.length, ownerAddress.length); - public static String triggerParamListContract(byte[] contractAddress, String method, - List params, Boolean isHex, long callValue, long feeLimit, String tokenId, - long tokenValue, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + return sha3omit12(combined); - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, params)); + /** + * constructor. + */ - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; + public static SmartContract getContract(byte[] address, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString byteString = ByteString.copyFrom(address); + BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(byteString).build(); + logger.info("contract name is " + blockingStubFull.getContract(bytesMessage).getName()); + logger.info("contract address is " + WalletClient.encode58Check(address)); + return blockingStubFull.getContract(bytesMessage); + } + + /** + * constructor. + */ + + public static SmartContractDataWrapper getContractInfo(byte[] address, + WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString byteString = ByteString.copyFrom(address); + BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(byteString).build(); + logger.info( + "contract name is " + blockingStubFull.getContractInfo(bytesMessage).getSmartContract() + .getName()); + logger.info("contract address is " + WalletClient.encode58Check(address)); + return blockingStubFull.getContractInfo(bytesMessage); + } + + private static byte[] replaceLibraryAddress(String code, String libraryAddressPair) { + + String[] libraryAddressList = libraryAddressPair.split("[,]"); + + for (int i = 0; i < libraryAddressList.length; i++) { + String cur = libraryAddressList[i]; + + int lastPosition = cur.lastIndexOf(":"); + if (-1 == lastPosition) { + throw new RuntimeException("libraryAddress delimit by ':'"); + } + String libraryName = cur.substring(0, lastPosition); + String addr = cur.substring(lastPosition + 1); + String libraryAddressHex = ByteArray.toHexString(Commons.decodeFromBase58Check(addr)) + .substring(2); + + String repeated = new String(new char[40 - libraryName.length() - 2]).replace("\0", "_"); + String beReplaced = "__" + libraryName + repeated; + Matcher m = Pattern.compile(beReplaced).matcher(code); + code = m.replaceAll(libraryAddressHex); + } + + return Hex.decode(code); } - transaction = signTransaction(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + + private static byte[] replaceLibraryAddress_1(String code, byte[] libraryAddress) { + + String libraryAddressHex = ByteArray.toHexString(libraryAddress).substring(2); + + Matcher m = Pattern.compile("__.*__").matcher(code); + code = m.replaceAll(libraryAddressHex); + return Hex.decode(code); } + private static byte[] replaceLibraryAddresscompilerVersion(String code, String libraryAddressPair, + String compilerVersion) { - } + String[] libraryAddressList = libraryAddressPair.split("[,]"); - /** - * constructor. - */ + for (int i = 0; i < libraryAddressList.length; i++) { + String cur = libraryAddressList[i]; - public static Boolean exchangeCreate(byte[] firstTokenId, long firstTokenBalance, - byte[] secondTokenId, long secondTokenBalance, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ExchangeCreateContract.Builder builder = ExchangeCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)) - .setFirstTokenId(ByteString.copyFrom(firstTokenId)).setFirstTokenBalance(firstTokenBalance) - .setSecondTokenId(ByteString.copyFrom(secondTokenId)) - .setSecondTokenBalance(secondTokenBalance); - ExchangeCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeCreate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; + int lastPosition = cur.lastIndexOf(":"); + if (-1 == lastPosition) { + throw new RuntimeException("libraryAddress delimit by ':'"); + } + String libraryName = cur.substring(0, lastPosition); + String addr = cur.substring(lastPosition + 1); + String libraryAddressHex; + libraryAddressHex = (new String(Hex.encode(Commons.decodeFromBase58Check(addr)), + StandardCharsets.US_ASCII)).substring(2); + + String beReplaced; + if (compilerVersion == null) { + //old version + String repeated = new String(new char[40 - libraryName.length() - 2]).replace("\0", "_"); + beReplaced = "__" + libraryName + repeated; + } else if (compilerVersion.equalsIgnoreCase("v5")) { + //0.5.4 version + String libraryNameKeccak256 = ByteArray.toHexString(sha3(ByteArray.fromString(libraryName))) + .substring(0, 34); + beReplaced = "__\\$" + libraryNameKeccak256 + "\\$__"; + } else { + throw new RuntimeException("unknown compiler version."); + } + + Matcher m = Pattern.compile(beReplaced).matcher(code); + code = m.replaceAll(libraryAddressHex); + } + + return Hex.decode(code); } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + /** + * constructor. + */ - return response.getResult(); - } + public static boolean updateSetting(byte[] contractAddress, long consumeUserResourcePercent, + String priKey, byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + + UpdateSettingContract updateSettingContract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull + .updateSetting(updateSettingContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return false; + } + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - /** - * constructor. - */ - - public static Boolean injectExchange(long exchangeId, byte[] tokenId, long quant, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ExchangeInjectContract.Builder builder = ExchangeInjectContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); - ExchangeInjectContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeInject(contract); + /** + * constructor. + */ + + public static boolean updateSettingDelay(byte[] contractAddress, long consumeUserResourcePercent, + long delaySeconds, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + + UpdateSettingContract updateSettingContract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull + .updateSetting(updateSettingContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return false; + } + /* transactionExtention = TransactionUtils.setDelaySecondsToExtension( + transactionExtention, delaySeconds); if (transactionExtention == null) { return false; } @@ -4047,3303 +3479,3871 @@ public static Boolean injectExchange(long exchangeId, byte[] tokenId, long quant return false; } System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult();*/ + return false; + } - return response.getResult(); - } + /** + * constructor. + */ - public static Optional getExchangeList( - WalletGrpc.WalletBlockingStub blockingStubFull) { - ExchangeList exchangeList = blockingStubFull.listExchanges(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(exchangeList); - } + public static String updateSettingDelayGetTxid(byte[] contractAddress, + long consumeUserResourcePercent, long delaySeconds, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + + UpdateSettingContract updateSettingContract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull + .updateSetting(updateSettingContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return null; + } + return null; + } + + /** + * constructor. + */ + public static String updateEnergyLimitDelayGetTxid(byte[] contractAddress, long originEnergyLimit, + long delaySeconds, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + UpdateEnergyLimitContract.Builder builder = UpdateEnergyLimitContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setOriginEnergyLimit(originEnergyLimit); + + UpdateEnergyLimitContract updateEnergyLimitContract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull + .updateEnergyLimit(updateEnergyLimitContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return null; + } + //transactionExtention = TransactionUtils.setDelaySecondsToExtension( + // transactionExtention, delaySeconds); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } - /** - * constructor. - */ - public static Optional getExchangeList( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - ExchangeList exchangeList = blockingStubSolidity - .listExchanges(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(exchangeList); - } + /** + * 61 constructor. + */ + public static Optional getTransactionInfoById(String txId, + WalletGrpc.WalletBlockingStub blockingStubFull) { + ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); + BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); + TransactionInfo transactionInfo; + transactionInfo = blockingStubFull.getTransactionInfoById(request); + return Optional.ofNullable(transactionInfo); + } + + /** + * 61 constructor. + */ + public static Optional getTransactionInfoByIdFromSolidity(String txId, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); + BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); + TransactionInfo transactionInfo; + transactionInfo = blockingStubFull.getTransactionInfoById(request); + return Optional.ofNullable(transactionInfo); + } + + + /** + * constructor. + */ + public static Optional getTransactionInfoByBlockNum(long blockNum, + WalletGrpc.WalletBlockingStub blockingStubFull) { + NumberMessage.Builder builder = NumberMessage.newBuilder(); + builder.setNum(blockNum); + TransactionInfoList transactionInfoList; + transactionInfoList = blockingStubFull.getTransactionInfoByBlockNum(builder.build()); + return Optional.ofNullable(transactionInfoList); + } + + /** + * constructor. + */ + public static Optional getTransactionInfoByBlockNumFromSolidity( + long blockNum, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + NumberMessage.Builder builder = NumberMessage.newBuilder(); + builder.setNum(blockNum); + TransactionInfoList transactionInfoList; + transactionInfoList = blockingStubSolidity.getTransactionInfoByBlockNum(builder.build()); + return Optional.ofNullable(transactionInfoList); + } + + /** + * constructor. + */ + public static String triggerContract(byte[] contractAddress, String method, String argsStr, + Boolean isHex, long callValue, long feeLimit, byte[] ownerAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + return triggerContract(contractAddress, method, argsStr, isHex, callValue, feeLimit, "0", 0, + ownerAddress, priKey, blockingStubFull); + } - /** - * constructor. - */ + /** + * constructor. + */ - public static Optional getExchange(String id, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - BytesMessage request = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))).build(); - Exchange exchange = blockingStubSolidity.getExchangeById(request); - return Optional.ofNullable(exchange); - } + public static String triggerContract(byte[] contractAddress, String method, String argsStr, + Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, + byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + if (argsStr.equalsIgnoreCase("#")) { + logger.info("argsstr is #"); + argsStr = ""; + } - /** - * constructor. - */ + byte[] owner = ownerAddress; + byte[] input = new byte[0]; + if (!method.equalsIgnoreCase("#")) { + input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); + } - public static Optional getExchange(String id, - WalletGrpc.WalletBlockingStub blockingStubFull) { - BytesMessage request = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))).build(); - Exchange exchange = blockingStubFull.getExchangeById(request); - return Optional.ofNullable(exchange); - } + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); + + TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create call trx failed!"); + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null + && transactionExtention.getResult() != null) { + byte[] result = transactionExtention.getConstantResult(0).toByteArray(); + System.out.println("message:" + transaction.getRet(0).getRet()); + System.out.println( + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + System.out.println("Result:" + Hex.toHexString(result)); + return null; + } - /** - * constructor. - */ + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() + .toBuilder(); + rawBuilder.setFeeLimit(feeLimit); - public static boolean exchangeWithdraw(long exchangeId, byte[] tokenId, long quant, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - - ExchangeWithdrawContract.Builder builder = ExchangeWithdrawContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); - ExchangeWithdrawContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeWithdraw(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + + transactionExtention = texBuilder.build(); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; + + + /** + * constructor. + */ + public static String triggerContractBoth(byte[] contractAddress, String method, String argsStr, + Boolean isHex, long callValue, long feeLimit, byte[] ownerAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull, + WalletGrpc.WalletBlockingStub blockingStubFull1) { + return triggerContractBoth(contractAddress, method, argsStr, isHex, callValue, feeLimit, "0", 0, + ownerAddress, priKey, blockingStubFull, blockingStubFull1); } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } + /** + * constructor. + */ - /** - * constructor. - */ + public static String triggerContractBoth(byte[] contractAddress, String method, String argsStr, + Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, + byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, + WalletGrpc.WalletBlockingStub blockingStubFull1) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + if (argsStr.equalsIgnoreCase("#")) { + logger.info("argsstr is #"); + argsStr = ""; + } - public static boolean exchangeTransaction(long exchangeId, byte[] tokenId, long quant, - long expected, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - - ExchangeTransactionContract.Builder builder = ExchangeTransactionContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant).setExpected(expected); - ExchangeTransactionContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeTransaction(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; + byte[] owner = ownerAddress; + byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); + + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); + + TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create call trx failed!"); + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null + && transactionExtention.getResult() != null) { + byte[] result = transactionExtention.getConstantResult(0).toByteArray(); + System.out.println("message:" + transaction.getRet(0).getRet()); + System.out.println( + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + System.out.println("Result:" + Hex.toHexString(result)); + return null; + } + + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() + .toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransactionBoth(transaction, blockingStubFull, + blockingStubFull1); + if (response.getResult() == false) { + return null; + } else { + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - /** - * constructor. - */ + /** + * constructor. + */ - public static String deployContractWithConstantParame(String contractName, String abiString, - String code, String constructorStr, String argsStr, String data, Long feeLimit, long value, - long consumeUserResourcePercent, String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContractWithConstantParame(contractName, abiString, code, constructorStr, argsStr, - data, feeLimit, value, consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, - ownerAddress, blockingStubFull); - } + public static String triggerParamListContract(byte[] contractAddress, String method, + List params, Boolean isHex, long callValue, long feeLimit, String tokenId, + long tokenValue, byte[] ownerAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { - /** - * constructor. - */ + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + byte[] input = Hex.decode(AbiUtil.parseMethod(method, params)); + + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); + + TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create call trx failed!"); + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null + && transactionExtention.getResult() != null) { + byte[] result = transactionExtention.getConstantResult(0).toByteArray(); + System.out.println("message:" + transaction.getRet(0).getRet()); + System.out.println( + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + System.out.println("Result:" + Hex.toHexString(result)); + return null; + } + + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() + .toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } - public static String deployContractWithConstantParame(String contractName, String abiString, - String code, String constructorStr, String argsStr, String data, Long feeLimit, long value, - long consumeUserResourcePercent, long originEnergyLimit, String tokenId, long tokenValue, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; } - code += Hex.toHexString(AbiUtil.encodeInput(constructorStr, argsStr)); - byte[] owner = ownerAddress; - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); + /** + * constructor. + */ - if (value != 0) { + public static Boolean exchangeCreate(byte[] firstTokenId, long firstTokenBalance, + byte[] secondTokenId, long secondTokenBalance, byte[] ownerAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - builder.setCallValue(value); - } + byte[] owner = ownerAddress; - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); + ExchangeCreateContract.Builder builder = ExchangeCreateContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)) + .setFirstTokenId(ByteString.copyFrom(firstTokenId)).setFirstTokenBalance(firstTokenBalance) + .setSecondTokenId(ByteString.copyFrom(secondTokenId)) + .setSecondTokenBalance(secondTokenBalance); + ExchangeCreateContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.exchangeCreate(contract); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + System.out.println("txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + + return response.getResult(); } - builder.setBytecode(ByteString.copyFrom(byteCode)); - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + /** + * constructor. + */ - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); + public static Boolean injectExchange(long exchangeId, byte[] tokenId, long quant, + byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - if (transactionExtention == null) { - return null; + byte[] owner = ownerAddress; + + ExchangeInjectContract.Builder builder = ExchangeInjectContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) + .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); + ExchangeInjectContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.exchangeInject(contract); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + System.out.println("txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + + return response.getResult(); } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; + + public static Optional getExchangeList( + WalletGrpc.WalletBlockingStub blockingStubFull) { + ExchangeList exchangeList = blockingStubFull.listExchanges(EmptyMessage.newBuilder().build()); + return Optional.ofNullable(exchangeList); } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; + + /** + * constructor. + */ + + public static Optional getExchangeList( + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + ExchangeList exchangeList = blockingStubSolidity + .listExchanges(EmptyMessage.newBuilder().build()); + return Optional.ofNullable(exchangeList); } - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - byte[] contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - //logger.info("brodacast succesfully"); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + + + /** + * constructor. + */ + + public static Optional getExchange(String id, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + BytesMessage request = BytesMessage.newBuilder() + .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))).build(); + Exchange exchange = blockingStubSolidity.getExchangeById(request); + return Optional.ofNullable(exchange); } - } - /** - * constructor. - */ + /** + * constructor. + */ - public static Boolean freezeBalanceForReceiver(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, ByteString receiverAddressBytes, String priKey, + public static Optional getExchange(String id, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); - if (receiverAddressBytes != null) { - builder.setReceiverAddress(receiverAddressBytes); - } - FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); + BytesMessage request = BytesMessage.newBuilder() + .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))).build(); + Exchange exchange = blockingStubFull.getExchangeById(request); + return Optional.ofNullable(exchange); + } - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; + /** + * constructor. + */ + + public static boolean exchangeWithdraw(long exchangeId, byte[] tokenId, long quant, + byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + byte[] owner = ownerAddress; + + ExchangeWithdrawContract.Builder builder = ExchangeWithdrawContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) + .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); + ExchangeWithdrawContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.exchangeWithdraw(contract); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + System.out.println("txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } + + /** + * constructor. + */ + + public static boolean exchangeTransaction(long exchangeId, byte[] tokenId, long quant, + long expected, byte[] ownerAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + byte[] owner = ownerAddress; + + ExchangeTransactionContract.Builder builder = ExchangeTransactionContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) + .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant).setExpected(expected); + ExchangeTransactionContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.exchangeTransaction(contract); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + System.out.println("txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } + /** + * constructor. + */ - /** - * constructor. - */ + public static String deployContractWithConstantParame(String contractName, String abiString, + String code, String constructorStr, String argsStr, String data, Long feeLimit, long value, + long consumeUserResourcePercent, String libraryAddress, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + return deployContractWithConstantParame(contractName, abiString, code, constructorStr, argsStr, + data, feeLimit, value, consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, + ownerAddress, blockingStubFull); + } - public static Optional getDelegatedResource(byte[] fromAddress, - byte[] toAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString fromAddressBs = ByteString.copyFrom(fromAddress); - ByteString toAddressBs = ByteString.copyFrom(toAddress); + /** + * constructor. + */ - DelegatedResourceMessage request = DelegatedResourceMessage.newBuilder() - .setFromAddress(fromAddressBs).setToAddress(toAddressBs).build(); - DelegatedResourceList delegatedResource = blockingStubFull.getDelegatedResource(request); - return Optional.ofNullable(delegatedResource); - } + public static String deployContractWithConstantParame(String contractName, String abiString, + String code, String constructorStr, String argsStr, String data, Long feeLimit, long value, + long consumeUserResourcePercent, long originEnergyLimit, String tokenId, long tokenValue, + String libraryAddress, String priKey, byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - /** - * constructor. - */ - public static Optional getDelegatedResourceFromSolidity(byte[] fromAddress, - byte[] toAddress, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString fromAddressBs = ByteString.copyFrom(fromAddress); - ByteString toAddressBs = ByteString.copyFrom(toAddress); - - DelegatedResourceMessage request = DelegatedResourceMessage.newBuilder() - .setFromAddress(fromAddressBs).setToAddress(toAddressBs).build(); - DelegatedResourceList delegatedResource = blockingStubFull.getDelegatedResource(request); - return Optional.ofNullable(delegatedResource); - } + SmartContract.ABI abi = jsonStr2Abi(abiString); + if (abi == null) { + logger.error("abi is null"); + return null; + } + code += Hex.toHexString(AbiUtil.encodeInput(constructorStr, argsStr)); + byte[] owner = ownerAddress; + SmartContract.Builder builder = SmartContract.newBuilder(); + builder.setName(contractName); + builder.setOriginAddress(ByteString.copyFrom(owner)); + builder.setAbi(abi); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + builder.setOriginEnergyLimit(originEnergyLimit); - /** - * constructor. - */ + if (value != 0) { - public static Optional getDelegatedResourceAccountIndex( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + builder.setCallValue(value); + } - ByteString addressBs = ByteString.copyFrom(address); + byte[] byteCode; + if (null != libraryAddress) { + byteCode = replaceLibraryAddress(code, libraryAddress); + } else { + byteCode = Hex.decode(code); + } + builder.setBytecode(ByteString.copyFrom(byteCode)); + + Builder contractBuilder = CreateSmartContract.newBuilder(); + contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); + contractBuilder.setCallTokenValue(tokenValue); + contractBuilder.setTokenId(Long.parseLong(tokenId)); + CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) + .build(); + + TransactionExtention transactionExtention = blockingStubFull + .deployContract(contractDeployContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return null; + } - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(addressBs).build(); + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() + .toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); - DelegatedResourceAccountIndex accountIndex = blockingStubFull - .getDelegatedResourceAccountIndex(bytesMessage); - return Optional.ofNullable(accountIndex); - } + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println("txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + byte[] contractAddress = generateContractAddress(transaction, owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + //logger.info("brodacast succesfully"); + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } + } + /** + * constructor. + */ - /** - * constructor. - */ - public static Optional - getDelegatedResourceAccountIndexFromSolidity(byte[] address, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + public static Boolean freezeBalanceForReceiver(byte[] addRess, long freezeBalance, + long freezeDuration, int resourceCode, ByteString receiverAddressBytes, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + byte[] address = addRess; + long frozenBalance = freezeBalance; + long frozenDuration = freezeDuration; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - ByteString addressBs = ByteString.copyFrom(address); + FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); + ByteString byteAddreess = ByteString.copyFrom(address); - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(addressBs).build(); + builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) + .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); + if (receiverAddressBytes != null) { + builder.setReceiverAddress(receiverAddressBytes); + } + FreezeBalanceContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - DelegatedResourceAccountIndex accountIndex = blockingStubFull - .getDelegatedResourceAccountIndex(bytesMessage); - return Optional.ofNullable(accountIndex); - } + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction = null"); + return false; + } + transaction = TransactionUtils.setTimestamp(transaction); + transaction = TransactionUtils.sign(transaction, ecKey); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - /** - * constructor. - */ + /** + * constructor. + */ - public static AssetIssueContract getAssetIssueByName(String assetName, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - return blockingStubFull.getAssetIssueByName(request); - } + public static Optional getDelegatedResource(byte[] fromAddress, + byte[] toAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString fromAddressBs = ByteString.copyFrom(fromAddress); + ByteString toAddressBs = ByteString.copyFrom(toAddress); - /** - * constructor. - */ - public static AssetIssueContract getAssetIssueByNameFromSolidity(String assetName, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - return blockingStubFull.getAssetIssueByName(request); - } + DelegatedResourceMessage request = DelegatedResourceMessage.newBuilder() + .setFromAddress(fromAddressBs).setToAddress(toAddressBs).build(); + DelegatedResourceList delegatedResource = blockingStubFull.getDelegatedResource(request); + return Optional.ofNullable(delegatedResource); + } + /** + * constructor. + */ + public static Optional getDelegatedResourceFromSolidity(byte[] fromAddress, + byte[] toAddress, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString fromAddressBs = ByteString.copyFrom(fromAddress); + ByteString toAddressBs = ByteString.copyFrom(toAddress); - /** - * constructor. - */ + DelegatedResourceMessage request = DelegatedResourceMessage.newBuilder() + .setFromAddress(fromAddressBs).setToAddress(toAddressBs).build(); + DelegatedResourceList delegatedResource = blockingStubFull.getDelegatedResource(request); + return Optional.ofNullable(delegatedResource); + } - public static Optional getAssetIssueListByName(String assetName, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - AssetIssueList assetIssueList = blockingStubFull.getAssetIssueListByName(request); - return Optional.ofNullable(assetIssueList); - } - /** - * constructor. - */ - public static Optional getAssetIssueListByNameFromSolidity(String assetName, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - AssetIssueList assetIssueList = blockingStubFull.getAssetIssueListByName(request); - return Optional.ofNullable(assetIssueList); - } + /** + * constructor. + */ - /** - * constructor. - */ - public static Optional listAssetIssueFromSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - GrpcAPI.AssetIssueList assetIssueList = blockingStubFull - .getAssetIssueList(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(assetIssueList); - } + public static Optional getDelegatedResourceAccountIndex( + byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - /** - * constructor. - */ - public static Optional listAssetIssuepaginatedFromSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull, Long offset, Long limit) { - GrpcAPI.PaginatedMessage.Builder pageMessageBuilder = GrpcAPI.PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - AssetIssueList assetIssueList = blockingStubFull - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - return Optional.ofNullable(assetIssueList); - } + ByteString addressBs = ByteString.copyFrom(address); + BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(addressBs).build(); - /** - * constructor. - */ - public static Optional listWitnesses( - WalletGrpc.WalletBlockingStub blockingStubFull) { - GrpcAPI.WitnessList witnessList = blockingStubFull - .listWitnesses(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(witnessList); - } + DelegatedResourceAccountIndex accountIndex = blockingStubFull + .getDelegatedResourceAccountIndex(bytesMessage); + return Optional.ofNullable(accountIndex); + } - /** - * constructor. - */ - public static Optional listWitnessesFromSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - GrpcAPI.WitnessList witnessList = blockingStubFull - .listWitnesses(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(witnessList); - } + /** + * constructor. + */ + public static Optional + getDelegatedResourceAccountIndexFromSolidity(byte[] address, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - /** - * constructor. - */ + ByteString addressBs = ByteString.copyFrom(address); - public static AssetIssueContract getAssetIssueById(String assetId, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetIdBs = ByteString.copyFrom(assetId.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetIdBs).build(); - return blockingStubFull.getAssetIssueById(request); - } + BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(addressBs).build(); - /** - * constructor. - */ - public static AssetIssueContract getAssetIssueByIdFromSolidity(String assetId, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetIdBs = ByteString.copyFrom(assetId.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetIdBs).build(); - return blockingStubFull.getAssetIssueById(request); - } + DelegatedResourceAccountIndex accountIndex = blockingStubFull + .getDelegatedResourceAccountIndex(bytesMessage); + return Optional.ofNullable(accountIndex); + } - /** - * constructor. - */ - public static Optional getAssetIssueByAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - AssetIssueList assetIssueList = blockingStubFull.getAssetIssueByAccount(request); - return Optional.ofNullable(assetIssueList); - } - private static Permission json2Permission(JSONObject json) { - Permission.Builder permissionBuilder = Permission.newBuilder(); - if (json.containsKey("type")) { - int type = json.getInteger("type"); - permissionBuilder.setTypeValue(type); - } - if (json.containsKey("permission_name")) { - String permissionName = json.getString("permission_name"); - permissionBuilder.setPermissionName(permissionName); - } - if (json.containsKey("threshold")) { - //long threshold = json.getLong("threshold"); - long threshold = Long.parseLong(json.getString("threshold")); - permissionBuilder.setThreshold(threshold); - } - if (json.containsKey("parent_id")) { - int parentId = json.getInteger("parent_id"); - permissionBuilder.setParentId(parentId); - } - if (json.containsKey("operations")) { - byte[] operations = ByteArray.fromHexString(json.getString("operations")); - permissionBuilder.setOperations(ByteString.copyFrom(operations)); - } - if (json.containsKey("keys")) { - JSONArray keys = json.getJSONArray("keys"); - List keyList = new ArrayList<>(); - for (int i = 0; i < keys.size(); i++) { - Key.Builder keyBuilder = Key.newBuilder(); - JSONObject key = keys.getJSONObject(i); - String address = key.getString("address"); - long weight = Long.parseLong(key.getString("weight")); - //long weight = key.getLong("weight"); - //keyBuilder.setAddress(ByteString.copyFrom(address.getBytes())); - keyBuilder.setAddress(ByteString.copyFrom(WalletClient.decodeFromBase58Check(address))); - keyBuilder.setWeight(weight); - keyList.add(keyBuilder.build()); - } - permissionBuilder.addAllKeys(keyList); - } - return permissionBuilder.build(); - } + /** + * constructor. + */ - /** - * constructor. - */ - public static boolean accountPermissionUpdate(String permissionJson, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] priKeys) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownerpermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesspermission = permissions.getJSONObject("witness_permission"); - JSONArray activepermissions = permissions.getJSONArray("active_permissions"); - - if (ownerpermission != null) { - Permission ownerPermission = json2Permission(ownerpermission); - builder.setOwner(ownerPermission); - } - if (witnesspermission != null) { - Permission witnessPermission = json2Permission(witnesspermission); - builder.setWitness(witnessPermission); - } - if (activepermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activepermissions.size(); j++) { - JSONObject permission = activepermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); + public static AssetIssueContract getAssetIssueByName(String assetName, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); + BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); + return blockingStubFull.getAssetIssueByName(request); } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - AccountPermissionUpdateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; + /** + * constructor. + */ + public static AssetIssueContract getAssetIssueByNameFromSolidity(String assetName, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); + BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); + return blockingStubFull.getAssetIssueByName(request); } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - public static long getFreezeBalanceCount(byte[] accountAddress, String ecKey, Long targetEnergy, - WalletGrpc.WalletBlockingStub blockingStubFull) { - //Precision change as the entire network freezes - AccountResourceMessage resourceInfo = getAccountResource(accountAddress, blockingStubFull); - - Account info = queryAccount(accountAddress, blockingStubFull); - Account getAccount = queryAccount(ecKey, blockingStubFull); + /** + * constructor. + */ - long balance = info.getBalance(); - long frozenBalance = info.getAccountResource().getFrozenBalanceForEnergy().getFrozenBalance(); - long totalEnergyLimit = resourceInfo.getTotalEnergyLimit(); - long totalEnergyWeight = resourceInfo.getTotalEnergyWeight(); - long energyUsed = resourceInfo.getEnergyUsed(); - long energyLimit = resourceInfo.getEnergyLimit(); + public static Optional getAssetIssueListByName(String assetName, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); + BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); + AssetIssueList assetIssueList = blockingStubFull.getAssetIssueListByName(request); + return Optional.ofNullable(assetIssueList); + } + + /** + * constructor. + */ + public static Optional getAssetIssueListByNameFromSolidity(String assetName, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); + BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); + AssetIssueList assetIssueList = blockingStubFull.getAssetIssueListByName(request); + return Optional.ofNullable(assetIssueList); + } + + /** + * constructor. + */ + public static Optional listAssetIssueFromSolidity( + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + GrpcAPI.AssetIssueList assetIssueList = blockingStubFull + .getAssetIssueList(EmptyMessage.newBuilder().build()); + return Optional.ofNullable(assetIssueList); + } + + /** + * constructor. + */ + public static Optional listAssetIssuepaginatedFromSolidity( + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull, Long offset, Long limit) { + GrpcAPI.PaginatedMessage.Builder pageMessageBuilder = GrpcAPI.PaginatedMessage.newBuilder(); + pageMessageBuilder.setOffset(offset); + pageMessageBuilder.setLimit(limit); + AssetIssueList assetIssueList = blockingStubFull + .getPaginatedAssetIssueList(pageMessageBuilder.build()); + return Optional.ofNullable(assetIssueList); + } + + + /** + * constructor. + */ + public static Optional listWitnesses( + WalletGrpc.WalletBlockingStub blockingStubFull) { + GrpcAPI.WitnessList witnessList = blockingStubFull + .listWitnesses(EmptyMessage.newBuilder().build()); + return Optional.ofNullable(witnessList); + } + + /** + * constructor. + */ + public static Optional listWitnessesFromSolidity( + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + GrpcAPI.WitnessList witnessList = blockingStubFull + .listWitnesses(EmptyMessage.newBuilder().build()); + return Optional.ofNullable(witnessList); + } + + + /** + * constructor. + */ + + public static AssetIssueContract getAssetIssueById(String assetId, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString assetIdBs = ByteString.copyFrom(assetId.getBytes()); + BytesMessage request = BytesMessage.newBuilder().setValue(assetIdBs).build(); + return blockingStubFull.getAssetIssueById(request); + } - if (energyUsed > energyLimit) { - targetEnergy = energyUsed - energyLimit + targetEnergy; + /** + * constructor. + */ + public static AssetIssueContract getAssetIssueByIdFromSolidity(String assetId, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString assetIdBs = ByteString.copyFrom(assetId.getBytes()); + BytesMessage request = BytesMessage.newBuilder().setValue(assetIdBs).build(); + return blockingStubFull.getAssetIssueById(request); } - if (totalEnergyWeight == 0) { - return 1000_000L; + /** + * constructor. + */ + public static Optional getAssetIssueByAccount(byte[] address, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString addressBs = ByteString.copyFrom(address); + Account request = Account.newBuilder().setAddress(addressBs).build(); + AssetIssueList assetIssueList = blockingStubFull.getAssetIssueByAccount(request); + return Optional.ofNullable(assetIssueList); + } + + private static Permission json2Permission(JSONObject json) { + Permission.Builder permissionBuilder = Permission.newBuilder(); + if (json.containsKey("type")) { + int type = json.getInteger("type"); + permissionBuilder.setTypeValue(type); + } + if (json.containsKey("permission_name")) { + String permissionName = json.getString("permission_name"); + permissionBuilder.setPermissionName(permissionName); + } + if (json.containsKey("threshold")) { + //long threshold = json.getLong("threshold"); + long threshold = Long.parseLong(json.getString("threshold")); + permissionBuilder.setThreshold(threshold); + } + if (json.containsKey("parent_id")) { + int parentId = json.getInteger("parent_id"); + permissionBuilder.setParentId(parentId); + } + if (json.containsKey("operations")) { + byte[] operations = ByteArray.fromHexString(json.getString("operations")); + permissionBuilder.setOperations(ByteString.copyFrom(operations)); + } + if (json.containsKey("keys")) { + JSONArray keys = json.getJSONArray("keys"); + List keyList = new ArrayList<>(); + for (int i = 0; i < keys.size(); i++) { + Key.Builder keyBuilder = Key.newBuilder(); + JSONObject key = keys.getJSONObject(i); + String address = key.getString("address"); + long weight = Long.parseLong(key.getString("weight")); + //long weight = key.getLong("weight"); + //keyBuilder.setAddress(ByteString.copyFrom(address.getBytes())); + keyBuilder.setAddress(ByteString.copyFrom(WalletClient.decodeFromBase58Check(address))); + keyBuilder.setWeight(weight); + keyList.add(keyBuilder.build()); + } + permissionBuilder.addAllKeys(keyList); + } + return permissionBuilder.build(); } - // totalEnergyLimit / (totalEnergyWeight + needBalance) = needEnergy / needBalance - final BigInteger totalEnergyWeightBi = BigInteger.valueOf(totalEnergyWeight); - long needBalance = totalEnergyWeightBi.multiply(BigInteger.valueOf(1_000_000)) - .multiply(BigInteger.valueOf(targetEnergy)) - .divide(BigInteger.valueOf(totalEnergyLimit - targetEnergy)).longValue(); + /** + * constructor. + */ + public static boolean accountPermissionUpdate(String permissionJson, byte[] owner, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull, String[] priKeys) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - logger.info("getFreezeBalanceCount, needBalance: " + needBalance); + AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - if (needBalance < 1000000L) { - needBalance = 1000000L; - logger.info("getFreezeBalanceCount, needBalance less than 1 TRX, modify to: " + needBalance); - } - return needBalance; - } + JSONObject permissions = JSONObject.parseObject(permissionJson); + JSONObject ownerpermission = permissions.getJSONObject("owner_permission"); + JSONObject witnesspermission = permissions.getJSONObject("witness_permission"); + JSONArray activepermissions = permissions.getJSONArray("active_permissions"); - /** - * constructor. - */ - public static Long getAssetIssueValue(byte[] accountAddress, ByteString assetIssueId, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Long assetIssueCount = 0L; - Account contractAccount = queryAccount(accountAddress, blockingStubFull); - Map createAssetIssueMap = contractAccount.getAssetV2Map(); - for (Map.Entry entry : createAssetIssueMap.entrySet()) { - if (assetIssueId.toStringUtf8().equals(entry.getKey())) { - assetIssueCount = entry.getValue(); - } - } - return assetIssueCount; - } + if (ownerpermission != null) { + Permission ownerPermission = json2Permission(ownerpermission); + builder.setOwner(ownerPermission); + } + if (witnesspermission != null) { + Permission witnessPermission = json2Permission(witnesspermission); + builder.setWitness(witnessPermission); + } + if (activepermissions != null) { + List activePermissionList = new ArrayList<>(); + for (int j = 0; j < activepermissions.size(); j++) { + JSONObject permission = activepermissions.getJSONObject(j); + activePermissionList.add(json2Permission(permission)); + } + builder.addAllActives(activePermissionList); + } + builder.setOwnerAddress(ByteString.copyFrom(owner)); - /** - * constructor. - */ - public static List getStrings(byte[] data) { - int index = 0; - List ret = new ArrayList<>(); - while (index < data.length) { - ret.add(byte2HexStr(data, index, 32)); - index += 32; - } - return ret; - } + AccountPermissionUpdateContract contract = builder.build(); - /** - * constructor. - */ - public static String byte2HexStr(byte[] b, int offset, int length) { - StringBuilder ssBuilder = new StringBuilder(); - for (int n = offset; n < offset + length && n < b.length; n++) { - String stmp = Integer.toHexString(b[n] & 0xFF); - ssBuilder.append((stmp.length() == 1) ? "0" + stmp : stmp); + TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); } - return ssBuilder.toString().toUpperCase().trim(); - } - /** - * constructor. - */ - public static Transaction addTransactionSign(Transaction transaction, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - Transaction.Builder transactionBuilderSigned = transaction.toBuilder(); - byte[] hash = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()); - - ECDSASignature signature = ecKey.sign(hash); - ByteString bsSign = ByteString.copyFrom(signature.toByteArray()); - transactionBuilderSigned.addSignature(bsSign); - transaction = transactionBuilderSigned.build(); - return transaction; - } + /** + * constructor. + */ + public static long getFreezeBalanceCount(byte[] accountAddress, String ecKey, Long targetEnergy, + WalletGrpc.WalletBlockingStub blockingStubFull) { + //Precision change as the entire network freezes + AccountResourceMessage resourceInfo = getAccountResource(accountAddress, blockingStubFull); - /** - * constructor. - */ - public static GrpcAPI.Return deployContractAndGetResponse(String contractName, String abiString, - String code, String data, Long feeLimit, long value, long consumeUserResourcePercent, - long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, - byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + Account info = queryAccount(accountAddress, blockingStubFull); - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); + Account getAccount = queryAccount(ecKey, blockingStubFull); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - byte[] contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + long balance = info.getBalance(); + long frozenBalance = info.getAccountResource().getFrozenBalanceForEnergy().getFrozenBalance(); + long totalEnergyLimit = resourceInfo.getTotalEnergyLimit(); + long totalEnergyWeight = resourceInfo.getTotalEnergyWeight(); + long energyUsed = resourceInfo.getEnergyUsed(); + long energyLimit = resourceInfo.getEnergyLimit(); - return response; - } + if (energyUsed > energyLimit) { + targetEnergy = energyUsed - energyLimit + targetEnergy; + } - /** - * constructor. - */ - public static GrpcAPI.Return triggerContractAndGetResponse(byte[] contractAddress, String method, - String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response; - } + if (totalEnergyWeight == 0) { + return 1000_000L; + } - /** - * constructor. - */ - public static boolean updateEnergyLimit(byte[] contractAddress, long originEnergyLimit, - String priKey, byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateEnergyLimitContract.Builder builder = UpdateEnergyLimitContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setOriginEnergyLimit(originEnergyLimit); + // totalEnergyLimit / (totalEnergyWeight + needBalance) = needEnergy / needBalance + final BigInteger totalEnergyWeightBi = BigInteger.valueOf(totalEnergyWeight); + long needBalance = totalEnergyWeightBi.multiply(BigInteger.valueOf(1_000_000)) + .multiply(BigInteger.valueOf(targetEnergy)) + .divide(BigInteger.valueOf(totalEnergyLimit - targetEnergy)).longValue(); - UpdateEnergyLimitContract updateEnergyLimitContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateEnergyLimit(updateEnergyLimitContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; + logger.info("getFreezeBalanceCount, needBalance: " + needBalance); + + if (needBalance < 1000000L) { + needBalance = 1000000L; + logger.info("getFreezeBalanceCount, needBalance less than 1 TRX, modify to: " + needBalance); + } + return needBalance; } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; + + /** + * constructor. + */ + public static Long getAssetIssueValue(byte[] accountAddress, ByteString assetIssueId, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Long assetIssueCount = 0L; + Account contractAccount = queryAccount(accountAddress, blockingStubFull); + Map createAssetIssueMap = contractAccount.getAssetV2Map(); + for (Map.Entry entry : createAssetIssueMap.entrySet()) { + if (assetIssueId.toStringUtf8().equals(entry.getKey())) { + assetIssueCount = entry.getValue(); + } + } + return assetIssueCount; + } + + /** + * constructor. + */ + public static List getStrings(byte[] data) { + int index = 0; + List ret = new ArrayList<>(); + while (index < data.length) { + ret.add(byte2HexStr(data, index, 32)); + index += 32; + } + return ret; } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - /** - * constructor. - */ - public static GrpcAPI.Return accountPermissionUpdateForResponse(String permissionJson, - byte[] owner, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownerpermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesspermission = permissions.getJSONObject("witness_permission"); - JSONArray activepermissions = permissions.getJSONArray("active_permissions"); - - if (ownerpermission != null) { - Permission ownerPermission = json2Permission(ownerpermission); - builder.setOwner(ownerPermission); - } - if (witnesspermission != null) { - Permission witnessPermission = json2Permission(witnesspermission); - builder.setWitness(witnessPermission); - } - if (activepermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activepermissions.size(); j++) { - JSONObject permission = activepermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); + /** + * constructor. + */ + public static String byte2HexStr(byte[] b, int offset, int length) { + StringBuilder ssBuilder = new StringBuilder(); + for (int n = offset; n < offset + length && n < b.length; n++) { + String stmp = Integer.toHexString(b[n] & 0xFF); + ssBuilder.append((stmp.length() == 1) ? "0" + stmp : stmp); + } + return ssBuilder.toString().toUpperCase().trim(); } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - AccountPermissionUpdateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return ret; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + /** + * constructor. + */ + public static Transaction addTransactionSign(Transaction transaction, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; + + Transaction.Builder transactionBuilderSigned = transaction.toBuilder(); + byte[] hash = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()); + + ECDSASignature signature = ecKey.sign(hash); + ByteString bsSign = ByteString.copyFrom(signature.toByteArray()); + transactionBuilderSigned.addSignature(bsSign); + transaction = transactionBuilderSigned.build(); + return transaction; + } + + /** + * constructor. + */ + public static GrpcAPI.Return deployContractAndGetResponse(String contractName, String abiString, + String code, String data, Long feeLimit, long value, long consumeUserResourcePercent, + long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, + byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - return response; - } + byte[] owner = ownerAddress; + SmartContract.ABI abi = jsonStr2Abi(abiString); + if (abi == null) { + logger.error("abi is null"); + return null; + } + //byte[] codeBytes = Hex.decode(code); + SmartContract.Builder builder = SmartContract.newBuilder(); + builder.setName(contractName); + builder.setOriginAddress(ByteString.copyFrom(owner)); + builder.setAbi(abi); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + builder.setOriginEnergyLimit(originEnergyLimit); - public static TransactionApprovedList getTransactionApprovedList(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return blockingStubFull.getTransactionApprovedList(transaction); - } + if (value != 0) { - /** - * constructor. - */ - public static long getFreezeBalanceNetCount(byte[] accountAddress, String ecKey, Long targetNet, - WalletGrpc.WalletBlockingStub blockingStubFull) { - //Precision change as the entire network freezes - AccountResourceMessage resourceInfo = getAccountResource(accountAddress, blockingStubFull); + builder.setCallValue(value); + } - Account info = queryAccount(accountAddress, blockingStubFull); + byte[] byteCode; + if (null != libraryAddress) { + byteCode = replaceLibraryAddress(code, libraryAddress); + } else { + byteCode = Hex.decode(code); + } + builder.setBytecode(ByteString.copyFrom(byteCode)); + + Builder contractBuilder = CreateSmartContract.newBuilder(); + contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); + contractBuilder.setCallTokenValue(tokenValue); + contractBuilder.setTokenId(Long.parseLong(tokenId)); + CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) + .build(); + + TransactionExtention transactionExtention = blockingStubFull + .deployContract(contractDeployContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return null; + } - Account getAccount = queryAccount(ecKey, blockingStubFull); + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() + .toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); - long balance = info.getBalance(); - long totalNetLimit = resourceInfo.getTotalNetLimit(); - long totalNetWeight = resourceInfo.getTotalNetWeight(); - long netUsed = resourceInfo.getNetUsed(); - long netLimit = resourceInfo.getNetLimit(); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println("txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + byte[] contractAddress = generateContractAddress(transaction, owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (netUsed > netLimit) { - targetNet = netUsed - netLimit + targetNet; + return response; } - if (totalNetWeight == 0) { - return 1000_000L; + /** + * constructor. + */ + public static GrpcAPI.Return triggerContractAndGetResponse(byte[] contractAddress, String method, + String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, + byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + if (argsStr.equalsIgnoreCase("#")) { + logger.info("argsstr is #"); + argsStr = ""; + } + + byte[] owner = ownerAddress; + byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); + + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); + + TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create call trx failed!"); + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null + && transactionExtention.getResult() != null) { + byte[] result = transactionExtention.getConstantResult(0).toByteArray(); + System.out.println("message:" + transaction.getRet(0).getRet()); + System.out.println( + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + System.out.println("Result:" + Hex.toHexString(result)); + return null; + } + + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() + .toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response; } - // totalNetLimit / (totalNetWeight + needBalance) = needNet / needBalance - final BigInteger totalNetWeightBi = BigInteger.valueOf(totalNetWeight); - long needBalance = totalNetWeightBi.multiply(BigInteger.valueOf(1_000_000)) - .multiply(BigInteger.valueOf(targetNet)) - .divide(BigInteger.valueOf(totalNetLimit - targetNet)).longValue(); + /** + * constructor. + */ + public static boolean updateEnergyLimit(byte[] contractAddress, long originEnergyLimit, + String priKey, byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + UpdateEnergyLimitContract.Builder builder = UpdateEnergyLimitContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setOriginEnergyLimit(originEnergyLimit); + + UpdateEnergyLimitContract updateEnergyLimitContract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull + .updateEnergyLimit(updateEnergyLimitContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return false; + } + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } + + /** + * constructor. + */ + public static GrpcAPI.Return accountPermissionUpdateForResponse(String permissionJson, + byte[] owner, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); + + JSONObject permissions = JSONObject.parseObject(permissionJson); + JSONObject ownerpermission = permissions.getJSONObject("owner_permission"); + JSONObject witnesspermission = permissions.getJSONObject("witness_permission"); + JSONArray activepermissions = permissions.getJSONArray("active_permissions"); + + if (ownerpermission != null) { + Permission ownerPermission = json2Permission(ownerpermission); + builder.setOwner(ownerPermission); + } + if (witnesspermission != null) { + Permission witnessPermission = json2Permission(witnesspermission); + builder.setWitness(witnessPermission); + } + if (activepermissions != null) { + List activePermissionList = new ArrayList<>(); + for (int j = 0; j < activepermissions.size(); j++) { + JSONObject permission = activepermissions.getJSONObject(j); + activePermissionList.add(json2Permission(permission)); + } + builder.addAllActives(activePermissionList); + } + builder.setOwnerAddress(ByteString.copyFrom(owner)); + + AccountPermissionUpdateContract contract = builder.build(); + + TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return ret; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return ret; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - logger.info("getFreezeBalanceNetCount, needBalance: " + needBalance); + return response; + } - if (needBalance < 1000000L) { - needBalance = 1000000L; - logger - .info("getFreezeBalanceNetCount, needBalance less than 1 TRX, modify to: " + needBalance); + public static TransactionApprovedList getTransactionApprovedList(Transaction transaction, + WalletGrpc.WalletBlockingStub blockingStubFull) { + return blockingStubFull.getTransactionApprovedList(transaction); } - return needBalance; - } - /** - * constructor. - */ - public static GrpcAPI.Return broadcastTransaction(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull) { - int i = 10; - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - while (!response.getResult() && response.getCode() == response_code.SERVER_BUSY - && i > 0) { - try { - Thread.sleep(300); - } catch (InterruptedException e) { - e.printStackTrace(); - } - i--; - response = blockingStubFull.broadcastTransaction(transaction); - logger.info("repeate times = " + (10 - i)); - } - - if (response.getResult() == false) { - logger.info("Code = " + response.getCode()); - logger.info("Message = " + response.getMessage().toStringUtf8()); - } - return response; - } + /** + * constructor. + */ + public static long getFreezeBalanceNetCount(byte[] accountAddress, String ecKey, Long targetNet, + WalletGrpc.WalletBlockingStub blockingStubFull) { + //Precision change as the entire network freezes + AccountResourceMessage resourceInfo = getAccountResource(accountAddress, blockingStubFull); - /** - * constructor. - */ - public static GrpcAPI.Return broadcastTransactionBoth(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletGrpc.WalletBlockingStub blockingStubFull1) { - int i = 10; - waitProduceNextBlock(blockingStubFull1); - GrpcAPI.Return response = blockingStubFull1.broadcastTransaction(transaction); - GrpcAPI.Return response1 = blockingStubFull.broadcastTransaction(transaction); - while (response.getResult() == false && response.getCode() == response_code.SERVER_BUSY - && i > 0) { - try { - Thread.sleep(300); - } catch (InterruptedException e) { - e.printStackTrace(); - } - i--; - response = blockingStubFull.broadcastTransaction(transaction); - logger.info("repeate times = " + (10 - i)); - } - - if (response.getResult() == false) { - logger.info("Code = " + response.getCode()); - logger.info("Message = " + response.getMessage().toStringUtf8()); - } - return response; - } + Account info = queryAccount(accountAddress, blockingStubFull); - /** - * constructor. - */ - public static String exec(String command) throws InterruptedException { - String returnString = ""; - Process pro = null; - Runtime runTime = Runtime.getRuntime(); - if (runTime == null) { - logger.error("Create runtime false!"); - } - try { - pro = runTime.exec(command); - BufferedReader input = new BufferedReader(new InputStreamReader(pro.getInputStream())); - PrintWriter output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream())); - String line; - while ((line = input.readLine()) != null) { - returnString = returnString + line + "\n"; - } - input.close(); - output.close(); - pro.destroy(); - } catch (IOException ex) { - logger.error(null, ex); - } - return returnString; - } + Account getAccount = queryAccount(ecKey, blockingStubFull); - /** - * constructor. - */ - public static HashMap getBycodeAbiNoOptimize(String solFile, String contractName) { - final String compile = Configuration.getByPath("testng.conf") - .getString("defaultParameter.solidityCompile"); - - String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); - String outputPath = "src/test/resources/soliditycode//output" + dirPath; - - File binFile = new File(outputPath + "/" + contractName + ".bin"); - File abiFile = new File(outputPath + "/" + contractName + ".abi"); - if (binFile.exists()) { - binFile.delete(); - } - if (abiFile.exists()) { - abiFile.delete(); - } - - HashMap retMap = new HashMap<>(); - String absolutePath = System.getProperty("user.dir"); - logger.debug("absolutePath: " + absolutePath); - logger.debug("solFile: " + solFile); - logger.debug("outputPath: " + outputPath); - String cmd = - compile + " --bin --abi --overwrite " + absolutePath + "/" - + solFile + " -o " - + absolutePath + "/" + outputPath; - logger.info("cmd: " + cmd); - - String byteCode = null; - String abI = null; - - // compile solidity file - try { - exec(cmd); - } catch (InterruptedException e) { - e.printStackTrace(); - } - // get byteCode and ABI - try { - byteCode = fileRead(outputPath + "/" + contractName + ".bin", false); - retMap.put("byteCode", byteCode); - logger.debug("byteCode: " + byteCode); - abI = fileRead(outputPath + "/" + contractName + ".abi", false); - retMap.put("abI", abI); - logger.debug("abI: " + abI); - } catch (Exception e) { - e.printStackTrace(); - } - return retMap; - } + long balance = info.getBalance(); + long totalNetLimit = resourceInfo.getTotalNetLimit(); + long totalNetWeight = resourceInfo.getTotalNetWeight(); + long netUsed = resourceInfo.getNetUsed(); + long netLimit = resourceInfo.getNetLimit(); - /** - * constructor. - */ - public static HashMap getBycodeAbi(String solFile, String contractName) { - final String compile = Configuration.getByPath("testng.conf") - .getString("defaultParameter.solidityCompile"); - - String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); - String outputPath = "src/test/resources/soliditycode//output" + dirPath; - - File binFile = new File(outputPath + "/" + contractName + ".bin"); - File abiFile = new File(outputPath + "/" + contractName + ".abi"); - if (binFile.exists()) { - binFile.delete(); - } - if (abiFile.exists()) { - abiFile.delete(); - } - - HashMap retMap = new HashMap<>(); - String absolutePath = System.getProperty("user.dir"); - logger.debug("absolutePath: " + absolutePath); - logger.debug("solFile: " + solFile); - logger.debug("outputPath: " + outputPath); - String cmd = - compile + " --optimize --bin --abi --overwrite " + absolutePath + "/" - + solFile + " -o " - + absolutePath + "/" + outputPath; - logger.info("cmd: " + cmd); - - String byteCode = null; - String abI = null; - - // compile solidity file - try { - exec(cmd); - } catch (InterruptedException e) { - e.printStackTrace(); - } - // get byteCode and ABI - try { - byteCode = fileRead(outputPath + "/" + contractName + ".bin", false); - retMap.put("byteCode", byteCode); - logger.debug("byteCode: " + byteCode); - abI = fileRead(outputPath + "/" + contractName + ".abi", false); - retMap.put("abI", abI); - logger.debug("abI: " + abI); - } catch (Exception e) { - e.printStackTrace(); - } - return retMap; - } + if (netUsed > netLimit) { + targetNet = netUsed - netLimit + targetNet; + } - /** - * constructor. - */ - public static String fileRead(String filePath, boolean isLibrary) throws Exception { - File file = new File(filePath); - FileReader reader = new FileReader(file); - BufferedReader breader = new BufferedReader(reader); - StringBuilder sb = new StringBuilder(); - String s = ""; - if (!isLibrary) { - if ((s = breader.readLine()) != null) { - sb.append(s); - } - breader.close(); - } else { - String fistLine = breader.readLine(); - breader.readLine(); - if ((s = breader.readLine()) != null && !s.equals("")) { - s = s.substring(s.indexOf("-> ") + 3); - sb.append(s + ":"); - } else { - s = fistLine.substring(fistLine.indexOf("__") + 2, fistLine.lastIndexOf("__")); - sb.append(s + ":"); - } - breader.close(); - } - return sb.toString(); - } + if (totalNetWeight == 0) { + return 1000_000L; + } - /** - * constructor. - */ - public static HashMap getBycodeAbiForLibrary(String solFile, - String contractName) { - HashMap retMap = null; - String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); - String outputPath = "src/test/resources/soliditycode/output" + dirPath; - try { - retMap = PublicMethed.getBycodeAbi(solFile, contractName); - String library = fileRead(outputPath + "/" + contractName + ".bin", true); - retMap.put("library", library); - logger.debug("library: " + library); - } catch (Exception e) { - e.printStackTrace(); - } - - return retMap; - } + // totalNetLimit / (totalNetWeight + needBalance) = needNet / needBalance + final BigInteger totalNetWeightBi = BigInteger.valueOf(totalNetWeight); + long needBalance = totalNetWeightBi.multiply(BigInteger.valueOf(1_000_000)) + .multiply(BigInteger.valueOf(targetNet)) + .divide(BigInteger.valueOf(totalNetLimit - targetNet)).longValue(); - /** - * constructor. - */ - public static String triggerConstantContract(byte[] contractAddress, String method, - String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); + logger.info("getFreezeBalanceNetCount, needBalance: " + needBalance); - TransactionExtention transactionExtention = blockingStubFull - .triggerConstantContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; + if (needBalance < 1000000L) { + needBalance = 1000000L; + logger + .info("getFreezeBalanceNetCount, needBalance less than 1 TRX, modify to: " + needBalance); + } + return needBalance; } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; + + /** + * constructor. + */ + public static GrpcAPI.Return broadcastTransaction(Transaction transaction, + WalletGrpc.WalletBlockingStub blockingStubFull) { + int i = 10; + GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); + while (!response.getResult() && response.getCode() == response_code.SERVER_BUSY + && i > 0) { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + i--; + response = blockingStubFull.broadcastTransaction(transaction); + logger.info("repeate times = " + (10 - i)); + } + + if (response.getResult() == false) { + logger.info("Code = " + response.getCode()); + logger.info("Message = " + response.getMessage().toStringUtf8()); + } + return response; } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; + + /** + * constructor. + */ + public static GrpcAPI.Return broadcastTransactionBoth(Transaction transaction, + WalletGrpc.WalletBlockingStub blockingStubFull, + WalletGrpc.WalletBlockingStub blockingStubFull1) { + int i = 10; + waitProduceNextBlock(blockingStubFull1); + GrpcAPI.Return response = blockingStubFull1.broadcastTransaction(transaction); + GrpcAPI.Return response1 = blockingStubFull.broadcastTransaction(transaction); + while (response.getResult() == false && response.getCode() == response_code.SERVER_BUSY + && i > 0) { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + i--; + response = blockingStubFull.broadcastTransaction(transaction); + logger.info("repeate times = " + (10 - i)); + } + + if (response.getResult() == false) { + logger.info("Code = " + response.getCode()); + logger.info("Message = " + response.getMessage().toStringUtf8()); + } + return response; } - transaction = signTransaction(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + + /** + * constructor. + */ + public static String exec(String command) throws InterruptedException { + String returnString = ""; + Process pro = null; + Runtime runTime = Runtime.getRuntime(); + if (runTime == null) { + logger.error("Create runtime false!"); + } + try { + pro = runTime.exec(command); + BufferedReader input = new BufferedReader(new InputStreamReader(pro.getInputStream())); + PrintWriter output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream())); + String line; + while ((line = input.readLine()) != null) { + returnString = returnString + line + "\n"; + } + input.close(); + output.close(); + pro.destroy(); + } catch (IOException ex) { + logger.error(null, ex); + } + return returnString; } - } - /** - * constructor. - */ - public static TransactionExtention triggerConstantContractForExtentionOnSolidity( - byte[] contractAddress, String method, String argsStr, Boolean isHex, long callValue, - long feeLimit, String tokenId, long tokenValue, byte[] ownerAddress, String priKey, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); + /** + * constructor. + */ + public static HashMap getBycodeAbiNoOptimize(String solFile, String contractName) { + final String compile = Configuration.getByPath("testng.conf") + .getString("defaultParameter.solidityCompile"); - TransactionExtention transactionExtention = blockingStubSolidity - .triggerConstantContract(triggerContract); - return transactionExtention; + String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); + String outputPath = "src/test/resources/soliditycode//output" + dirPath; - } + File binFile = new File(outputPath + "/" + contractName + ".bin"); + File abiFile = new File(outputPath + "/" + contractName + ".abi"); + if (binFile.exists()) { + binFile.delete(); + } + if (abiFile.exists()) { + abiFile.delete(); + } - /** - * constructor. - */ - public static String clearContractAbi(byte[] contractAddress, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); + HashMap retMap = new HashMap<>(); + String absolutePath = System.getProperty("user.dir"); + logger.debug("absolutePath: " + absolutePath); + logger.debug("solFile: " + solFile); + logger.debug("outputPath: " + outputPath); + String cmd = + compile + " --bin --abi --overwrite " + absolutePath + "/" + + solFile + " -o " + + absolutePath + "/" + outputPath; + logger.info("cmd: " + cmd); + + String byteCode = null; + String abI = null; + + // compile solidity file + try { + exec(cmd); + } catch (InterruptedException e) { + e.printStackTrace(); + } + // get byteCode and ABI + try { + byteCode = fileRead(outputPath + "/" + contractName + ".bin", false); + retMap.put("byteCode", byteCode); + logger.debug("byteCode: " + byteCode); + abI = fileRead(outputPath + "/" + contractName + ".abi", false); + retMap.put("abI", abI); + logger.debug("abI: " + abI); + } catch (Exception e) { + e.printStackTrace(); + } + return retMap; } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; + /** + * constructor. + */ + public static HashMap getBycodeAbi(String solFile, String contractName) { + final String compile = Configuration.getByPath("testng.conf") + .getString("defaultParameter.solidityCompile"); - ClearABIContract.Builder builder = ClearABIContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); + String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); + String outputPath = "src/test/resources/soliditycode//output" + dirPath; - ClearABIContract clearAbiContract = builder.build(); + File binFile = new File(outputPath + "/" + contractName + ".bin"); + File abiFile = new File(outputPath + "/" + contractName + ".abi"); + if (binFile.exists()) { + binFile.delete(); + } + if (abiFile.exists()) { + abiFile.delete(); + } - TransactionExtention transactionExtention = blockingStubFull.clearContractABI(clearAbiContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; + HashMap retMap = new HashMap<>(); + String absolutePath = System.getProperty("user.dir"); + logger.debug("absolutePath: " + absolutePath); + logger.debug("solFile: " + solFile); + logger.debug("outputPath: " + outputPath); + String cmd = + compile + " --optimize --bin --abi --overwrite " + absolutePath + "/" + + solFile + " -o " + + absolutePath + "/" + outputPath; + logger.info("cmd: " + cmd); + + String byteCode = null; + String abI = null; + + // compile solidity file + try { + exec(cmd); + } catch (InterruptedException e) { + e.printStackTrace(); + } + // get byteCode and ABI + try { + byteCode = fileRead(outputPath + "/" + contractName + ".bin", false); + retMap.put("byteCode", byteCode); + logger.debug("byteCode: " + byteCode); + abI = fileRead(outputPath + "/" + contractName + ".abi", false); + retMap.put("abI", abI); + logger.debug("abI: " + abI); + } catch (Exception e) { + e.printStackTrace(); + } + return retMap; } - transaction = signTransaction(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + + /** + * constructor. + */ + public static String fileRead(String filePath, boolean isLibrary) throws Exception { + File file = new File(filePath); + FileReader reader = new FileReader(file); + BufferedReader breader = new BufferedReader(reader); + StringBuilder sb = new StringBuilder(); + String s = ""; + if (!isLibrary) { + if ((s = breader.readLine()) != null) { + sb.append(s); + } + breader.close(); + } else { + String fistLine = breader.readLine(); + breader.readLine(); + if ((s = breader.readLine()) != null && !s.equals("")) { + s = s.substring(s.indexOf("-> ") + 3); + sb.append(s + ":"); + } else { + s = fistLine.substring(fistLine.indexOf("__") + 2, fistLine.lastIndexOf("__")); + sb.append(s + ":"); + } + breader.close(); + } + return sb.toString(); } - } - /** - * constructor. - */ - public static TransactionExtention clearContractAbiForExtention(byte[] contractAddress, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); + /** + * constructor. + */ + public static HashMap getBycodeAbiForLibrary(String solFile, + String contractName) { + HashMap retMap = null; + String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); + String outputPath = "src/test/resources/soliditycode/output" + dirPath; + try { + retMap = PublicMethed.getBycodeAbi(solFile, contractName); + String library = fileRead(outputPath + "/" + contractName + ".bin", true); + retMap.put("library", library); + logger.debug("library: " + library); + } catch (Exception e) { + e.printStackTrace(); + } + + return retMap; } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; + /** + * constructor. + */ + public static String triggerConstantContract(byte[] contractAddress, String method, + String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, + byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + if (argsStr.equalsIgnoreCase("#")) { + logger.info("argsstr is #"); + argsStr = ""; + } - ClearABIContract.Builder builder = ClearABIContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); + byte[] owner = ownerAddress; + byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); + + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); + + TransactionExtention transactionExtention = blockingStubFull + .triggerConstantContract(triggerContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create call trx failed!"); + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null + && transactionExtention.getResult() != null) { + byte[] result = transactionExtention.getConstantResult(0).toByteArray(); + System.out.println("message:" + transaction.getRet(0).getRet()); + System.out.println( + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + System.out.println("Result:" + Hex.toHexString(result)); + return null; + } + + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() + .toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } + } - ClearABIContract clearAbiContract = builder.build(); + /** + * constructor. + */ + public static TransactionExtention triggerConstantContractForExtentionOnSolidity( + byte[] contractAddress, String method, String argsStr, Boolean isHex, long callValue, + long feeLimit, String tokenId, long tokenValue, byte[] ownerAddress, String priKey, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + if (argsStr.equalsIgnoreCase("#")) { + logger.info("argsstr is #"); + argsStr = ""; + } - TransactionExtention transactionExtention = blockingStubFull.clearContractABI(clearAbiContract); - return transactionExtention; + byte[] owner = ownerAddress; + byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - } + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); - /** - * constructor. - */ - public static TransactionExtention triggerConstantContractForExtention(byte[] contractAddress, - String method, String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, - long tokenValue, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - if (tokenId.equalsIgnoreCase("") || tokenId.equalsIgnoreCase("#")) { - logger.info("tokenid is 0"); - tokenId = "0"; - - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .triggerConstantContract(triggerContract); - return transactionExtention; + TransactionExtention transactionExtention = blockingStubSolidity + .triggerConstantContract(triggerContract); + return transactionExtention; + } - } + /** + * constructor. + */ + public static String clearContractAbi(byte[] contractAddress, byte[] ownerAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - /** - * constructor. - */ - public static TransactionExtention triggerSolidityContractForExtention(byte[] contractAddress, - String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, - String priKey, WalletSolidityGrpc.WalletSolidityBlockingStub solidityBlockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); + byte[] owner = ownerAddress; - TransactionExtention transactionExtention = solidityBlockingStubFull - .triggerConstantContract(triggerContract); - return transactionExtention; + ClearABIContract.Builder builder = ClearABIContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); - } + ClearABIContract clearAbiContract = builder.build(); - /** - * constructor. - */ + TransactionExtention transactionExtention = blockingStubFull.clearContractABI(clearAbiContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create call trx failed!"); + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null + && transactionExtention.getResult() != null) { + byte[] result = transactionExtention.getConstantResult(0).toByteArray(); + System.out.println("message:" + transaction.getRet(0).getRet()); + System.out.println( + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + System.out.println("Result:" + Hex.toHexString(result)); + return null; + } - public static TransactionExtention triggerContractForExtention(byte[] contractAddress, - String method, String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, - long tokenValue, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() + .toBuilder(); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } } - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); + /** + * constructor. + */ + public static TransactionExtention clearContractAbiForExtention(byte[] contractAddress, + byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); + byte[] owner = ownerAddress; - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - return transactionExtention; + ClearABIContract.Builder builder = ClearABIContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); - } + ClearABIContract clearAbiContract = builder.build(); - /** - * constructor. - */ - public static String create2(String[] parameters) { - if (parameters == null || parameters.length != 3) { - logger.error("create2 needs 3 parameter:\ncreate2 address code salt"); - return null; - } + TransactionExtention transactionExtention = blockingStubFull.clearContractABI(clearAbiContract); + return transactionExtention; - byte[] address = WalletClient.decodeFromBase58Check(parameters[0]); - if (!WalletClient.addressValid(address)) { - logger.error("length of address must be 21 bytes."); - return null; } - byte[] code = Hex.decode(parameters[1]); - byte[] temp = Longs.toByteArray(Long.parseLong(parameters[2])); - if (temp.length != 8) { - logger.error("Invalid salt!"); - return null; - } - byte[] salt = new byte[32]; - System.arraycopy(temp, 0, salt, 24, 8); + /** + * constructor. + */ + public static TransactionExtention triggerConstantContractForExtention(byte[] contractAddress, + String method, String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, + long tokenValue, byte[] ownerAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + if (argsStr.equalsIgnoreCase("#")) { + logger.info("argsstr is #"); + argsStr = ""; + } + if (tokenId.equalsIgnoreCase("") || tokenId.equalsIgnoreCase("#")) { + logger.info("tokenid is 0"); + tokenId = "0"; - byte[] mergedData = ByteUtil.merge(address, salt, sha3(code)); - String create2Address = Base58.encode58Check(sha3omit12(mergedData)); + } - logger.info("create2 Address: " + create2Address); + byte[] owner = ownerAddress; + byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull + .triggerConstantContract(triggerContract); + return transactionExtention; + + + } + + /** + * constructor. + */ + public static TransactionExtention triggerSolidityContractForExtention(byte[] contractAddress, + String method, String argsStr, + Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, + byte[] ownerAddress, + String priKey, WalletSolidityGrpc.WalletSolidityBlockingStub solidityBlockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + if (argsStr.equalsIgnoreCase("#")) { + logger.info("argsstr is #"); + argsStr = ""; + } - return create2Address; - } + byte[] owner = ownerAddress; + byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); - /** - * constructor. - */ - public static boolean sendShieldCoin(byte[] publicZenTokenOwnerAddress, long fromAmount, - ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, - byte[] publicZenTokenToAddress, long toAmount, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - PrivateParameters.Builder builder = PrivateParameters.newBuilder(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); - builder.setFromAmount(fromAmount); - } - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); - builder.setToAmount(toAmount); - } - - if (shieldAddressInfo != null) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - - //String shieldAddress = noteInfo.getPaymentAddress(); - //ShieldAddressInfo addressInfo = - // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - builder.setAsk(ByteString.copyFrom(expandedSpendingKey.getAsk())); - builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); - builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); - } catch (Exception e) { - System.out.println(e); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - //System.out.println("address " + noteInfo.getPaymentAddress()); - //System.out.println("value " + noteInfo.getValue()); - //System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); - //System.out.println("trxId " + noteInfo.getTrxId()); - //System.out.println("index " + noteInfo.getIndex()); - //System.out.println("meno " + new String(noteInfo.getMemo())); - - SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); - spendNoteBuilder.setNote(noteBuild.build()); - try { - spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - - IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); - spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); - spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); - - builder.addShieldedSpends(spendNoteBuilder.build()); - - } else { - byte[] ovk = ByteArray - .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - builder.setOvk(ByteString.copyFrom(ovk)); - } - - if (shieldOutputList.size() > 0) { - for (int i = 0; i < shieldOutputList.size(); ++i) { - builder - .addShieldedReceives(ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); - } - } + TransactionExtention transactionExtention = solidityBlockingStubFull + .triggerConstantContract(triggerContract); + return transactionExtention; - TransactionExtention transactionExtention = blockingStubFull - .createShieldedTransaction(builder.build()); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - Any any = transaction.getRawData().getContract(0).getParameter(); - - try { - ShieldedTransferContract shieldedTransferContract = any - .unpack(ShieldedTransferContract.class); - if (shieldedTransferContract.getFromAmount() > 0 || fromAmount == 321321) { - transaction = signTransactionForShield(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - } else { - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - } - } catch (Exception e) { - System.out.println(e); } - return broadcastTransaction(transaction, blockingStubFull).getResult(); - } - /** - * constructor. - */ - public static boolean sendShieldCoinWithoutAsk(byte[] publicZenTokenOwnerAddress, long fromAmount, - ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, - byte[] publicZenTokenToAddress, long toAmount, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - PrivateParametersWithoutAsk.Builder builder = PrivateParametersWithoutAsk.newBuilder(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); - builder.setFromAmount(fromAmount); - } - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); - builder.setToAmount(toAmount); - } - - byte[] ask = new byte[32]; - if (shieldAddressInfo != null) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); - if (merkleVoucherInfo.getVouchersCount() != 1) { - System.out.println("Can't get all merkel tree, please check the notes."); - return false; - } - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - - //String shieldAddress = noteInfo.getPaymentAddress(); - //ShieldAddressInfo addressInfo = - // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); - String shieldAddress = noteTx.getNote().getPaymentAddress(); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - System.arraycopy(expandedSpendingKey.getAsk(), 0, ask, 0, 32); - builder.setAk( - ByteString.copyFrom(ExpandedSpendingKey.getAkFromAsk(expandedSpendingKey.getAsk()))); - builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); - builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); - } catch (Exception e) { - System.out.println(e); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - //System.out.println("address " + noteInfo.getPaymentAddress()); - //System.out.println("value " + noteInfo.getValue()); - //System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); - //System.out.println("trxId " + noteInfo.getTrxId()); - //System.out.println("index " + noteInfo.getIndex()); - //System.out.println("meno " + new String(noteInfo.getMemo())); - - SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); - spendNoteBuilder.setNote(noteBuild.build()); - try { - spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - - spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); - spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); - - builder.addShieldedSpends(spendNoteBuilder.build()); - - } else { - byte[] ovk = ByteArray - .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - builder.setOvk(ByteString.copyFrom(ovk)); - } - - if (shieldOutputList.size() > 0) { - for (int i = 0; i < shieldOutputList.size(); ++i) { - builder - .addShieldedReceives(ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); - } - } + /** + * constructor. + */ - TransactionExtention transactionExtention = blockingStubFull - .createShieldedTransactionWithoutSpendAuthSig(builder.build()); - if (transactionExtention == null) { - System.out.println("sendShieldCoinWithoutAsk failure."); - return false; - } - BytesMessage trxHash = blockingStubFull - .getShieldTransactionHash(transactionExtention.getTransaction()); - if (trxHash == null || trxHash.getValue().toByteArray().length != 32) { - System.out.println("sendShieldCoinWithoutAsk get transaction hash failure."); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRawData().getContract(0).getType() - != ContractType.ShieldedTransferContract) { - System.out.println("This method only for ShieldedTransferContract, please check!"); - return false; - } - Any any = transaction.getRawData().getContract(0).getParameter(); - Transaction transaction1 = transactionExtention.getTransaction(); - try { - ShieldedTransferContract shieldContract = any.unpack(ShieldedTransferContract.class); - List spendDescList = shieldContract.getSpendDescriptionList(); - ShieldedTransferContract.Builder contractBuild = shieldContract.toBuilder() - .clearSpendDescription(); - for (int i = 0; i < spendDescList.size(); i++) { - - SpendAuthSigParameters.Builder builder1 = SpendAuthSigParameters.newBuilder(); - builder1.setAsk(ByteString.copyFrom(ask)); - builder1.setTxHash(ByteString.copyFrom(trxHash.getValue().toByteArray())); - builder1.setAlpha(builder.getShieldedSpends(i).getAlpha()); - SpendDescription.Builder spendDescription = spendDescList.get(i).toBuilder(); - BytesMessage authSig = blockingStubFull.createSpendAuthSig(builder1.build()); - spendDescription - .setSpendAuthoritySignature(ByteString.copyFrom(authSig.getValue().toByteArray())); - - contractBuild.addSpendDescription(spendDescription.build()); - } - - Transaction.raw.Builder rawBuilder = transaction.toBuilder().getRawDataBuilder() - .clearContract().addContract( - Transaction.Contract.newBuilder().setType(ContractType.ShieldedTransferContract) - .setParameter(Any.pack(contractBuild.build())).build()); - - transaction = transaction.toBuilder().clearRawData().setRawData(rawBuilder).build(); - - transactionExtention = transactionExtention.toBuilder().setTransaction(transaction).build(); - - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - transaction1 = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - if (transaction1.getRawData().getContract(0).getType() - != ContractType.ShieldedTransferContract) { - transaction1 = signTransaction(ecKey, transaction1); - } else { - Any any1 = transaction1.getRawData().getContract(0).getParameter(); - ShieldedTransferContract shieldedTransferContract = any1 - .unpack(ShieldedTransferContract.class); - if (shieldedTransferContract.getFromAmount() > 0) { - transaction1 = signTransactionForShield(ecKey, transaction1); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction1.getRawData().toByteArray()))); - } - } - } catch (Exception e) { - System.out.println(e); - } - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction1.getRawData().toByteArray()))); - return broadcastTransaction(transaction1, blockingStubFull).getResult(); - } + public static TransactionExtention triggerContractForExtention(byte[] contractAddress, + String method, String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, + long tokenValue, byte[] ownerAddress, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + if (argsStr.equalsIgnoreCase("#")) { + logger.info("argsstr is #"); + argsStr = ""; + } + byte[] owner = ownerAddress; + byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - /** - * constructor. - */ - public static List addShieldOutputList(List shieldOutList, String shieldToAddress, - String toAmountString, String menoString) { - String shieldAddress = shieldToAddress; - String amountString = toAmountString; - if (menoString.equals("null")) { - menoString = ""; - } - long shieldAmount = 0; - if (!StringUtil.isNullOrEmpty(amountString)) { - shieldAmount = Long.valueOf(amountString); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setValue(shieldAmount); - try { - noteBuild.setRcm(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - noteBuild.setMemo(ByteString.copyFrom(menoString.getBytes())); - shieldOutList.add(noteBuild.build()); - //logger.info(shieldOutList.toString()); - return shieldOutList; - } + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); - /** - * constructor. - */ - public static Optional generateShieldAddress() { - ShieldAddressInfo addressInfo = new ShieldAddressInfo(); - try { - DiversifierT diversifier = DiversifierT.random(); - SpendingKey spendingKey = SpendingKey.random(); - FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); - IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(diversifier).get(); - - addressInfo.setSk(spendingKey.getValue()); - addressInfo.setD(diversifier); - addressInfo.setIvk(incomingViewingKey.getValue()); - addressInfo.setOvk(fullViewingKey.getOvk()); - addressInfo.setPkD(paymentAddress.getPkD()); - - if (addressInfo.validateCheck()) { - return Optional.of(addressInfo); - } - } catch (Exception e) { - e.printStackTrace(); - } - - return Optional.empty(); - } + TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); + return transactionExtention; + } - /** - * constructor. - */ - public static DecryptNotes listShieldNote(Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - logger.info(ByteArray.toHexString(shieldAddressInfo.get().ivk)); - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); - logger.info(notes.toString()); - return notes; - } + /** + * constructor. + */ + public static String create2(String[] parameters) { + if (parameters == null || parameters.length != 3) { + logger.error("create2 needs 3 parameter:\ncreate2 address code salt"); + return null; + } - /** - * constructor. - */ - public static DecryptNotes getShieldNotesByIvk(Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - //startBlockNum = 0L; - logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum + 1); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); - logger.info(notes.toString()); - return notes; - } + byte[] address = WalletClient.decodeFromBase58Check(parameters[0]); + if (!WalletClient.addressValid(address)) { + logger.error("length of address must be 21 bytes."); + return null; + } - /** - * constructor. - */ - public static DecryptNotesMarked getShieldNotesAndMarkByIvk( - Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - //startBlockNum = 0L; - logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); - try { - IvkDecryptAndMarkParameters.Builder builder = IvkDecryptAndMarkParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum + 1); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - builder.setAk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getNk())); - DecryptNotesMarked decryptNotes = blockingStubFull.scanAndMarkNoteByIvk(builder.build()); - logger.info(decryptNotes.toString()); - return decryptNotes; - } catch (Exception e) { - logger.info(e.toString()); - return null; - } - } + byte[] code = Hex.decode(parameters[1]); + byte[] temp = Longs.toByteArray(Long.parseLong(parameters[2])); + if (temp.length != 8) { + logger.error("Invalid salt!"); + return null; + } + byte[] salt = new byte[32]; + System.arraycopy(temp, 0, salt, 24, 8); + + byte[] mergedData = ByteUtil.merge(address, salt, sha3(code)); + String create2Address = Base58.encode58Check(sha3omit12(mergedData)); - /** - * constructor. - */ - public static DecryptNotesMarked getShieldNotesAndMarkByIvkOnSolidity( - Optional shieldAddressInfo, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Block currentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - //startBlockNum = 0L; - logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); - try { - IvkDecryptAndMarkParameters.Builder builder = IvkDecryptAndMarkParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum + 1); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - builder.setAk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getNk())); - DecryptNotesMarked decryptNotes = blockingStubSolidity.scanAndMarkNoteByIvk(builder.build()); - logger.info(decryptNotes.toString()); - return decryptNotes; - } catch (Exception e) { - logger.info(e.toString()); - return null; + logger.info("create2 Address: " + create2Address); + + return create2Address; } - } - /** - * constructor. - */ - public static Integer getShieldNotesCount(Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - - if (currentBlockNum < 100) { - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(0); - builder.setEndBlockIndex(currentBlockNum); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); - logger.info(notes.toString()); - return notes.getNoteTxsCount(); - } - Integer count = 0; - Long startBlockNum = 0L; - while (startBlockNum + 100 < currentBlockNum) { - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum); - builder.setEndBlockIndex(startBlockNum + 100); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); - count = count + notes.getNoteTxsCount(); - startBlockNum = startBlockNum + 100; - } - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum); - builder.setEndBlockIndex(currentBlockNum); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); - count = count + notes.getNoteTxsCount(); - return count; - } + /** + * constructor. + */ + public static boolean sendShieldCoin(byte[] publicZenTokenOwnerAddress, long fromAmount, + ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, + byte[] publicZenTokenToAddress, long toAmount, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - /** - * constructor. - */ - public static DecryptNotes getShieldNotesByIvkOnSolidity( - Optional shieldAddressInfo, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Block currentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum); - builder.setEndBlockIndex(currentBlockNum); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubSolidity.scanNoteByIvk(builder.build()); - logger.info(notes.toString()); - return notes; - } + PrivateParameters.Builder builder = PrivateParameters.newBuilder(); + if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { + builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); + builder.setFromAmount(fromAmount); + } + if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { + builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); + builder.setToAmount(toAmount); + } + if (shieldAddressInfo != null) { + OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); + + //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); + OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); + outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); + outPointBuild.setIndex(noteTx.getIndex()); + request.addOutPoints(outPointBuild.build()); + + //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); + + //String shieldAddress = noteInfo.getPaymentAddress(); + //ShieldAddressInfo addressInfo = + // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); + SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); + try { + ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); + builder.setAsk(ByteString.copyFrom(expandedSpendingKey.getAsk())); + builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); + builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); + } catch (Exception e) { + System.out.println(e); + } + + Note.Builder noteBuild = Note.newBuilder(); + noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); + noteBuild.setValue(noteTx.getNote().getValue()); + noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); + noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); + + //System.out.println("address " + noteInfo.getPaymentAddress()); + //System.out.println("value " + noteInfo.getValue()); + //System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); + //System.out.println("trxId " + noteInfo.getTrxId()); + //System.out.println("index " + noteInfo.getIndex()); + //System.out.println("meno " + new String(noteInfo.getMemo())); + + SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); + spendNoteBuilder.setNote(noteBuild.build()); + try { + spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); + } catch (Exception e) { + System.out.println(e); + } + + IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull + .getMerkleTreeVoucherInfo(request.build()); + spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); + spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); + + builder.addShieldedSpends(spendNoteBuilder.build()); + + } else { + byte[] ovk = ByteArray + .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); + builder.setOvk(ByteString.copyFrom(ovk)); + } - /** - * constructor. - */ - public static DecryptNotes getShieldNotesByOvk(Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - logger.info("ovk:" + ByteArray.toHexString(shieldAddressInfo.get().ovk)); - OvkDecryptParameters.Builder builder = OvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum + 1); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setOvk(ByteString.copyFrom(shieldAddressInfo.get().getOvk())); - DecryptNotes notes = blockingStubFull.scanNoteByOvk(builder.build()); - logger.info(notes.toString()); - return notes; - } + if (shieldOutputList.size() > 0) { + for (int i = 0; i < shieldOutputList.size(); ++i) { + builder + .addShieldedReceives(ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); + } + } - /** - * constructor. - */ - public static DecryptNotes getShieldNotesByOvkOnSolidity( - Optional shieldAddressInfo, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Block currentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - OvkDecryptParameters.Builder builder = OvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum); - builder.setEndBlockIndex(currentBlockNum); - builder.setOvk(ByteString.copyFrom(shieldAddressInfo.get().getOvk())); - DecryptNotes notes = blockingStubSolidity.scanNoteByOvk(builder.build()); - logger.info(notes.toString()); - return notes; - } + TransactionExtention transactionExtention = blockingStubFull + .createShieldedTransaction(builder.build()); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + Any any = transaction.getRawData().getContract(0).getParameter(); + try { + ShieldedTransferContract shieldedTransferContract = any + .unpack(ShieldedTransferContract.class); + if (shieldedTransferContract.getFromAmount() > 0 || fromAmount == 321321) { + transaction = signTransactionForShield(ecKey, transaction); + System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + } else { + System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + } + } catch (Exception e) { + System.out.println(e); + } + return broadcastTransaction(transaction, blockingStubFull).getResult(); + } + + /** + * constructor. + */ + public static boolean sendShieldCoinWithoutAsk(byte[] publicZenTokenOwnerAddress, long fromAmount, + ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, + byte[] publicZenTokenToAddress, long toAmount, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - /** - * constructor. - */ - public static String getMemo(Note note) { - return ZenUtils.getMemo(note.getMemo().toByteArray()); - } + PrivateParametersWithoutAsk.Builder builder = PrivateParametersWithoutAsk.newBuilder(); + if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { + builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); + builder.setFromAmount(fromAmount); + } + if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { + builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); + builder.setToAmount(toAmount); + } - /** - * constructor. - */ - public static SpendResult getSpendResult(ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, - WalletGrpc.WalletBlockingStub blockingStubFull) { + byte[] ask = new byte[32]; + if (shieldAddressInfo != null) { + OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); + + //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); + OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); + outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); + outPointBuild.setIndex(noteTx.getIndex()); + request.addOutPoints(outPointBuild.build()); + IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull + .getMerkleTreeVoucherInfo(request.build()); + if (merkleVoucherInfo.getVouchersCount() != 1) { + System.out.println("Can't get all merkel tree, please check the notes."); + return false; + } + + //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); + + //String shieldAddress = noteInfo.getPaymentAddress(); + //ShieldAddressInfo addressInfo = + // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); + String shieldAddress = noteTx.getNote().getPaymentAddress(); + SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); + try { + ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); + System.arraycopy(expandedSpendingKey.getAsk(), 0, ask, 0, 32); + builder.setAk( + ByteString.copyFrom(ExpandedSpendingKey.getAkFromAsk(expandedSpendingKey.getAsk()))); + builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); + builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); + } catch (Exception e) { + System.out.println(e); + } + + Note.Builder noteBuild = Note.newBuilder(); + noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); + noteBuild.setValue(noteTx.getNote().getValue()); + noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); + noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); + + //System.out.println("address " + noteInfo.getPaymentAddress()); + //System.out.println("value " + noteInfo.getValue()); + //System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); + //System.out.println("trxId " + noteInfo.getTrxId()); + //System.out.println("index " + noteInfo.getIndex()); + //System.out.println("meno " + new String(noteInfo.getMemo())); + + SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); + spendNoteBuilder.setNote(noteBuild.build()); + try { + spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); + } catch (Exception e) { + System.out.println(e); + } + + spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); + spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); + + builder.addShieldedSpends(spendNoteBuilder.build()); + + } else { + byte[] ovk = ByteArray + .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); + builder.setOvk(ByteString.copyFrom(ovk)); + } + + if (shieldOutputList.size() > 0) { + for (int i = 0; i < shieldOutputList.size(); ++i) { + builder + .addShieldedReceives(ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); + } + } + + TransactionExtention transactionExtention = blockingStubFull + .createShieldedTransactionWithoutSpendAuthSig(builder.build()); + if (transactionExtention == null) { + System.out.println("sendShieldCoinWithoutAsk failure."); + return false; + } + BytesMessage trxHash = blockingStubFull + .getShieldTransactionHash(transactionExtention.getTransaction()); + if (trxHash == null || trxHash.getValue().toByteArray().length != 32) { + System.out.println("sendShieldCoinWithoutAsk get transaction hash failure."); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction.getRawData().getContract(0).getType() + != ContractType.ShieldedTransferContract) { + System.out.println("This method only for ShieldedTransferContract, please check!"); + return false; + } + Any any = transaction.getRawData().getContract(0).getParameter(); + Transaction transaction1 = transactionExtention.getTransaction(); + try { + ShieldedTransferContract shieldContract = any.unpack(ShieldedTransferContract.class); + List spendDescList = shieldContract.getSpendDescriptionList(); + ShieldedTransferContract.Builder contractBuild = shieldContract.toBuilder() + .clearSpendDescription(); + for (int i = 0; i < spendDescList.size(); i++) { + + SpendAuthSigParameters.Builder builder1 = SpendAuthSigParameters.newBuilder(); + builder1.setAsk(ByteString.copyFrom(ask)); + builder1.setTxHash(ByteString.copyFrom(trxHash.getValue().toByteArray())); + builder1.setAlpha(builder.getShieldedSpends(i).getAlpha()); + SpendDescription.Builder spendDescription = spendDescList.get(i).toBuilder(); + BytesMessage authSig = blockingStubFull.createSpendAuthSig(builder1.build()); + spendDescription + .setSpendAuthoritySignature(ByteString.copyFrom(authSig.getValue().toByteArray())); + + contractBuild.addSpendDescription(spendDescription.build()); + } + + Transaction.raw.Builder rawBuilder = transaction.toBuilder().getRawDataBuilder() + .clearContract().addContract( + Transaction.Contract.newBuilder().setType(ContractType.ShieldedTransferContract) + .setParameter(Any.pack(contractBuild.build())).build()); + + transaction = transaction.toBuilder().clearRawData().setRawData(rawBuilder).build(); + + transactionExtention = transactionExtention.toBuilder().setTransaction(transaction).build(); + + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + transaction1 = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + + if (transaction1.getRawData().getContract(0).getType() + != ContractType.ShieldedTransferContract) { + transaction1 = signTransaction(ecKey, transaction1); + } else { + Any any1 = transaction1.getRawData().getContract(0).getParameter(); + ShieldedTransferContract shieldedTransferContract = any1 + .unpack(ShieldedTransferContract.class); + if (shieldedTransferContract.getFromAmount() > 0) { + transaction1 = signTransactionForShield(ecKey, transaction1); + System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction1.getRawData().toByteArray()))); + } + } + } catch (Exception e) { + System.out.println(e); + } + System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction1.getRawData().toByteArray()))); + return broadcastTransaction(transaction1, blockingStubFull).getResult(); + } - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - Optional merkleVoucherInfo = Optional - .of(blockingStubFull.getMerkleTreeVoucherInfo(request.build())); - - if (merkleVoucherInfo.isPresent() && merkleVoucherInfo.get().getVouchersCount() > 0) { - NoteParameters.Builder builder = NoteParameters.newBuilder(); - try { - builder.setAk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getNk())); - logger.info("AK:" + ByteArray.toHexString(shieldAddressInfo.getFullViewingKey().getAk())); - logger.info("NK:" + ByteArray.toHexString(shieldAddressInfo.getFullViewingKey().getNk())); - } catch (Exception e) { - Assert.assertTrue(1 == 1); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - builder.setNote(noteBuild.build()); - builder.setTxid(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - builder.setIndex(noteTx.getIndex()); - //builder.setVoucher(merkleVoucherInfo.getVouchers(0)); - - SpendResult result = blockingStubFull.isSpend(builder.build()); - return result; - - } - return null; - } + /** + * constructor. + */ + public static List addShieldOutputList(List shieldOutList, String shieldToAddress, + String toAmountString, String menoString) { + String shieldAddress = shieldToAddress; + String amountString = toAmountString; + if (menoString.equals("null")) { + menoString = ""; + } + long shieldAmount = 0; + if (!StringUtil.isNullOrEmpty(amountString)) { + shieldAmount = Long.valueOf(amountString); + } - /** - * constructor. - */ - public static SpendResult getSpendResultOnSolidity(ShieldAddressInfo shieldAddressInfo, - NoteTx noteTx, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - Optional merkleVoucherInfo = Optional - .of(blockingStubSolidity.getMerkleTreeVoucherInfo(request.build())); - - if (merkleVoucherInfo.isPresent() && merkleVoucherInfo.get().getVouchersCount() > 0) { - NoteParameters.Builder builder = NoteParameters.newBuilder(); - try { - builder.setAk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getNk())); - } catch (Exception e) { - Assert.assertTrue(1 == 1); - } - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - builder.setNote(noteBuild.build()); - builder.setTxid(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - builder.setIndex(noteTx.getIndex()); - //builder.setVoucher(merkleVoucherInfo.getVouchers(0)); - - SpendResult result = blockingStubSolidity.isSpend(builder.build()); - return result; - } - return null; - } + Note.Builder noteBuild = Note.newBuilder(); + noteBuild.setPaymentAddress(shieldAddress); + noteBuild.setPaymentAddress(shieldAddress); + noteBuild.setValue(shieldAmount); + try { + noteBuild.setRcm(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); + } catch (Exception e) { + System.out.println(e); + } + noteBuild.setMemo(ByteString.copyFrom(menoString.getBytes())); + shieldOutList.add(noteBuild.build()); + //logger.info(shieldOutList.toString()); + return shieldOutList; + } - /** - * constructor. - */ - public static String getShieldNullifier(ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, - WalletGrpc.WalletBlockingStub blockingStubFull) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); - if (merkleVoucherInfo.getVouchersCount() < 1) { - System.out.println("get merkleVoucherInfo failure."); - return null; - } - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - String shieldAddress = noteTx.getNote().getPaymentAddress(); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - //TODO - FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); - NfParameters.Builder builder = NfParameters.newBuilder(); - builder.setNote(noteBuild.build()); - builder.setVoucher(merkleVoucherInfo.getVouchers(0)); - builder.setAk(ByteString.copyFrom(fullViewingKey.getAk())); - builder.setNk(ByteString.copyFrom(fullViewingKey.getNk())); - - BytesMessage nullifier = blockingStubFull.createShieldNullifier(builder.build()); - return ByteArray.toHexString(nullifier.getValue().toByteArray()); - - } catch (Exception e) { - e.printStackTrace(); - } - return null; + /** + * constructor. + */ + public static Optional generateShieldAddress() { + ShieldAddressInfo addressInfo = new ShieldAddressInfo(); + try { + DiversifierT diversifier = DiversifierT.random(); + SpendingKey spendingKey = SpendingKey.random(); + FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); + IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); + PaymentAddress paymentAddress = incomingViewingKey.address(diversifier).get(); + + addressInfo.setSk(spendingKey.getValue()); + addressInfo.setD(diversifier); + addressInfo.setIvk(incomingViewingKey.getValue()); + addressInfo.setOvk(fullViewingKey.getOvk()); + addressInfo.setPkD(paymentAddress.getPkD()); + + if (addressInfo.validateCheck()) { + return Optional.of(addressInfo); + } + } catch (Exception e) { + e.printStackTrace(); + } - } + return Optional.empty(); + } - /** - * constructor. - */ - public static String sendShieldCoinGetTxid(byte[] publicZenTokenOwnerAddress, long fromAmount, - ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, - byte[] publicZenTokenToAddress, long toAmount, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - PrivateParameters.Builder builder = PrivateParameters.newBuilder(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); - builder.setFromAmount(fromAmount); - } - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); - builder.setToAmount(toAmount); - } - - if (shieldAddressInfo != null) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - - //String shieldAddress = noteInfo.getPaymentAddress(); - //ShieldAddressInfo addressInfo = - // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - builder.setAsk(ByteString.copyFrom(expandedSpendingKey.getAsk())); - builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); - builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); - } catch (Exception e) { - System.out.println(e); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - //System.out.println("address " + noteInfo.getPaymentAddress()); - //System.out.println("value " + noteInfo.getValue()); - //System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); - //System.out.println("trxId " + noteInfo.getTrxId()); - //System.out.println("index " + noteInfo.getIndex()); - //System.out.println("meno " + new String(noteInfo.getMemo())); - - SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); - spendNoteBuilder.setNote(noteBuild.build()); - try { - spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - - IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); - spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); - spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); - - builder.addShieldedSpends(spendNoteBuilder.build()); - - } else { - byte[] ovk = ByteArray - .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - builder.setOvk(ByteString.copyFrom(ovk)); - } - - if (shieldOutputList.size() > 0) { - for (int i = 0; i < shieldOutputList.size(); ++i) { - builder - .addShieldedReceives(ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); - } + /** + * constructor. + */ + public static DecryptNotes listShieldNote(Optional shieldAddressInfo, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Long startBlockNum = 0L; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + logger.info(ByteArray.toHexString(shieldAddressInfo.get().ivk)); + IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum); + builder.setEndBlockIndex(currentBlockNum + 1); + builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); + DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); + logger.info(notes.toString()); + return notes; + } + + /** + * constructor. + */ + public static DecryptNotes getShieldNotesByIvk(Optional shieldAddressInfo, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Long startBlockNum = 0L; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + //startBlockNum = 0L; + logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); + IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum + 1); + builder.setEndBlockIndex(currentBlockNum + 1); + builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); + DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); + logger.info(notes.toString()); + return notes; + } + + /** + * constructor. + */ + public static DecryptNotesMarked getShieldNotesAndMarkByIvk( + Optional shieldAddressInfo, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Long startBlockNum = 0L; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + //startBlockNum = 0L; + logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); + try { + IvkDecryptAndMarkParameters.Builder builder = IvkDecryptAndMarkParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum + 1); + builder.setEndBlockIndex(currentBlockNum + 1); + builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); + builder.setAk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getAk())); + builder.setNk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getNk())); + DecryptNotesMarked decryptNotes = blockingStubFull.scanAndMarkNoteByIvk(builder.build()); + logger.info(decryptNotes.toString()); + return decryptNotes; + } catch (Exception e) { + logger.info(e.toString()); + return null; + } } - TransactionExtention transactionExtention = blockingStubFull - .createShieldedTransaction(builder.build()); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; + /** + * constructor. + */ + public static DecryptNotesMarked getShieldNotesAndMarkByIvkOnSolidity( + Optional shieldAddressInfo, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + Block currentBlock = blockingStubSolidity + .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Long startBlockNum = 0L; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + //startBlockNum = 0L; + logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); + try { + IvkDecryptAndMarkParameters.Builder builder = IvkDecryptAndMarkParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum + 1); + builder.setEndBlockIndex(currentBlockNum + 1); + builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); + builder.setAk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getAk())); + builder.setNk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getNk())); + DecryptNotesMarked decryptNotes = blockingStubSolidity.scanAndMarkNoteByIvk(builder.build()); + logger.info(decryptNotes.toString()); + return decryptNotes; + } catch (Exception e) { + logger.info(e.toString()); + return null; + } } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - Any any = transaction.getRawData().getContract(0).getParameter(); - - try { - ShieldedTransferContract shieldedTransferContract = any - .unpack(ShieldedTransferContract.class); - if (shieldedTransferContract.getFromAmount() > 0) { - transaction = signTransactionForShield(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - } else { - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - } - } catch (Exception e) { - System.out.println(e); - } - broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - /** - * constructor. - */ - public static byte[] decode58Check(String input) { - byte[] decodeCheck = org.tron.common.utils.Base58.decode(input); - if (decodeCheck.length <= 4) { - return null; - } - byte[] decodeData = new byte[decodeCheck.length - 4]; - System.arraycopy(decodeCheck, 0, decodeData, 0, decodeData.length); - byte[] hash0 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), decodeData); - byte[] hash1 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), hash0); - if (hash1[0] == decodeCheck[decodeData.length] && hash1[1] == decodeCheck[decodeData.length + 1] - && hash1[2] == decodeCheck[decodeData.length + 2] && hash1[3] == decodeCheck[ - decodeData.length + 3]) { - return decodeData; - } - return null; - } - - /** - * constructor. - */ - public static void freedResource(byte[] fromAddress, String priKey, byte[] toAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - long balance = PublicMethed.queryAccount(fromAddress, blockingStubFull).getBalance(); - sendcoin(toAddress, balance - 500000, fromAddress, priKey, blockingStubFull); - } + /** + * constructor. + */ + public static Integer getShieldNotesCount(Optional shieldAddressInfo, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + + if (currentBlockNum < 100) { + IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); + builder.setStartBlockIndex(0); + builder.setEndBlockIndex(currentBlockNum); + builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); + DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); + logger.info(notes.toString()); + return notes.getNoteTxsCount(); + } + Integer count = 0; + Long startBlockNum = 0L; + while (startBlockNum + 100 < currentBlockNum) { + IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum); + builder.setEndBlockIndex(startBlockNum + 100); + builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); + DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); + count = count + notes.getNoteTxsCount(); + startBlockNum = startBlockNum + 100; + } + IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum); + builder.setEndBlockIndex(currentBlockNum); + builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); + DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); + count = count + notes.getNoteTxsCount(); + return count; + + } + + /** + * constructor. + */ + public static DecryptNotes getShieldNotesByIvkOnSolidity( + Optional shieldAddressInfo, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + Block currentBlock = blockingStubSolidity + .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Long startBlockNum = 0L; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum); + builder.setEndBlockIndex(currentBlockNum); + builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); + DecryptNotes notes = blockingStubSolidity.scanNoteByIvk(builder.build()); + logger.info(notes.toString()); + return notes; + } + + + /** + * constructor. + */ + public static DecryptNotes getShieldNotesByOvk(Optional shieldAddressInfo, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Long startBlockNum = 0L; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + logger.info("ovk:" + ByteArray.toHexString(shieldAddressInfo.get().ovk)); + OvkDecryptParameters.Builder builder = OvkDecryptParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum + 1); + builder.setEndBlockIndex(currentBlockNum + 1); + builder.setOvk(ByteString.copyFrom(shieldAddressInfo.get().getOvk())); + DecryptNotes notes = blockingStubFull.scanNoteByOvk(builder.build()); + logger.info(notes.toString()); + return notes; + } + + /** + * constructor. + */ + public static DecryptNotes getShieldNotesByOvkOnSolidity( + Optional shieldAddressInfo, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + Block currentBlock = blockingStubSolidity + .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Long startBlockNum = 0L; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + OvkDecryptParameters.Builder builder = OvkDecryptParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum); + builder.setEndBlockIndex(currentBlockNum); + builder.setOvk(ByteString.copyFrom(shieldAddressInfo.get().getOvk())); + DecryptNotes notes = blockingStubSolidity.scanNoteByOvk(builder.build()); + logger.info(notes.toString()); + return notes; + } - /** - * constructor. - */ - public static String parametersString(List parameters) { - String[] inputArr = new String[parameters.size()]; - int i = 0; - for (Object parameter : parameters) { - if (parameter instanceof List) { - StringBuilder sb = new StringBuilder(); - for (Object item : (List) parameter) { - if (sb.length() != 0) { - sb.append(","); - } - sb.append("\"").append(item).append("\""); - } - inputArr[i++] = "[" + sb.toString() + "]"; - } else { - inputArr[i++] = - (parameter instanceof String) ? ("\"" + parameter + "\"") : ("" + parameter); - } - } - String input = StringUtils.join(inputArr, ','); - return input; - } - /** - * constructor. - */ - public static String bytes32ToString(byte[] bytes) { - if (bytes == null) { - return "null"; - } - int imax = bytes.length - 1; - if (imax == -1) { - return ""; + /** + * constructor. + */ + public static String getMemo(Note note) { + return ZenUtils.getMemo(note.getMemo().toByteArray()); } - StringBuilder b = new StringBuilder(); - for (int i = 0; ; i++) { - b.append(bytes[i]); - if (i == imax) { - return b.toString(); - } - } - } + /** + * constructor. + */ + public static SpendResult getSpendResult(ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, + WalletGrpc.WalletBlockingStub blockingStubFull) { + + OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); + OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); + outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); + outPointBuild.setIndex(noteTx.getIndex()); + request.addOutPoints(outPointBuild.build()); + Optional merkleVoucherInfo = Optional + .of(blockingStubFull.getMerkleTreeVoucherInfo(request.build())); + + if (merkleVoucherInfo.isPresent() && merkleVoucherInfo.get().getVouchersCount() > 0) { + NoteParameters.Builder builder = NoteParameters.newBuilder(); + try { + builder.setAk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getAk())); + builder.setNk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getNk())); + logger.info("AK:" + ByteArray.toHexString(shieldAddressInfo.getFullViewingKey().getAk())); + logger.info("NK:" + ByteArray.toHexString(shieldAddressInfo.getFullViewingKey().getNk())); + } catch (Exception e) { + Assert.assertTrue(1 == 1); + } + + Note.Builder noteBuild = Note.newBuilder(); + noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); + noteBuild.setValue(noteTx.getNote().getValue()); + noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); + noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); + builder.setNote(noteBuild.build()); + builder.setTxid(ByteString.copyFrom(noteTx.getTxid().toByteArray())); + builder.setIndex(noteTx.getIndex()); + //builder.setVoucher(merkleVoucherInfo.getVouchers(0)); + + SpendResult result = blockingStubFull.isSpend(builder.build()); + return result; - /** - * constructor. - */ + } + return null; - public static Return transferAssetForReturn(byte[] to, byte[] assertName, long amount, - byte[] address, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); } - final ECKey ecKey = temKey; - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); + /** + * constructor. + */ + public static SpendResult getSpendResultOnSolidity(ShieldAddressInfo shieldAddressInfo, + NoteTx noteTx, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); + OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); + outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); + outPointBuild.setIndex(noteTx.getIndex()); + request.addOutPoints(outPointBuild.build()); + Optional merkleVoucherInfo = Optional + .of(blockingStubSolidity.getMerkleTreeVoucherInfo(request.build())); + + if (merkleVoucherInfo.isPresent() && merkleVoucherInfo.get().getVouchersCount() > 0) { + NoteParameters.Builder builder = NoteParameters.newBuilder(); + try { + builder.setAk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getAk())); + builder.setNk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getNk())); + } catch (Exception e) { + Assert.assertTrue(1 == 1); + } + Note.Builder noteBuild = Note.newBuilder(); + noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); + noteBuild.setValue(noteTx.getNote().getValue()); + noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); + noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); + builder.setNote(noteBuild.build()); + builder.setTxid(ByteString.copyFrom(noteTx.getTxid().toByteArray())); + builder.setIndex(noteTx.getIndex()); + //builder.setVoucher(merkleVoucherInfo.getVouchers(0)); + + SpendResult result = blockingStubSolidity.isSpend(builder.build()); + return result; + } + return null; + } - TransferAssetContract contract = builder.build(); - TransactionExtention transaction = blockingStubFull.transferAsset2(contract); + /** + * constructor. + */ + public static String getShieldNullifier(ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, + WalletGrpc.WalletBlockingStub blockingStubFull) { + OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); + OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); + outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); + outPointBuild.setIndex(noteTx.getIndex()); + request.addOutPoints(outPointBuild.build()); + IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull + .getMerkleTreeVoucherInfo(request.build()); + if (merkleVoucherInfo.getVouchersCount() < 1) { + System.out.println("get merkleVoucherInfo failure."); + return null; + } + Note.Builder noteBuild = Note.newBuilder(); + noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); + noteBuild.setValue(noteTx.getNote().getValue()); + noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); + noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); + + String shieldAddress = noteTx.getNote().getPaymentAddress(); + SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); + try { + //TODO + FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); + NfParameters.Builder builder = NfParameters.newBuilder(); + builder.setNote(noteBuild.build()); + builder.setVoucher(merkleVoucherInfo.getVouchers(0)); + builder.setAk(ByteString.copyFrom(fullViewingKey.getAk())); + builder.setNk(ByteString.copyFrom(fullViewingKey.getNk())); + + BytesMessage nullifier = blockingStubFull.createShieldNullifier(builder.build()); + return ByteArray.toHexString(nullifier.getValue().toByteArray()); + + } catch (Exception e) { + e.printStackTrace(); + } + return null; - if (transaction == null) { - return transaction.getResult(); } - Return ret = transaction.getResult(); - return ret; - - } - /** - * constructor. - */ + /** + * constructor. + */ + public static String sendShieldCoinGetTxid(byte[] publicZenTokenOwnerAddress, long fromAmount, + ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, + byte[] publicZenTokenToAddress, long toAmount, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - public static Return sendcoinForReturn(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - TransactionExtention transaction = blockingStubFull.createTransaction2(contract); - if (transaction == null) { - return transaction.getResult(); - } - Return ret = transaction.getResult(); - return ret; - } + PrivateParameters.Builder builder = PrivateParameters.newBuilder(); + if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { + builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); + builder.setFromAmount(fromAmount); + } + if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { + builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); + builder.setToAmount(toAmount); + } - /** - * constructor. - */ + if (shieldAddressInfo != null) { + OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); + + //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); + OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); + outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); + outPointBuild.setIndex(noteTx.getIndex()); + request.addOutPoints(outPointBuild.build()); + + //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); + + //String shieldAddress = noteInfo.getPaymentAddress(); + //ShieldAddressInfo addressInfo = + // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); + SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); + try { + ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); + builder.setAsk(ByteString.copyFrom(expandedSpendingKey.getAsk())); + builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); + builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); + } catch (Exception e) { + System.out.println(e); + } + + Note.Builder noteBuild = Note.newBuilder(); + noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); + noteBuild.setValue(noteTx.getNote().getValue()); + noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); + noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); + + //System.out.println("address " + noteInfo.getPaymentAddress()); + //System.out.println("value " + noteInfo.getValue()); + //System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); + //System.out.println("trxId " + noteInfo.getTrxId()); + //System.out.println("index " + noteInfo.getIndex()); + //System.out.println("meno " + new String(noteInfo.getMemo())); + + SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); + spendNoteBuilder.setNote(noteBuild.build()); + try { + spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); + } catch (Exception e) { + System.out.println(e); + } + + IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull + .getMerkleTreeVoucherInfo(request.build()); + spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); + spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); + + builder.addShieldedSpends(spendNoteBuilder.build()); + + } else { + byte[] ovk = ByteArray + .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); + builder.setOvk(ByteString.copyFrom(ovk)); + } - public static Transaction sendcoinForTransaction(byte[] to, long amount, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - TransactionExtention extention = blockingStubFull.createTransaction2(contract); - Protocol.Transaction transaction = extention.getTransaction(); - return transaction; - } + if (shieldOutputList.size() > 0) { + for (int i = 0; i < shieldOutputList.size(); ++i) { + builder + .addShieldedReceives(ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); + } + } - /** - * constructor. - */ - public static String marketSellAsset(byte[] owner, String priKey, byte[] sellTokenId, - long sellTokenQuantity, byte[] buyTokenId, long buyTokenQuantity, - WalletGrpc.WalletBlockingStub blockingStubFull) { + TransactionExtention transactionExtention = blockingStubFull + .createShieldedTransaction(builder.build()); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + Any any = transaction.getRawData().getContract(0).getParameter(); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - MarketContract.MarketSellAssetContract.Builder builder = MarketContract.MarketSellAssetContract - .newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setSellTokenQuantity(sellTokenQuantity) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .setBuyTokenQuantity(buyTokenQuantity); - - TransactionExtention transactionExtention = blockingStubFull.marketSellAsset(builder.build()); - if (transactionExtention == null) { - return null; + try { + ShieldedTransferContract shieldedTransferContract = any + .unpack(ShieldedTransferContract.class); + if (shieldedTransferContract.getFromAmount() > 0) { + transaction = signTransactionForShield(ecKey, transaction); + System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + } else { + System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + } + } catch (Exception e) { + System.out.println(e); + } + broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; + + /** + * constructor. + */ + public static byte[] decode58Check(String input) { + byte[] decodeCheck = org.tron.common.utils.Base58.decode(input); + if (decodeCheck.length <= 4) { + return null; + } + byte[] decodeData = new byte[decodeCheck.length - 4]; + System.arraycopy(decodeCheck, 0, decodeData, 0, decodeData.length); + byte[] hash0 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), decodeData); + byte[] hash1 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), hash0); + if (hash1[0] == decodeCheck[decodeData.length] && hash1[1] == decodeCheck[decodeData.length + 1] + && hash1[2] == decodeCheck[decodeData.length + 2] && hash1[3] == decodeCheck[ + decodeData.length + 3]) { + return decodeData; + } + return null; } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; + + /** + * constructor. + */ + public static void freedResource(byte[] fromAddress, String priKey, byte[] toAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + long balance = PublicMethed.queryAccount(fromAddress, blockingStubFull).getBalance(); + sendcoin(toAddress, balance - 500000, fromAddress, priKey, blockingStubFull); + } + + /** + * constructor. + */ + public static String parametersString(List parameters) { + String[] inputArr = new String[parameters.size()]; + int i = 0; + for (Object parameter : parameters) { + if (parameter instanceof List) { + StringBuilder sb = new StringBuilder(); + for (Object item : (List) parameter) { + if (sb.length() != 0) { + sb.append(","); + } + sb.append("\"").append(item).append("\""); + } + inputArr[i++] = "[" + sb.toString() + "]"; + } else { + inputArr[i++] = + (parameter instanceof String) ? ("\"" + parameter + "\"") : ("" + parameter); + } + } + String input = StringUtils.join(inputArr, ','); + return input; } - if (transaction.getRawData().getContract(0).getType() - == ContractType.ShieldedTransferContract) { - return null; + /** + * constructor. + */ + public static String bytes32ToString(byte[] bytes) { + if (bytes == null) { + return "null"; + } + int imax = bytes.length - 1; + if (imax == -1) { + return ""; + } + + StringBuilder b = new StringBuilder(); + for (int i = 0; ; i++) { + b.append(bytes[i]); + if (i == imax) { + return b.toString(); + } + } } - transaction = signTransaction(ecKey, transaction); - broadcastTransaction(transaction, blockingStubFull); + /** + * constructor. + */ - String txid = ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + public static Return transferAssetForReturn(byte[] to, byte[] assertName, long amount, + byte[] address, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsName = ByteString.copyFrom(assertName); + ByteString bsOwner = ByteString.copyFrom(address); + builder.setToAddress(bsTo); + builder.setAssetName(bsName); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferAssetContract contract = builder.build(); + TransactionExtention transaction = blockingStubFull.transferAsset2(contract); + + if (transaction == null) { + return transaction.getResult(); + } + Return ret = transaction.getResult(); + return ret; - System.out.println("trigger txid = " + txid); - return txid; + } - } - /** - * constructor. - */ - public static Return marketSellAssetGetResposne(byte[] owner, String priKey, byte[] sellTokenId, - long sellTokenQuantity, byte[] buyTokenId, long buyTokenQuantity, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** + * constructor. + */ - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); + public static Return sendcoinForReturn(byte[] to, long amount, byte[] owner, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + //String priKey = testKey002; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + TransferContract.Builder builder = TransferContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsOwner = ByteString.copyFrom(owner); + builder.setToAddress(bsTo); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferContract contract = builder.build(); + TransactionExtention transaction = blockingStubFull.createTransaction2(contract); + if (transaction == null) { + return transaction.getResult(); + } + Return ret = transaction.getResult(); + return ret; } - ECKey ecKey = temKey; - MarketContract.MarketSellAssetContract.Builder builder = MarketContract.MarketSellAssetContract - .newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setSellTokenQuantity(sellTokenQuantity) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .setBuyTokenQuantity(buyTokenQuantity); + /** + * constructor. + */ - TransactionExtention transactionExtention = blockingStubFull.marketSellAsset(builder.build()); + public static Transaction sendcoinForTransaction(byte[] to, long amount, byte[] owner, + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + //String priKey = testKey002; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + TransferContract.Builder builder = TransferContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsOwner = ByteString.copyFrom(owner); + builder.setToAddress(bsTo); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferContract contract = builder.build(); + TransactionExtention extention = blockingStubFull.createTransaction2(contract); + Protocol.Transaction transaction = extention.getTransaction(); + return transaction; + } + + /** + * constructor. + */ + public static String marketSellAsset(byte[] owner, String priKey, byte[] sellTokenId, + long sellTokenQuantity, byte[] buyTokenId, long buyTokenQuantity, + WalletGrpc.WalletBlockingStub blockingStubFull) { - return transactionExtention.getResult(); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - } + MarketContract.MarketSellAssetContract.Builder builder = MarketContract.MarketSellAssetContract + .newBuilder(); + builder + .setOwnerAddress(ByteString.copyFrom(owner)) + .setSellTokenId(ByteString.copyFrom(sellTokenId)) + .setSellTokenQuantity(sellTokenQuantity) + .setBuyTokenId(ByteString.copyFrom(buyTokenId)) + .setBuyTokenQuantity(buyTokenQuantity); - /** - * constructor. - */ - public static String marketCancelOrder(byte[] owner, String priKey, byte[] orderId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + TransactionExtention transactionExtention = blockingStubFull.marketSellAsset(builder.build()); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + if (transaction.getRawData().getContract(0).getType() + == ContractType.ShieldedTransferContract) { + return null; + } - MarketContract.MarketCancelOrderContract.Builder builder = MarketContract - .MarketCancelOrderContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); + transaction = signTransaction(ecKey, transaction); + broadcastTransaction(transaction, blockingStubFull); - TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); + String txid = ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret.getMessage().toStringUtf8(); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } + System.out.println("trigger txid = " + txid); + return txid; - if (transaction.getRawData().getContract(0).getType() - == ContractType.ShieldedTransferContract) { - return null; } - transaction = signTransaction(ecKey, transaction); - broadcastTransaction(transaction, blockingStubFull); - - String txid = ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + /** + * constructor. + */ + public static Return marketSellAssetGetResposne(byte[] owner, String priKey, byte[] sellTokenId, + long sellTokenQuantity, byte[] buyTokenId, long buyTokenQuantity, + WalletGrpc.WalletBlockingStub blockingStubFull) { - System.out.println("trigger txid = " + txid); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; - return txid; - } + MarketContract.MarketSellAssetContract.Builder builder = MarketContract.MarketSellAssetContract + .newBuilder(); + builder + .setOwnerAddress(ByteString.copyFrom(owner)) + .setSellTokenId(ByteString.copyFrom(sellTokenId)) + .setSellTokenQuantity(sellTokenQuantity) + .setBuyTokenId(ByteString.copyFrom(buyTokenId)) + .setBuyTokenQuantity(buyTokenQuantity); - /** - * constructor. - */ + TransactionExtention transactionExtention = blockingStubFull.marketSellAsset(builder.build()); - public static Return marketCancelOrderGetResposne(byte[] owner, String priKey, byte[] orderId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + return transactionExtention.getResult(); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); } - ECKey ecKey = temKey; - MarketContract.MarketCancelOrderContract.Builder builder = MarketContract - .MarketCancelOrderContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); + /** + * constructor. + */ + public static String marketCancelOrder(byte[] owner, String priKey, byte[] orderId, + WalletGrpc.WalletBlockingStub blockingStubFull) { - TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - if (transactionExtention == null) { - return null; - } - return transactionExtention.getResult(); - } + MarketContract.MarketCancelOrderContract.Builder builder = MarketContract + .MarketCancelOrderContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); - /** - * constructor. - */ - public static Optional getMarketOrderByAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - BytesMessage request = BytesMessage.newBuilder().setValue(addressBs).build(); + TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); - Protocol.MarketOrderList marketOrderList; - marketOrderList = blockingStubFull.getMarketOrderByAccount(request); - return Optional.ofNullable(marketOrderList); - } + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return ret.getMessage().toStringUtf8(); + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } - /** - * constructor. - */ - public static Optional getMarketOrderByAccountSolidity(byte[] address, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - ByteString addressBs = ByteString.copyFrom(address); - BytesMessage request = BytesMessage.newBuilder().setValue(addressBs).build(); - - Protocol.MarketOrderList marketOrderList; - marketOrderList = blockingStubSolidity.getMarketOrderByAccount(request); - return Optional.ofNullable(marketOrderList); - } + if (transaction.getRawData().getContract(0).getType() + == ContractType.ShieldedTransferContract) { + return null; + } - /** - * constructor. - */ - public static Optional getMarketOrderById(byte[] order, - WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString orderBytes = ByteString.copyFrom(order); - BytesMessage request = BytesMessage.newBuilder().setValue(orderBytes).build(); - Protocol.MarketOrder orderPair = blockingStubFull.getMarketOrderById(request); - return Optional.ofNullable(orderPair); - } + transaction = signTransaction(ecKey, transaction); + broadcastTransaction(transaction, blockingStubFull); - /** - * constructor. - */ - public static Optional getMarketOrderByIdSolidity(byte[] order, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - ByteString orderBytes = ByteString.copyFrom(order); - BytesMessage request = BytesMessage.newBuilder().setValue(orderBytes).build(); - Protocol.MarketOrder orderPair = blockingStubSolidity.getMarketOrderById(request); - return Optional.ofNullable(orderPair); - } + String txid = ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); - /** - * constructor. - */ - public static Optional getMarketPriceByPair(byte[] sellTokenId, - byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { - Protocol.MarketOrderPair request = - Protocol.MarketOrderPair.newBuilder() - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .build(); - - Protocol.MarketPriceList marketPriceList = blockingStubFull.getMarketPriceByPair(request); - return Optional.ofNullable(marketPriceList); - } + System.out.println("trigger txid = " + txid); - /** - * constructor. - */ - public static Optional getMarketOrderListByPair(byte[] sellTokenId, - byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { - Protocol.MarketOrderPair request = - Protocol.MarketOrderPair.newBuilder() - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .build(); - - Protocol.MarketOrderList marketOrderList = blockingStubFull.getMarketOrderListByPair(request); - return Optional.ofNullable(marketOrderList); - } + return txid; + } - /** - * constructor. - */ - public static Optional getMarketOrderListByPairSolidity( - byte[] sellTokenId, - byte[] buyTokenId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Protocol.MarketOrderPair request = - Protocol.MarketOrderPair.newBuilder() - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .build(); - - Protocol.MarketOrderList marketOrderList = blockingStubSolidity - .getMarketOrderListByPair(request); - return Optional.ofNullable(marketOrderList); - } + /** + * constructor. + */ - /** - * constructor. - */ - public static Optional getMarketPairList( - WalletGrpc.WalletBlockingStub blockingStubFull) { - Protocol.MarketOrderPairList marketOrderList = blockingStubFull - .getMarketPairList(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(marketOrderList); - } + public static Return marketCancelOrderGetResposne(byte[] owner, String priKey, byte[] orderId, + WalletGrpc.WalletBlockingStub blockingStubFull) { - /** - * constructor. - */ - public static Optional getMarketPairListSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Protocol.MarketOrderPairList marketOrderList = blockingStubSolidity - .getMarketPairList(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(marketOrderList); - } + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; - /** - * constructor. - */ - public static String stringToHexString(String s) { - String str = ""; - for (int i = 0; i < s.length(); i++) { - int ch = s.charAt(i); - String s4 = Integer.toHexString(ch); - str = str + s4; - } - return str; - } + MarketContract.MarketCancelOrderContract.Builder builder = MarketContract + .MarketCancelOrderContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); - /** - * constructor. - */ - public static String hexStringToString(String s) { - if (s == null || s.equals("")) { - return null; - } - s = s.replace(" ", ""); - byte[] baKeyword = new byte[s.length() / 2]; - for (int i = 0; i < baKeyword.length; i++) { - try { - baKeyword[i] = (byte) (0xff & Integer.parseInt( - s.substring(i * 2, i * 2 + 2), 16)); - } catch (Exception e) { - e.printStackTrace(); - } - } - try { - s = new String(baKeyword, "gbk"); - new String(); - } catch (Exception e1) { - e1.printStackTrace(); - } - return s; - } + TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); - /** - * constructor. - */ - public static String removeAll0sAtTheEndOfHexStr(String s) { - return s.replaceAll("(00)+$", ""); - } + if (transactionExtention == null) { + return null; + } + return transactionExtention.getResult(); + } - /** - * constructor. - */ - public static String replaceCode(String code, String address) { - if (code.indexOf("__$") == -1) { - return code; - } else { - int index = code.indexOf("_"); - String oldStr = code.substring(index - 1, index + 39); - Pattern p = Pattern.compile(oldStr); - Matcher m = p.matcher(code); - String result = m.replaceAll(address); - return result; + /** + * constructor. + */ + public static Optional getMarketOrderByAccount(byte[] address, + WalletGrpc.WalletBlockingStub blockingStubFull) { + ByteString addressBs = ByteString.copyFrom(address); + BytesMessage request = BytesMessage.newBuilder().setValue(addressBs).build(); + + Protocol.MarketOrderList marketOrderList; + marketOrderList = blockingStubFull.getMarketOrderByAccount(request); + return Optional.ofNullable(marketOrderList); + } + + /** + * constructor. + */ + public static Optional getMarketOrderByAccountSolidity(byte[] address, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + ByteString addressBs = ByteString.copyFrom(address); + BytesMessage request = BytesMessage.newBuilder().setValue(addressBs).build(); + + Protocol.MarketOrderList marketOrderList; + marketOrderList = blockingStubSolidity.getMarketOrderByAccount(request); + return Optional.ofNullable(marketOrderList); + } + + /** + * constructor. + */ + public static Optional getMarketOrderById(byte[] order, + WalletGrpc.WalletBlockingStub blockingStubFull) { + ByteString orderBytes = ByteString.copyFrom(order); + BytesMessage request = BytesMessage.newBuilder().setValue(orderBytes).build(); + Protocol.MarketOrder orderPair = blockingStubFull.getMarketOrderById(request); + return Optional.ofNullable(orderPair); + } + + /** + * constructor. + */ + public static Optional getMarketOrderByIdSolidity(byte[] order, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + ByteString orderBytes = ByteString.copyFrom(order); + BytesMessage request = BytesMessage.newBuilder().setValue(orderBytes).build(); + Protocol.MarketOrder orderPair = blockingStubSolidity.getMarketOrderById(request); + return Optional.ofNullable(orderPair); + } + + /** + * constructor. + */ + public static Optional getMarketPriceByPair(byte[] sellTokenId, + byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { + Protocol.MarketOrderPair request = + Protocol.MarketOrderPair.newBuilder() + .setSellTokenId(ByteString.copyFrom(sellTokenId)) + .setBuyTokenId(ByteString.copyFrom(buyTokenId)) + .build(); + + Protocol.MarketPriceList marketPriceList = blockingStubFull.getMarketPriceByPair(request); + return Optional.ofNullable(marketPriceList); + } + + /** + * constructor. + */ + public static Optional getMarketOrderListByPair(byte[] sellTokenId, + byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { + Protocol.MarketOrderPair request = + Protocol.MarketOrderPair.newBuilder() + .setSellTokenId(ByteString.copyFrom(sellTokenId)) + .setBuyTokenId(ByteString.copyFrom(buyTokenId)) + .build(); + + Protocol.MarketOrderList marketOrderList = blockingStubFull.getMarketOrderListByPair(request); + return Optional.ofNullable(marketOrderList); + } + + /** + * constructor. + */ + public static Optional getMarketOrderListByPairSolidity( + byte[] sellTokenId, + byte[] buyTokenId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + Protocol.MarketOrderPair request = + Protocol.MarketOrderPair.newBuilder() + .setSellTokenId(ByteString.copyFrom(sellTokenId)) + .setBuyTokenId(ByteString.copyFrom(buyTokenId)) + .build(); + + Protocol.MarketOrderList marketOrderList = blockingStubSolidity + .getMarketOrderListByPair(request); + return Optional.ofNullable(marketOrderList); + } + + /** + * constructor. + */ + public static Optional getMarketPairList( + WalletGrpc.WalletBlockingStub blockingStubFull) { + Protocol.MarketOrderPairList marketOrderList = blockingStubFull + .getMarketPairList(EmptyMessage.newBuilder().build()); + return Optional.ofNullable(marketOrderList); + } + + /** + * constructor. + */ + public static Optional getMarketPairListSolidity( + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + Protocol.MarketOrderPairList marketOrderList = blockingStubSolidity + .getMarketPairList(EmptyMessage.newBuilder().build()); + return Optional.ofNullable(marketOrderList); + } + + /** + * constructor. + */ + public static String stringToHexString(String s) { + String str = ""; + for (int i = 0; i < s.length(); i++) { + int ch = s.charAt(i); + String s4 = Integer.toHexString(ch); + str = str + s4; + } + return str; } - } - /** - * constructor. - */ - public static Map getAllowance2(Long startNum, Long endNum, - WalletGrpc.WalletBlockingStub blockingStubFull) { - final String blackHole = Configuration.getByPath("testng.conf") - .getString("defaultParameter.blackHoleAddress"); - Long totalCount = 0L; - Map witnessBlockCount = new HashMap<>(); - Map witnessBrokerage = new HashMap<>(); - Map witnessVoteCount = new HashMap<>(); - Map witnessAllowance = new HashMap<>(); - List witnessList = PublicMethed.listWitnesses(blockingStubFull) - .get().getWitnessesList(); - for (Protocol.Witness witness : witnessList) { - witnessVoteCount.put(ByteArray.toHexString(witness.getAddress().toByteArray()), - witness.getVoteCount()); - GrpcAPI.BytesMessage bytesMessage = GrpcAPI.BytesMessage.newBuilder() - .setValue(witness.getAddress()).build(); - Long brokerager = blockingStubFull.getBrokerageInfo(bytesMessage).getNum(); - witnessBrokerage.put(ByteArray.toHexString(witness.getAddress().toByteArray()), brokerager); - totalCount += witness.getVoteCount(); - } - Optional infoById = null; - for (Long k = startNum; k < endNum; k++) { - String witnessAdd = ByteArray.toHexString(PublicMethed.getBlock(k, blockingStubFull) - .getBlockHeader().getRawData().getWitnessAddress().toByteArray()); - witnessBlockCount.put(witnessAdd, witnessBlockCount.getOrDefault(witnessAdd, 0) + 1); - List transList = PublicMethed.getBlock(k, - blockingStubFull).getTransactionsList(); - for (Transaction tem : transList) { - String txid = ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - tem.getRawData().toByteArray())); - logger.info("----ss txid:" + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long packingFee = infoById.get().getPackingFee(); - - witnessAllowance.put(witnessAdd, witnessAllowance.getOrDefault(witnessAdd, 0L) - + packingFee); - } - } - - logger.info("========totalCount:" + totalCount); - List chainParaList = - blockingStubFull.getChainParameters(EmptyMessage.newBuilder().build()) - .getChainParameterList(); - Long witness127PayPerBlock = 0L; - Long witnessPayPerBlock = 0L; - for (Protocol.ChainParameters.ChainParameter para : chainParaList) { - if ("getWitness127PayPerBlock".equals(para.getKey())) { - witness127PayPerBlock = para.getValue(); - } - if ("getWitnessPayPerBlock".equals(para.getKey())) { - witnessPayPerBlock = para.getValue(); - } - } - logger.info("witness127PayPerBlock:" + witness127PayPerBlock - + "\n witnessPayPerBlock:" + witnessPayPerBlock); - - for (Map.Entry entry : witnessBrokerage.entrySet()) { - logger.info("-----witnessBrokerage " + entry.getKey() + " : " + entry.getValue()); - } - for (Map.Entry entry : witnessVoteCount.entrySet()) { - logger.info("-----witnessVoteCount " + entry.getKey() + " : " + entry.getValue()); - } - for (Map.Entry entry : witnessBlockCount.entrySet()) { - logger.info("-----witnessBlockCount " + entry.getKey() + " : " + entry.getValue()); - } - - for (Map.Entry entry : witnessVoteCount.entrySet()) { - String witnessAdd = entry.getKey(); - logger.info("----witnessAdd:" + witnessAdd + " block count:" - + witnessBlockCount.get(witnessAdd) - + " all: " + witnessAllowance.getOrDefault(witnessAdd, 0L)); - Long pay = (witnessBlockCount.get(witnessAdd) * witnessPayPerBlock - + (endNum - startNum) * witness127PayPerBlock * entry.getValue() / totalCount - + witnessAllowance.getOrDefault(witnessAdd, 0L)) - * witnessBrokerage.get(witnessAdd) / 100; - - witnessAllowance.put(witnessAdd, pay); - logger.info("****** " + witnessAdd + " : " + pay); - } - return witnessAllowance; - } + /** + * constructor. + */ + public static String hexStringToString(String s) { + if (s == null || s.equals("")) { + return null; + } + s = s.replace(" ", ""); + byte[] baKeyword = new byte[s.length() / 2]; + for (int i = 0; i < baKeyword.length; i++) { + try { + baKeyword[i] = (byte) (0xff & Integer.parseInt( + s.substring(i * 2, i * 2 + 2), 16)); + } catch (Exception e) { + e.printStackTrace(); + } + } + try { + s = new String(baKeyword, "gbk"); + new String(); + } catch (Exception e1) { + e1.printStackTrace(); + } + return s; + } + + /** + * constructor. + */ + public static String removeAll0sAtTheEndOfHexStr(String s) { + return s.replaceAll("(00)+$", ""); + } + + /** + * constructor. + */ + public static String replaceCode(String code, String address) { + if (code.indexOf("__$") == -1) { + return code; + } else { + int index = code.indexOf("_"); + String oldStr = code.substring(index - 1, index + 39); + Pattern p = Pattern.compile(oldStr); + Matcher m = p.matcher(code); + String result = m.replaceAll(address); + return result; + } + } - public static String getContractStringMsg(byte[] contractMsgArray) { - int resultLenth = ByteArray.toInt(ByteArray.subArray(contractMsgArray, 32, 64)); - return ByteArray.toStr(ByteArray.subArray(contractMsgArray, 64, 64 + resultLenth)); - } + /** + * constructor. + */ + public static Map getAllowance2(Long startNum, Long endNum, + WalletGrpc.WalletBlockingStub blockingStubFull) { + final String blackHole = Configuration.getByPath("testng.conf") + .getString("defaultParameter.blackHoleAddress"); + Long totalCount = 0L; + Map witnessBlockCount = new HashMap<>(); + Map witnessBrokerage = new HashMap<>(); + Map witnessVoteCount = new HashMap<>(); + Map witnessAllowance = new HashMap<>(); + List witnessList = PublicMethed.listWitnesses(blockingStubFull) + .get().getWitnessesList(); + for (Protocol.Witness witness : witnessList) { + witnessVoteCount.put(ByteArray.toHexString(witness.getAddress().toByteArray()), + witness.getVoteCount()); + GrpcAPI.BytesMessage bytesMessage = GrpcAPI.BytesMessage.newBuilder() + .setValue(witness.getAddress()).build(); + Long brokerager = blockingStubFull.getBrokerageInfo(bytesMessage).getNum(); + witnessBrokerage.put(ByteArray.toHexString(witness.getAddress().toByteArray()), brokerager); + totalCount += witness.getVoteCount(); + } + Optional infoById = null; + for (Long k = startNum; k < endNum; k++) { + String witnessAdd = ByteArray.toHexString(PublicMethed.getBlock(k, blockingStubFull) + .getBlockHeader().getRawData().getWitnessAddress().toByteArray()); + witnessBlockCount.put(witnessAdd, witnessBlockCount.getOrDefault(witnessAdd, 0) + 1); + List transList = PublicMethed.getBlock(k, + blockingStubFull).getTransactionsList(); + for (Transaction tem : transList) { + String txid = ByteArray.toHexString(Sha256Hash + .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + tem.getRawData().toByteArray())); + logger.info("----ss txid:" + txid); + infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); + Long packingFee = infoById.get().getPackingFee(); + + witnessAllowance.put(witnessAdd, witnessAllowance.getOrDefault(witnessAdd, 0L) + + packingFee); + } + } + + logger.info("========totalCount:" + totalCount); + List chainParaList = + blockingStubFull.getChainParameters(EmptyMessage.newBuilder().build()) + .getChainParameterList(); + Long witness127PayPerBlock = 0L; + Long witnessPayPerBlock = 0L; + for (Protocol.ChainParameters.ChainParameter para : chainParaList) { + if ("getWitness127PayPerBlock".equals(para.getKey())) { + witness127PayPerBlock = para.getValue(); + } + if ("getWitnessPayPerBlock".equals(para.getKey())) { + witnessPayPerBlock = para.getValue(); + } + } + logger.info("witness127PayPerBlock:" + witness127PayPerBlock + + "\n witnessPayPerBlock:" + witnessPayPerBlock); - /** - * constructor. - */ - public boolean updateBrokerage(byte[] owner, int brokerage, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + for (Map.Entry entry : witnessBrokerage.entrySet()) { + logger.info("-----witnessBrokerage " + entry.getKey() + " : " + entry.getValue()); + } + for (Map.Entry entry : witnessVoteCount.entrySet()) { + logger.info("-----witnessVoteCount " + entry.getKey() + " : " + entry.getValue()); + } + for (Map.Entry entry : witnessBlockCount.entrySet()) { + logger.info("-----witnessBlockCount " + entry.getKey() + " : " + entry.getValue()); + } - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); + for (Map.Entry entry : witnessVoteCount.entrySet()) { + String witnessAdd = entry.getKey(); + logger.info("----witnessAdd:" + witnessAdd + " block count:" + + witnessBlockCount.get(witnessAdd) + + " all: " + witnessAllowance.getOrDefault(witnessAdd, 0L)); + Long pay = (witnessBlockCount.get(witnessAdd) * witnessPayPerBlock + + (endNum - startNum) * witness127PayPerBlock * entry.getValue() / totalCount + + witnessAllowance.getOrDefault(witnessAdd, 0L)) + * witnessBrokerage.get(witnessAdd) / 100; + + witnessAllowance.put(witnessAdd, pay); + logger.info("****** " + witnessAdd + " : " + pay); + } + return witnessAllowance; } - ECKey ecKey = temKey; - UpdateBrokerageContract.Builder updateBrokerageContract = UpdateBrokerageContract.newBuilder(); - updateBrokerageContract.setOwnerAddress(ByteString.copyFrom(owner)).setBrokerage(brokerage); - TransactionExtention transactionExtention = blockingStubFull - .updateBrokerage(updateBrokerageContract.build()); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; + public static String getContractStringMsg(byte[] contractMsgArray) { + int resultLenth = ByteArray.toInt(ByteArray.subArray(contractMsgArray, 32, 64)); + return ByteArray.toStr(ByteArray.subArray(contractMsgArray, 64, 64 + resultLenth)); } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } + /** + * constructor. + */ + public boolean updateBrokerage(byte[] owner, int brokerage, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { - /** - * constructor. - */ - public static Long getAccountBalance(Protocol.Block block,byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - final Long blockNum = block.getBlockHeader().getRawData().getNumber(); - BlockId blockId = new BlockId( - org.tron.common.utils.Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - block.getBlockHeader().getRawData().toByteArray()), - block.getBlockHeader().getRawData().getNumber()); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; + + UpdateBrokerageContract.Builder updateBrokerageContract = UpdateBrokerageContract.newBuilder(); + updateBrokerageContract.setOwnerAddress(ByteString.copyFrom(owner)).setBrokerage(brokerage); + TransactionExtention transactionExtention = blockingStubFull + .updateBrokerage(updateBrokerageContract.build()); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out + .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return false; + } + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } + /** + * constructor. + */ + public static Long getAccountBalance(Protocol.Block block, byte[] address, + WalletGrpc.WalletBlockingStub blockingStubFull) { + final Long blockNum = block.getBlockHeader().getRawData().getNumber(); + BlockId blockId = new BlockId( + org.tron.common.utils.Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), + block.getBlockHeader().getRawData().toByteArray()), + block.getBlockHeader().getRawData().getNumber()); - BalanceContract.AccountIdentifier accountIdentifier = BalanceContract - .AccountIdentifier.newBuilder().setAddress(ByteString.copyFrom(address)).build(); - BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier - = BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() - .setHash(blockId.getByteString()).setNumber(blockNum).build(); - BalanceContract.AccountBalanceRequest accountBalanceRequest - = BalanceContract.AccountBalanceRequest.newBuilder() - .setAccountIdentifier(accountIdentifier).setBlockIdentifier(blockIdentifier).build(); - return blockingStubFull.getAccountBalance(accountBalanceRequest).getBalance(); - } + BalanceContract.AccountIdentifier accountIdentifier = BalanceContract + .AccountIdentifier.newBuilder().setAddress(ByteString.copyFrom(address)).build(); + BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier + = BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() + .setHash(blockId.getByteString()).setNumber(blockNum).build(); - /** - * constructor. - */ - public static BalanceContract.BlockBalanceTrace getBlockBalance(Protocol.Block block, - WalletGrpc.WalletBlockingStub blockingStubFull) { - final Long blockNum = block.getBlockHeader().getRawData().getNumber(); - BlockId blockId = new BlockId( - org.tron.common.utils.Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - block.getBlockHeader().getRawData().toByteArray()), - block.getBlockHeader().getRawData().getNumber()); - BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier - = BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() - .setHash(blockId.getByteString()).setNumber(blockNum).build(); + BalanceContract.AccountBalanceRequest accountBalanceRequest + = BalanceContract.AccountBalanceRequest.newBuilder() + .setAccountIdentifier(accountIdentifier).setBlockIdentifier(blockIdentifier).build(); + return blockingStubFull.getAccountBalance(accountBalanceRequest).getBalance(); + } - return blockingStubFull.getBlockBalanceTrace(blockIdentifier); + /** + * constructor. + */ + public static BalanceContract.BlockBalanceTrace getBlockBalance(Protocol.Block block, + WalletGrpc.WalletBlockingStub blockingStubFull) { + final Long blockNum = block.getBlockHeader().getRawData().getNumber(); + BlockId blockId = new BlockId( + org.tron.common.utils.Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), + block.getBlockHeader().getRawData().toByteArray()), + block.getBlockHeader().getRawData().getNumber()); + BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier + = BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() + .setHash(blockId.getByteString()).setNumber(blockNum).build(); + return blockingStubFull.getBlockBalanceTrace(blockIdentifier); - } - /** - * 61 constructor. - */ + } - public static Optional getTransactionFromPending(String txId, - WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction; - transaction = blockingStubFull.getTransactionFromPending(request); - return Optional.ofNullable(transaction); - } + /** + * 61 constructor. + */ + + public static Optional getTransactionFromPending(String txId, + WalletGrpc.WalletBlockingStub blockingStubFull) { + ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); + BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); + Transaction transaction; + transaction = blockingStubFull.getTransactionFromPending(request); + return Optional.ofNullable(transaction); + } } From a650d5bc79d2618c4b10922fc2e1f47c55836bf0 Mon Sep 17 00:00:00 2001 From: sophiawang <1975054324@qq.com> Date: Wed, 8 Dec 2021 10:59:11 +0800 Subject: [PATCH 10/24] fix case for opcode test in linux --- .../tvmnewcommand/newGrammar/Opcode.java | 35 ++----------------- 1 file changed, 2 insertions(+), 33 deletions(-) diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java index ea72aa3bdb1..65515d6db51 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java @@ -95,7 +95,7 @@ public void test01Smod() { Assert.assertEquals(1, trueRes); } - @Test(enabled = true, description = "test opcode extcodecopy") + @Test(enabled = true, description = "test opcode extcodecopy return contract bytecode") public void test02Extcodecopy() { String base58 = Base58.encode58Check(mapKeyContract); String txid = PublicMethed.triggerContract(mapKeyContract, @@ -107,38 +107,7 @@ public void test02Extcodecopy() { logger.info("txid: " + txid + "\n" + infoById.toString()); Assert.assertEquals(0, infoById.get().getResultValue()); Assert.assertTrue(ByteArray.toHexString( - infoById.get().getContractResult(0).toByteArray()).contains( - "000000000000000000000000000000000000000000000000000000000000002000000000000000" - + "000000000000000000000000000000000000000000000005f06080604052600436106100705760" - + "003560e01c80638d2702f41161004e5780638d2702f414610144578063ad0a3301146101625780" - + "63d159bd5f146101a7578063f6d3ba26146101fe57610070565b806330adc4b114610075578063" - + "805ad10f146100ba5780638c82bdbd146100ff575b600080fd5b34801561008157600080fd5b50" - + "d3801561008e57600080fd5b50d2801561009b57600080fd5b506100a4610243565b6040516100" - + "b19190610421565b60405180910390f35b3480156100c657600080fd5b50d380156100d3576000" - + "80fd5b50d280156100e057600080fd5b506100e96102b3565b6040516100f691906103e4565b60" - + "405180910390f35b34801561010b57600080fd5b50d3801561011857600080fd5b50d280156101" - + "2557600080fd5b5061012e6102bb565b60405161013b919061043c565b60405180910390f35b61" - + "014c6102c3565b6040516101599190610421565b60405180910390f35b34801561016e57600080" - + "fd5b50d3801561017b57600080fd5b50d2801561018857600080fd5b506101916102e9565b6040" - + "5161019e919061043c565b60405180910390f35b3480156101b357600080fd5b50d380156101c0" - + "57600080fd5b50d280156101cd57600080fd5b506101e860048036038101906101e39190610351" - + "565b6102fe565b6040516101f591906103ff565b60405180910390f35b34801561020a57600080" - + "fd5b50d3801561021757600080fd5b50d2801561022457600080fd5b5061022d610329565b6040" - + "5161023a919061043c565b60405180910390f35b60008060019050600060029050600060039050" - + "600060039050600060039050600060039050600060039050600060039050600060019050600060" - + "0290506000600390506000600390506000600390506000600390506000600390508e9f50505050" - + "50505050505050505050505090565b600041905090565b600044905090565b6000806003905060" - + "0060029050600081836102de919061050d565b905080935050505090565b60006c112233445566" - + "77889900112233905090565b6060813b6040519150601f19601f60208301011682016040528082" - + "5280600060208401853c50919050565b600045905090565b60008135905061034081610583565b" - + "61034981610473565b905092915050565b6000602082840312156103675761036661056d565b5b" - + "600061037584828501610331565b91505092915050565b61038781610473565b82525050565b60" - + "0061039882610457565b6103a28185610462565b93506103b28185602086016104da565b6103bb" - + "81610572565b840191505092915050565b6103cf81610485565b82525050565b6103de816104d0" - + "565b82525050565b60006020820190506103f9600083018461037e565b92915050565b60006020" - + "820190508181036000830152610419818461038d565b905092915050565b600060208201905061" - - )); + infoById.get().getContractResult(0).toByteArray()).length() > 0); } From 28bc3b8dafa1a3147d20a36dba8a35d128f14ea6 Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Mon, 13 Dec 2021 16:45:58 +0800 Subject: [PATCH 11/24] add --- .../common/client/utils/JsonRpcBase.java | 2 + .../dailybuild/jsonrpc/Accounts003.java | 372 ++++++++++++++++++ 2 files changed, 374 insertions(+) create mode 100644 framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java index 38beefc88b4..584a16f95e8 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java @@ -56,6 +56,8 @@ public class JsonRpcBase { PublicMethed.getAddressString(jsonRpcOwnerKey); public static String jsonRpcNode = Configuration.getByPath("testng.conf").getStringList("jsonRpcNode.ip.list").get(0); + public static String jsonRpcNodeForSolidity = + Configuration.getByPath("testng.conf").getStringList("jsonRpcNode.ip.list").get(1); public static String httpFullNode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(0); public static String solidityNode = diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java new file mode 100644 index 00000000000..e0c5f3e7a91 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java @@ -0,0 +1,372 @@ +package stest.tron.wallet.dailybuild.jsonrpc; + +import com.alibaba.fastjson.JSONObject; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.HttpResponse; +import org.junit.Assert; +import org.testng.annotations.Test; +import stest.tron.wallet.common.client.utils.HttpMethed; +import stest.tron.wallet.common.client.utils.JsonRpcBase; + +@Slf4j +public class Accounts003 extends JsonRpcBase { + JSONObject responseContent; + HttpResponse response; + String topic0 = null; + String topic1 = null; + String fromBlock = null; + String toBlock = null; + String newFilterResultIdfrom01 = null; + String newFilterResultIdfrom02 = null; + String blockHash = null; + + @Test(enabled = true, description = "Eth api of eth_newFilter contains nothing.") + public void test01GetNewFilterContainNothing() { + JsonObject paramBody = new JsonObject(); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test01GetNewFilterContainNothing_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test01GetNewFilterContainNothing_responseContent" + responseContent); + logger.info("result:" + responseContent.getString("result")); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test( + enabled = true, + description = "Eth api of eth_newFilter contains address,fromBlock and toBlock.") + public void test02GetNewFilterContainAddress() { + if (blockNumForTrc20 - 10 < 0) { + fromBlock = "0"; + } else { + fromBlock = "0x" + Integer.toHexString(blockNumForTrc20 - 10); + } + toBlock = "0x" + Integer.toHexString(blockNumForTrc20 + 10); + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test02GetNewFilterContainAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test02GetNewFilterContainAddress_responseContent" + responseContent); + newFilterResultIdfrom01 = responseContent.getString("result"); + logger.info("test02GetNewFilterContainAddress_id:" + responseContent.getString("result")); + } + + @Test( + enabled = true, + description = "Eth api of eth_newFilter contains topic fromBlock and toBlock.") + public void test03GetNewFilterContainTopic() { + response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNumForTrc20); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + logger.info("blockHash:" + responseContent.getString("blockID")); + blockHash = responseContent.getString("blockID"); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + JsonObject paramBody = new JsonObject(); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test03GetNewFilterContainTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test03GetNewFilterContainTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + newFilterResultIdfrom02 = responseContent.getString("result"); + logger.info("test03GetNewFilterContainTopic_id:" + newFilterResultIdfrom02); + } + + @Test(enabled = true, description = "Eth api of eth_newFilter contains topic and address.") + public void test04GetNewFilterContainsTopicAndAddress() { + + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test04GetNewFilterContainsTopicAndAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test04GetNewFilterContainsTopicAndAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_newFilter only contain topic and blockHash.") + public void test05GetNewFilterOnlyContainTopic() throws InterruptedException { + JsonObject paramBody = new JsonObject(); + paramBody.addProperty("blockHash", blockHash); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + paramBody.add("topics", topicArray); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test05GetNewFilterOnlyContainTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test05GetNewFilterOnlyContainTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_newFilter which only contains blockHash.") + public void test06GetNewFilterHasOnlyBlockHash() throws InterruptedException { + response = HttpMethed.getNowBlockFromSolidity(solidityNode); + responseContent = HttpMethed.parseResponseContent(response); + String blockHash = responseContent.getString("blockID"); + Thread.sleep(30000); + JsonObject paramBody = new JsonObject(); + paramBody.addProperty("blockHash", blockHash); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test06GetNewFilterHasOnlyBlockHash_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test06GetNewFilterHasOnlyBlockHash_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_newFilter check new and after block.") + public void test07GetNewFilterCheckNewBlock() { + JsonObject paramBody = new JsonObject(); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + paramBody.add("topics", topicArray); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test07GetNewFilterCheckNewBlock_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test07GetNewFilterCheckNewBlock_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_newBlockFilter") + public void test08GetEthNewBlockFilter() { + + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test08GetEthNewBlockFilter_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test08GetEthNewBlockFilter_responseContent:" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_getFilterChanges has less 20 elements.") + public void test09GetFilterChanges() { + + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); + String ethNewBlockFilterResult = responseContent.get("result").toString(); + logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); + String newFilterId = responseContent.getString("result"); + logger.info("newFilterId:" + newFilterId); + params = new JsonArray(); + params.add(newFilterId); + requestBody = getJsonRpcBody("eth_getFilterChanges", params); + logger.info("test09GetFilterChanges_requestBody: " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test09GetFilterChanges_responseContent:" + responseContent); + Assert.assertEquals("[]", responseContent.getString("result")); + } + + @Test( + enabled = true, + description = "Eth api of eth_getLogs contains address ,fromBlock and toBlock.") + public void test10GetLogsOnlyContainAddress() { + JsonArray addressArray = new JsonArray(); + logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); + addressArray.add(contractTrc20AddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + logger.info("blockNumForTrc20:" + blockNumForTrc20); + paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 20))); + paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 20))); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); + logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test10GetLogsOnlyContainAddress_responseContent:" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + String address = + responseContent.getJSONArray("result").getJSONObject(0).getString("address").substring(2); + Assert.assertEquals(address, contractTrc20AddressFrom58.substring(2)); + topic0 = responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); + } + + @Test(enabled = true, description = "Eth api of eth_getLogs both contains topic and address.") + public void test11GetLogsContainsTopicAndAddress() { + JsonArray topicArray = new JsonArray(); + topicArray.add(topic0); + JsonObject paramBody = new JsonObject(); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 10))); + paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 10))); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); + logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test11GetLogsContainsTopicAndAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + String topicFromResult = + responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); + Assert.assertEquals(topicFromResult, topic0); + } + + @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") + public void test12GetFilterLogsContainsAddress() { + + JsonArray params = new JsonArray(); + params.add(newFilterResultIdfrom01); + JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); + logger.info("test12GetFilterLogsContainsAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test12GetFilterLogsContainsAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") + public void test13GetFilterLogsContainsTopic() { + + JsonArray params = new JsonArray(); + params.add(newFilterResultIdfrom02); + JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); + logger.info("test13GetFilterLogsContainsTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test13GetFilterLogsContainsTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test( + enabled = true, + description = + "Eth api of eth_uninstallFilter which method is eth_newFilter" + + " and params has one element ") + public void test14EthUninstallFilter() { + // create ID + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.addProperty("fromBlock", "0x1f8b6a7"); + paramBody.addProperty("toBlock", "0x1f8b6a7"); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test14_newfilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_newfilter_responseContentr" + responseContent); + String ethNewFilterResult = responseContent.get("result").toString(); + logger.info("EthNewFilterResult:" + ethNewFilterResult); + Assert.assertNotNull(responseContent.getString("result")); + + // verify ID invalid + + // first time + params = new JsonArray(); + params.add(responseContent.get("result").toString()); + requestBody = getJsonRpcBody("eth_uninstallFilter", params); + logger.info("test14_eth_uninstallFilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_eth_uninstallFilter_responseContentr_first" + responseContent); + Assert.assertEquals(responseContent.get("result"), true); + // second time + logger.info("test14_eth_uninstallFilter_second " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_eth_uninstallFilter_responseContentr_second " + responseContent); + Assert.assertEquals( + responseContent.getJSONObject("error").getString("message"), "filter not found"); + + // query getFilterChanges to verify ID has invalid + params = new JsonArray(); + params.add(ethNewFilterResult); + requestBody = getJsonRpcBody("getFilterChanges", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14EthUninstallFilter_responseContent" + responseContent); + String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; + Assert.assertEquals(responseContent.get("error").toString(), expectResult); + } + + @Test( + enabled = true, + description = + "Eth api of eth_uninstallFilter which method is eth_newBlockFilter" + + " and params has one element ") + public void test15EthUninstallFilter() { + // create ID + + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); + String ethNewBlockFilterResult = responseContent.get("result").toString(); + logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); + Assert.assertNotNull(responseContent.getString("result")); + + // verify ID invalid + // first time + params = new JsonArray(); + params.add(responseContent.get("result").toString()); + requestBody = getJsonRpcBody("eth_uninstallFilter", params); + logger.info("test15_eth_uninstallFilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15_eth_uninstallFilter_responseContentr_first" + responseContent); + Assert.assertEquals(responseContent.get("result"), true); + // second time + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15_eth_uninstallFilter_responseContentr_second" + responseContent); + Assert.assertEquals( + responseContent.getJSONObject("error").getString("message"), "filter not found"); + // query getFilterChanges to verify ID has invalid + params = new JsonArray(); + params.add(ethNewBlockFilterResult); + requestBody = getJsonRpcBody("getFilterChanges", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_responseContent" + responseContent); + String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; + Assert.assertEquals(responseContent.get("error").toString(), expectResult); + } +} From 52fbc4ba0f1fc275961e011554e5e4f38bc13314 Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Mon, 13 Dec 2021 16:49:50 +0800 Subject: [PATCH 12/24] add --- .../dailybuild/jsonrpc/Accounts003.java | 662 +++++++++--------- 1 file changed, 331 insertions(+), 331 deletions(-) diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java index e0c5f3e7a91..a8cc54adac1 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java @@ -12,361 +12,361 @@ @Slf4j public class Accounts003 extends JsonRpcBase { - JSONObject responseContent; - HttpResponse response; - String topic0 = null; - String topic1 = null; - String fromBlock = null; - String toBlock = null; - String newFilterResultIdfrom01 = null; - String newFilterResultIdfrom02 = null; - String blockHash = null; + JSONObject responseContent; + HttpResponse response; + String topic0 = null; + String topic1 = null; + String fromBlock = null; + String toBlock = null; + String newFilterResultIdfrom01 = null; + String newFilterResultIdfrom02 = null; + String blockHash = null; - @Test(enabled = true, description = "Eth api of eth_newFilter contains nothing.") - public void test01GetNewFilterContainNothing() { - JsonObject paramBody = new JsonObject(); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test01GetNewFilterContainNothing_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test01GetNewFilterContainNothing_responseContent" + responseContent); - logger.info("result:" + responseContent.getString("result")); - Assert.assertNotNull(responseContent.getString("result")); - } + @Test(enabled = true, description = "Eth api of eth_newFilter contains nothing.") + public void test01GetNewFilterContainNothing() { + JsonObject paramBody = new JsonObject(); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test01GetNewFilterContainNothing_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test01GetNewFilterContainNothing_responseContent" + responseContent); + logger.info("result:" + responseContent.getString("result")); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test( - enabled = true, - description = "Eth api of eth_newFilter contains address,fromBlock and toBlock.") - public void test02GetNewFilterContainAddress() { - if (blockNumForTrc20 - 10 < 0) { - fromBlock = "0"; - } else { - fromBlock = "0x" + Integer.toHexString(blockNumForTrc20 - 10); - } - toBlock = "0x" + Integer.toHexString(blockNumForTrc20 + 10); - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test02GetNewFilterContainAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test02GetNewFilterContainAddress_responseContent" + responseContent); - newFilterResultIdfrom01 = responseContent.getString("result"); - logger.info("test02GetNewFilterContainAddress_id:" + responseContent.getString("result")); + @Test( + enabled = true, + description = "Eth api of eth_newFilter contains address,fromBlock and toBlock.") + public void test02GetNewFilterContainAddress() { + if (blockNumForTrc20 - 10 < 0) { + fromBlock = "0"; + } else { + fromBlock = "0x" + Integer.toHexString(blockNumForTrc20 - 10); } + toBlock = "0x" + Integer.toHexString(blockNumForTrc20 + 10); + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test02GetNewFilterContainAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test02GetNewFilterContainAddress_responseContent" + responseContent); + newFilterResultIdfrom01 = responseContent.getString("result"); + logger.info("test02GetNewFilterContainAddress_id:" + responseContent.getString("result")); + } - @Test( - enabled = true, - description = "Eth api of eth_newFilter contains topic fromBlock and toBlock.") - public void test03GetNewFilterContainTopic() { - response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - logger.info("blockHash:" + responseContent.getString("blockID")); - blockHash = responseContent.getString("blockID"); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - JsonObject paramBody = new JsonObject(); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test03GetNewFilterContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test03GetNewFilterContainTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - newFilterResultIdfrom02 = responseContent.getString("result"); - logger.info("test03GetNewFilterContainTopic_id:" + newFilterResultIdfrom02); - } + @Test( + enabled = true, + description = "Eth api of eth_newFilter contains topic fromBlock and toBlock.") + public void test03GetNewFilterContainTopic() { + response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNumForTrc20); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + logger.info("blockHash:" + responseContent.getString("blockID")); + blockHash = responseContent.getString("blockID"); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + JsonObject paramBody = new JsonObject(); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test03GetNewFilterContainTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test03GetNewFilterContainTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + newFilterResultIdfrom02 = responseContent.getString("result"); + logger.info("test03GetNewFilterContainTopic_id:" + newFilterResultIdfrom02); + } - @Test(enabled = true, description = "Eth api of eth_newFilter contains topic and address.") - public void test04GetNewFilterContainsTopicAndAddress() { + @Test(enabled = true, description = "Eth api of eth_newFilter contains topic and address.") + public void test04GetNewFilterContainsTopicAndAddress() { - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test04GetNewFilterContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test04GetNewFilterContainsTopicAndAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test04GetNewFilterContainsTopicAndAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test04GetNewFilterContainsTopicAndAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_newFilter only contain topic and blockHash.") - public void test05GetNewFilterOnlyContainTopic() throws InterruptedException { - JsonObject paramBody = new JsonObject(); - paramBody.addProperty("blockHash", blockHash); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - paramBody.add("topics", topicArray); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test05GetNewFilterOnlyContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test05GetNewFilterOnlyContainTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + @Test(enabled = true, description = "Eth api of eth_newFilter only contain topic and blockHash.") + public void test05GetNewFilterOnlyContainTopic() throws InterruptedException { + JsonObject paramBody = new JsonObject(); + paramBody.addProperty("blockHash", blockHash); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + paramBody.add("topics", topicArray); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test05GetNewFilterOnlyContainTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test05GetNewFilterOnlyContainTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_newFilter which only contains blockHash.") - public void test06GetNewFilterHasOnlyBlockHash() throws InterruptedException { - response = HttpMethed.getNowBlockFromSolidity(solidityNode); - responseContent = HttpMethed.parseResponseContent(response); - String blockHash = responseContent.getString("blockID"); - Thread.sleep(30000); - JsonObject paramBody = new JsonObject(); - paramBody.addProperty("blockHash", blockHash); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test06GetNewFilterHasOnlyBlockHash_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test06GetNewFilterHasOnlyBlockHash_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + @Test(enabled = true, description = "Eth api of eth_newFilter which only contains blockHash.") + public void test06GetNewFilterHasOnlyBlockHash() throws InterruptedException { + response = HttpMethed.getNowBlockFromSolidity(solidityNode); + responseContent = HttpMethed.parseResponseContent(response); + String blockHash = responseContent.getString("blockID"); + Thread.sleep(30000); + JsonObject paramBody = new JsonObject(); + paramBody.addProperty("blockHash", blockHash); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test06GetNewFilterHasOnlyBlockHash_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test06GetNewFilterHasOnlyBlockHash_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_newFilter check new and after block.") - public void test07GetNewFilterCheckNewBlock() { - JsonObject paramBody = new JsonObject(); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - paramBody.add("topics", topicArray); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test07GetNewFilterCheckNewBlock_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test07GetNewFilterCheckNewBlock_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + @Test(enabled = true, description = "Eth api of eth_newFilter check new and after block.") + public void test07GetNewFilterCheckNewBlock() { + JsonObject paramBody = new JsonObject(); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + paramBody.add("topics", topicArray); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test07GetNewFilterCheckNewBlock_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test07GetNewFilterCheckNewBlock_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_newBlockFilter") - public void test08GetEthNewBlockFilter() { + @Test(enabled = true, description = "Eth api of eth_newBlockFilter") + public void test08GetEthNewBlockFilter() { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test08GetEthNewBlockFilter_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test08GetEthNewBlockFilter_responseContent:" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test08GetEthNewBlockFilter_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test08GetEthNewBlockFilter_responseContent:" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_getFilterChanges has less 20 elements.") - public void test09GetFilterChanges() { + @Test(enabled = true, description = "Eth api of eth_getFilterChanges has less 20 elements.") + public void test09GetFilterChanges() { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); - String ethNewBlockFilterResult = responseContent.get("result").toString(); - logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); - String newFilterId = responseContent.getString("result"); - logger.info("newFilterId:" + newFilterId); - params = new JsonArray(); - params.add(newFilterId); - requestBody = getJsonRpcBody("eth_getFilterChanges", params); - logger.info("test09GetFilterChanges_requestBody: " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test09GetFilterChanges_responseContent:" + responseContent); - Assert.assertEquals("[]", responseContent.getString("result")); - } + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); + String ethNewBlockFilterResult = responseContent.get("result").toString(); + logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); + String newFilterId = responseContent.getString("result"); + logger.info("newFilterId:" + newFilterId); + params = new JsonArray(); + params.add(newFilterId); + requestBody = getJsonRpcBody("eth_getFilterChanges", params); + logger.info("test09GetFilterChanges_requestBody: " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test09GetFilterChanges_responseContent:" + responseContent); + Assert.assertEquals("[]", responseContent.getString("result")); + } - @Test( - enabled = true, - description = "Eth api of eth_getLogs contains address ,fromBlock and toBlock.") - public void test10GetLogsOnlyContainAddress() { - JsonArray addressArray = new JsonArray(); - logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); - addressArray.add(contractTrc20AddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - logger.info("blockNumForTrc20:" + blockNumForTrc20); - paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 20))); - paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 20))); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); - logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test10GetLogsOnlyContainAddress_responseContent:" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - String address = - responseContent.getJSONArray("result").getJSONObject(0).getString("address").substring(2); - Assert.assertEquals(address, contractTrc20AddressFrom58.substring(2)); - topic0 = responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); - } + @Test( + enabled = true, + description = "Eth api of eth_getLogs contains address ,fromBlock and toBlock.") + public void test10GetLogsOnlyContainAddress() { + JsonArray addressArray = new JsonArray(); + logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); + addressArray.add(contractTrc20AddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + logger.info("blockNumForTrc20:" + blockNumForTrc20); + paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 20))); + paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 20))); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); + logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test10GetLogsOnlyContainAddress_responseContent:" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + String address = + responseContent.getJSONArray("result").getJSONObject(0).getString("address").substring(2); + Assert.assertEquals(address, contractTrc20AddressFrom58.substring(2)); + topic0 = responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); + } - @Test(enabled = true, description = "Eth api of eth_getLogs both contains topic and address.") - public void test11GetLogsContainsTopicAndAddress() { - JsonArray topicArray = new JsonArray(); - topicArray.add(topic0); - JsonObject paramBody = new JsonObject(); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 10))); - paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 10))); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); - logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test11GetLogsContainsTopicAndAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - String topicFromResult = - responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); - Assert.assertEquals(topicFromResult, topic0); - } + @Test(enabled = true, description = "Eth api of eth_getLogs both contains topic and address.") + public void test11GetLogsContainsTopicAndAddress() { + JsonArray topicArray = new JsonArray(); + topicArray.add(topic0); + JsonObject paramBody = new JsonObject(); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 10))); + paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 10))); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); + logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test11GetLogsContainsTopicAndAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + String topicFromResult = + responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); + Assert.assertEquals(topicFromResult, topic0); + } - @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") - public void test12GetFilterLogsContainsAddress() { + @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") + public void test12GetFilterLogsContainsAddress() { - JsonArray params = new JsonArray(); - params.add(newFilterResultIdfrom01); - JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); - logger.info("test12GetFilterLogsContainsAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test12GetFilterLogsContainsAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + JsonArray params = new JsonArray(); + params.add(newFilterResultIdfrom01); + JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); + logger.info("test12GetFilterLogsContainsAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test12GetFilterLogsContainsAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") - public void test13GetFilterLogsContainsTopic() { + @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") + public void test13GetFilterLogsContainsTopic() { - JsonArray params = new JsonArray(); - params.add(newFilterResultIdfrom02); - JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); - logger.info("test13GetFilterLogsContainsTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test13GetFilterLogsContainsTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + JsonArray params = new JsonArray(); + params.add(newFilterResultIdfrom02); + JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); + logger.info("test13GetFilterLogsContainsTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test13GetFilterLogsContainsTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test( - enabled = true, - description = - "Eth api of eth_uninstallFilter which method is eth_newFilter" - + " and params has one element ") - public void test14EthUninstallFilter() { - // create ID - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.addProperty("fromBlock", "0x1f8b6a7"); - paramBody.addProperty("toBlock", "0x1f8b6a7"); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test14_newfilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_newfilter_responseContentr" + responseContent); - String ethNewFilterResult = responseContent.get("result").toString(); - logger.info("EthNewFilterResult:" + ethNewFilterResult); - Assert.assertNotNull(responseContent.getString("result")); + @Test( + enabled = true, + description = + "Eth api of eth_uninstallFilter which method is eth_newFilter" + + " and params has one element ") + public void test14EthUninstallFilter() { + // create ID + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.addProperty("fromBlock", "0x1f8b6a7"); + paramBody.addProperty("toBlock", "0x1f8b6a7"); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test14_newfilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_newfilter_responseContentr" + responseContent); + String ethNewFilterResult = responseContent.get("result").toString(); + logger.info("EthNewFilterResult:" + ethNewFilterResult); + Assert.assertNotNull(responseContent.getString("result")); - // verify ID invalid + // verify ID invalid - // first time - params = new JsonArray(); - params.add(responseContent.get("result").toString()); - requestBody = getJsonRpcBody("eth_uninstallFilter", params); - logger.info("test14_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_eth_uninstallFilter_responseContentr_first" + responseContent); - Assert.assertEquals(responseContent.get("result"), true); - // second time - logger.info("test14_eth_uninstallFilter_second " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_eth_uninstallFilter_responseContentr_second " + responseContent); - Assert.assertEquals( - responseContent.getJSONObject("error").getString("message"), "filter not found"); + // first time + params = new JsonArray(); + params.add(responseContent.get("result").toString()); + requestBody = getJsonRpcBody("eth_uninstallFilter", params); + logger.info("test14_eth_uninstallFilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_eth_uninstallFilter_responseContentr_first" + responseContent); + Assert.assertEquals(responseContent.get("result"), true); + // second time + logger.info("test14_eth_uninstallFilter_second " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_eth_uninstallFilter_responseContentr_second " + responseContent); + Assert.assertEquals( + responseContent.getJSONObject("error").getString("message"), "filter not found"); - // query getFilterChanges to verify ID has invalid - params = new JsonArray(); - params.add(ethNewFilterResult); - requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14EthUninstallFilter_responseContent" + responseContent); - String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; - Assert.assertEquals(responseContent.get("error").toString(), expectResult); - } + // query getFilterChanges to verify ID has invalid + params = new JsonArray(); + params.add(ethNewFilterResult); + requestBody = getJsonRpcBody("getFilterChanges", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14EthUninstallFilter_responseContent" + responseContent); + String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; + Assert.assertEquals(responseContent.get("error").toString(), expectResult); + } - @Test( - enabled = true, - description = - "Eth api of eth_uninstallFilter which method is eth_newBlockFilter" - + " and params has one element ") - public void test15EthUninstallFilter() { - // create ID + @Test( + enabled = true, + description = + "Eth api of eth_uninstallFilter which method is eth_newBlockFilter" + + " and params has one element ") + public void test15EthUninstallFilter() { + // create ID - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); - String ethNewBlockFilterResult = responseContent.get("result").toString(); - logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); - Assert.assertNotNull(responseContent.getString("result")); + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); + String ethNewBlockFilterResult = responseContent.get("result").toString(); + logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); + Assert.assertNotNull(responseContent.getString("result")); - // verify ID invalid - // first time - params = new JsonArray(); - params.add(responseContent.get("result").toString()); - requestBody = getJsonRpcBody("eth_uninstallFilter", params); - logger.info("test15_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15_eth_uninstallFilter_responseContentr_first" + responseContent); - Assert.assertEquals(responseContent.get("result"), true); - // second time - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15_eth_uninstallFilter_responseContentr_second" + responseContent); - Assert.assertEquals( - responseContent.getJSONObject("error").getString("message"), "filter not found"); - // query getFilterChanges to verify ID has invalid - params = new JsonArray(); - params.add(ethNewBlockFilterResult); - requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_responseContent" + responseContent); - String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; - Assert.assertEquals(responseContent.get("error").toString(), expectResult); - } + // verify ID invalid + // first time + params = new JsonArray(); + params.add(responseContent.get("result").toString()); + requestBody = getJsonRpcBody("eth_uninstallFilter", params); + logger.info("test15_eth_uninstallFilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15_eth_uninstallFilter_responseContentr_first" + responseContent); + Assert.assertEquals(responseContent.get("result"), true); + // second time + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15_eth_uninstallFilter_responseContentr_second" + responseContent); + Assert.assertEquals( + responseContent.getJSONObject("error").getString("message"), "filter not found"); + // query getFilterChanges to verify ID has invalid + params = new JsonArray(); + params.add(ethNewBlockFilterResult); + requestBody = getJsonRpcBody("getFilterChanges", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_responseContent" + responseContent); + String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; + Assert.assertEquals(responseContent.get("error").toString(), expectResult); + } } From 925cc4f2d4c1cf4d5a8aa06da36983dda7c063fe Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Mon, 13 Dec 2021 17:46:59 +0800 Subject: [PATCH 13/24] add --- .../dailybuild/jsonrpc/Accounts004.java | 1242 +++++++++++++++++ 1 file changed, 1242 insertions(+) create mode 100644 framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java new file mode 100644 index 00000000000..f1e1cb8304b --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java @@ -0,0 +1,1242 @@ +package stest.tron.wallet.dailybuild.jsonrpc; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import io.grpc.ManagedChannelBuilder; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.HttpResponse; +import org.junit.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.tron.api.GrpcAPI; +import org.tron.api.WalletGrpc; +import org.tron.common.utils.ByteArray; +import org.tron.protos.Protocol.Block; +import stest.tron.wallet.common.client.utils.HttpMethed; +import stest.tron.wallet.common.client.utils.JsonRpcBase; +import stest.tron.wallet.common.client.utils.PublicMethed; + +@Slf4j +public class Accounts004 extends JsonRpcBase { + private JSONObject responseContent; + private HttpResponse response; + String realGasPrice; + String bid = null; + int indexNum = 0; + String indexHex = null; + JSONObject result = null; + String transacionHash = null; + String blockHash = null; + String blockNumHex = null; + String parentHash = null; + String txTrieRoot = null; + String witnessAddress = null; + String feeLimit = null; + String accountStateRoot = null; + String energyUsed = "0x135c6"; + + List transactionIdList = null; + long size = 0; + long gas = 0; + long blockTimeStamp = 0; + long gasPriceFromHttp = 0; + + /** constructor. */ + @BeforeClass(enabled = true) + public void beforeClass() { + channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); + blockingStubFull = WalletGrpc.newBlockingStub(channelFull); + } + + @Test(enabled = true, description = "Json rpc api of eth_accounts") + public void test01JsonRpcApiTestForEthAccounts() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_accounts", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + List result = new ArrayList(); + logger.info(String.valueOf(result)); + Assert.assertEquals(responseContent.get("result"), result); + } + + @Test(enabled = true, description = "Json rpc api of eth_blockNumber") + public void test02JsonRpcApiTestForEthBlockNumber() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_blockNumber", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + responseContent.get("result"); + String blockNum = responseContent.getString("result").substring(2); + long blockNumFromjsonRpcNodeForSolidity = Long.parseLong(blockNum, 16); + response = HttpMethed.getNowBlockFromSolidity(solidityNode); + responseContent = HttpMethed.parseResponseContent(response); + long blockNumFromHttp = + responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); + logger.info("blocknumFromjsonRpcNodeForSolidity:" + blockNumFromjsonRpcNodeForSolidity); + logger.info("blocknumFromHttp:" + blockNumFromHttp); + Assert.assertTrue(Math.abs(blockNumFromjsonRpcNodeForSolidity - blockNumFromHttp) <= 3); + } + + @Test(enabled = true, description = "Json rpc api of eth_call") + public void test03JsonRpcApiTestForEthCall() throws Exception { + JsonObject param = new JsonObject(); + HttpMethed.waitToProduceOneBlock(httpFullNode); + param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); + param.addProperty("to", trc20AddressHex); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x0"); + param.addProperty("data", "0x06fdde03"); + JsonArray params = new JsonArray(); + params.add(param); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_call", params); + logger.info("03params:" + params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + Assert.assertEquals( + "0x000000000000000000000000000000000000000000000000000" + + "00000000000200000000000000000000000000000000000000000" + + "00000000000000000000000a546f6b656e5452433230000000000" + + "00000000000000000000000000000000000", + dataResult); + } + + @Test(enabled = true, description = "Json rpc api of eth_chainId") + public void test04JsonRpcApiTestForEthChainId() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_chainId", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + responseContent.get("result"); + String blockIdFromjsonRpcNodeForSolidity = + responseContent.get("result").toString().substring(2); + response = HttpMethed.getBlockByNumFromSolidity(solidityNode, 0); + responseContent = HttpMethed.parseResponseContent(response); + String blockIdFromHttp = responseContent.getString("blockID").substring(56); + logger.info("blockIdFromjsonRpcNodeForSolidity:" + blockIdFromjsonRpcNodeForSolidity); + logger.info("blockIdFromHttp:" + blockIdFromHttp); + Assert.assertEquals(blockIdFromjsonRpcNodeForSolidity, blockIdFromHttp); + } + + @Test(enabled = true, description = "Json rpc api of eth_coinbase") + public void test05JsonRpcApiTestForEthCoinbase() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_coinbase", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + + Assert.assertEquals( + "0x410be88a918d74d0dfd71dc84bd4abf036d0562991", responseContent.getString("result")); + } + + @Test(enabled = true, description = "Json rpc api of eth_estimateGas") + public void test06JsonRpcApiTestForEthEstimateGas() throws Exception { + JsonObject param = new JsonObject(); + param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); + param.addProperty("to", trc20AddressHex); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x0"); + param.addProperty("data", "0x1249c58b"); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("test06requestBody:" + requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + Assert.assertEquals("0x147", dataResult); + } + + @Test(enabled = true, description = "Json rpc api of eth_estimateGasHasPayable") + public void test07JsonRpcApiTestForEthEstimateGasHasPayable() throws Exception { + response = HttpMethed.getTransactionInfoByIdFromSolidity(solidityNode, txid); + responseContent = HttpMethed.parseResponseContent(response); + Long realEnergyUsed = responseContent.getJSONObject("receipt").getLong("energy_usage_total"); + logger.info("realEnergyUsed:" + realEnergyUsed); + JsonObject param = new JsonObject(); + param.addProperty("from", "0x" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2)); + param.addProperty("to", "0x" + contractAddressFrom58); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x1389"); + param.addProperty("data", data); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("test07requestBody:" + requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + Assert.assertEquals((long) realEnergyUsed, Long.parseLong(dataResult.substring(2), 16)); + } + + @Test(enabled = true, description = "Json rpc api of eth_estimateGasWithoutTo") + public void test08JsonRpcApiTestForEthEstimateGasWithoutTo() throws Exception { + JsonObject param = new JsonObject(); + param.addProperty("from", "0x6C0214C9995C6F3A61AB23F0EB84B0CDE7FD9C7C"); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x0"); + param.addProperty( + "data", + "0x6080604052d3600055d2600155346002556101418061001f6000396000f30060806040" + + "52600436106100565763ffffffff7c010000000000000000000000000000000000000000" + + "000000000000000060003504166305c24200811461005b5780633be9ece7146100815780" + + "6371dc08ce146100aa575b600080fd5b6100636100b2565b6040805193845260208401929" + + "0925282820152519081900360600190f35b6100a873ffffffffffffffffffffffffffffff" + + "ffffffffff600435166024356044356100c0565b005b61006361010d565b60005460015460" + + "0254909192565b60405173ffffffffffffffffffffffffffffffffffffffff841690821561" + + "08fc029083908590600081818185878a8ad0945050505050158015610107573d6000803e3d" + + "6000fd5b50505050565bd3d2349091925600a165627a7a72305820a2fb39541e90eda9a2f5" + + "f9e7905ef98e66e60dd4b38e00b05de418da3154e757002900000000000000000000000000" + + "00000000000000000000000000000090fa17bb"); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("test08requestBody:" + requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + logger.info("dataResult:" + dataResult); + Assert.assertEquals(energyUsed, dataResult); + } + + @Test(enabled = true, description = "Json rpc api of eth_estimateGasSendTrx") + public void test09JsonRpcApiTestForEthEstimateGasSendTrx() throws Exception { + JsonObject param = new JsonObject(); + param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); + param.addProperty("to", "0xC1A74CD01732542093F5A87910A398AD70F04BD7"); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x1"); + param.addProperty("data", "0x0"); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("test09requestBody:" + requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + Assert.assertEquals("0x0", dataResult); + } + + @Test(enabled = true, description = "Json rpc api of eth_gasPrice") + public void test10JsonRpcApiTestForEthGasPrice() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_gasPrice", params); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + responseContent.get("result"); + String gasPrice = responseContent.get("result").toString().substring(2); + long gasPriceFromJsonrpc = Long.parseLong(gasPrice, 16); + logger.info(String.valueOf(gasPriceFromJsonrpc)); + response = HttpMethed.getChainParameters(httpFullNode); + responseContent = HttpMethed.parseResponseContent(response); + JSONArray temp; + temp = responseContent.getJSONArray("chainParameter"); + for (int i = 0; i < temp.size(); i++) { + if (temp.getJSONObject(i).get("key").equals("getEnergyFee")) { + gasPriceFromHttp = temp.getJSONObject(i).getLong("value"); + } + } + logger.info("gasPriceFromHttp:" + gasPriceFromHttp); + Assert.assertEquals(gasPriceFromJsonrpc, gasPriceFromHttp); + } + + @Test(enabled = true, description = "Json rpc api of eth_getBalance") + public void test11JsonRpcApiTestForEthGetBalance() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x" + ByteArray.toHexString(foundationAccountAddress).substring(2)); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getBalance", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String balance = responseContent.getString("result").substring(2); + Long balance1 = Long.parseLong(balance, 16); + logger.info("balance1:" + balance1); + response = HttpMethed.getAccountFromSolidity(solidityNode, foundationAccountAddress); + responseContent = HttpMethed.parseResponseContent(response); + Long balance2 = responseContent.getLong("balance"); + logger.info(balance1.toString()); + logger.info(balance2.toString()); + Assert.assertEquals(balance1, balance2); + } + + @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") + public void test12JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { + response = HttpMethed.getNowBlockFromSolidity(solidityNode); + responseContent = HttpMethed.parseResponseContent(response); + JsonArray params = new JsonArray(); + params.add("earliest"); + JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String transactionNum = responseContent.getString("result").substring(2); + int transactionNum1 = Integer.parseInt(transactionNum, 16); + logger.info(String.valueOf(transactionNum1)); + response = HttpMethed.getTransactionCountByBlocknumFromSolidity(solidityNode, 0); + responseContent = HttpMethed.parseResponseContent(response); + int transactionNum2 = responseContent.getInteger("count"); + logger.info(String.valueOf(transactionNum2)); + Assert.assertEquals(transactionNum1, transactionNum2); + } + + @Test(enabled = true, description = "Json rpc api of eth_getCode") + public void test13JsonRpcApiTestForEthGetCode() throws Exception { + + JsonArray params = new JsonArray(); + params.add(contractAddressFrom58); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getCode", params); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String codeFromJsonRpc = responseContent.getString("result").substring(2); + logger.info(codeFromJsonRpc); + response = HttpMethed.getContractInfo(httpFullNode, contractAddressFrom58); + logger.info("13contractAddressFrom58:" + contractAddressFrom58); + responseContent = HttpMethed.parseResponseContent(response); + String codeFromHttp = responseContent.getString("runtimecode"); + logger.info(codeFromHttp); + Assert.assertEquals(codeFromJsonRpc, codeFromHttp); + } + + @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") + public void test14JsonRpcApiTestForEthGetStorageAt01() throws Exception { + + JsonArray params = new JsonArray(); + params.add(contractAddressFrom58); + params.add("0x0"); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("14responseContent:" + responseContent); + String result = responseContent.getString("result").substring(2); + long resultExpect = Long.parseLong(result, 16); + logger.info("result:" + resultExpect); + Assert.assertEquals("1234", String.valueOf(resultExpect)); + } + + @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") + public void test15JsonRpcApiTestForEthGetStorageAt02() throws Exception { + + String address = + "000000000000000000000000" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2); + String str = address + "0000000000000000000000000000000000000000000000000000000000000001"; + logger.info("str:" + str); + JsonArray paramsForSha3 = new JsonArray(); + paramsForSha3.add(str); + JsonObject requestBodyForSha3 = getJsonRpcBody("web3_sha3", paramsForSha3); + logger.info("requestBodyForSha3:" + requestBodyForSha3); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForSha3); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + String resultForSha3 = responseContent.getString("result"); + logger.info("resultForSha3:" + resultForSha3); + JsonArray params = new JsonArray(); + params.add(contractAddressFrom58); + params.add(resultForSha3); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("15responseContent:" + responseContent); + String result = responseContent.getString("result").substring(2); + logger.info("15result:" + result); + logger.info("mapResult:" + Integer.parseInt(result, 16)); + Assert.assertEquals("5678", String.valueOf(Integer.parseInt(result, 16))); + } + + @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockNumberAndIndex") + public void test16JsonRpcApiTestForEthGetTransactionByBlockNumberAndIndex() throws Exception { + logger.info("16blockNum:" + blockNum); + blockNumHex = "0x" + Integer.toHexString(blockNum); + logger.info("blockNumHex:" + blockNumHex); + JsonArray params = new JsonArray(); + params.add(blockNumHex); + indexNum = 0; + response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNum); + responseContent = HttpMethed.parseResponseContent(response); + parentHash = + responseContent + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getString("parentHash"); + txTrieRoot = + responseContent + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getString("txTrieRoot"); + witnessAddress = + responseContent + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getString("witness_address"); + feeLimit = + responseContent + .getJSONArray("transactions") + .getJSONObject(0) + .getJSONObject("raw_data") + .getString("fee_limit"); + logger.info(feeLimit); + + JSONObject getBlockByNumFromSolidityResult = null; + for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { + if (txid.equals( + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { + indexNum = i; + getBlockByNumFromSolidityResult = + responseContent.getJSONArray("transactions").getJSONObject(i); + bid = responseContent.getString("blockID"); + break; + } + } + transactionIdList = new ArrayList<>(); + if (responseContent.getJSONArray("transactions").size() > 0) { + for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { + transactionIdList.add( + "0x" + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID")); + } + } + logger.info("16transactionIdList:" + transactionIdList); + logger.info(String.valueOf(indexNum)); + indexHex = "0x" + Integer.toHexString(indexNum); + logger.info("indexHex:" + indexHex); + params.add(indexHex); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockNumberAndIndex", params); + logger.info("13requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + result = responseContent.getJSONObject("result"); + logger.info("16 result" + result); + Map jsonrpcResult = new HashMap(); + for (Map.Entry entry : result.entrySet()) { + jsonrpcResult.put(entry.getKey(), entry.getValue()); + } + transacionHash = jsonrpcResult.get("hash").toString(); + logger.info("transactionHash:" + transacionHash); + blockHash = jsonrpcResult.get("blockHash").toString(); + logger.info("jsonrpcResult:" + jsonrpcResult); + response = HttpMethed.getTransactionInfoByBlocknumFromSolidity(solidityNode, blockNum); + logger.info("response:" + response); + List responseContent1 = HttpMethed.parseResponseContentArray(response); + logger.info("responseContent1:" + responseContent1); + blockTimeStamp = responseContent1.get(0).getLong("blockTimeStamp"); + + for (int i = 0; i < responseContent1.size(); i++) { + if (responseContent1.get(i).getString("id").equals(transactionIdList.get(0).substring(2))) { + gas = responseContent1.get(i).getJSONObject("receipt").getLong("energy_usage_total"); + logger.info("gas:" + gas); + break; + } + } + + Assert.assertEquals(jsonrpcResult.get("gas").toString(), "0x" + Long.toHexString(gas)); + Assert.assertNull(jsonrpcResult.get("nonce")); + Assert.assertEquals( + jsonrpcResult.get("hash").toString(), + "0x" + getBlockByNumFromSolidityResult.getString("txID")); + Assert.assertEquals(jsonrpcResult.get("blockHash").toString(), "0x" + bid); + Assert.assertEquals(jsonrpcResult.get("blockNumber").toString(), blockNumHex); + Assert.assertEquals(jsonrpcResult.get("transactionIndex").toString(), indexHex); + Assert.assertEquals( + jsonrpcResult.get("from").toString(), + "0x" + + getBlockByNumFromSolidityResult + .getJSONObject("raw_data") + .getJSONArray("contract") + .getJSONObject(0) + .getJSONObject("parameter") + .getJSONObject("value") + .getString("owner_address") + .substring(2)); + Assert.assertEquals( + jsonrpcResult.get("to").toString(), + "0x" + + getBlockByNumFromSolidityResult + .getJSONObject("raw_data") + .getJSONArray("contract") + .getJSONObject(0) + .getJSONObject("parameter") + .getJSONObject("value") + .getString("contract_address") + .substring(2)); + + Assert.assertEquals(jsonrpcResult.get("value").toString(), "0x1389"); + String data; + if (getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data") == null) { + data = "0x"; + } else { + data = + getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data").substring(2); + } + Assert.assertEquals(jsonrpcResult.get("input").toString(), data); + + long temp = + Long.parseLong( + getBlockByNumFromSolidityResult.getString("signature").substring(130, 131), 16); + long v = + Long.parseLong( + getBlockByNumFromSolidityResult.getString("signature").substring(130, 132), 16); + if (temp < 27) { + v += 27; + } + Assert.assertEquals(Long.parseLong(jsonrpcResult.get("v").toString().substring(2), 16), v); + Assert.assertEquals( + jsonrpcResult.get("r").toString().substring(2), + getBlockByNumFromSolidityResult.getString("signature").substring(2, 66)); + Assert.assertEquals( + jsonrpcResult.get("s").toString().substring(2), + getBlockByNumFromSolidityResult.getString("signature").substring(66, 130)); + } + + @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByHash") + public void test17JsonRpcApiTestForEthGetBlockTransactionCountByHash() throws Exception { + logger.info("blockNum:" + blockNum); + JsonArray params = new JsonArray(); + params.add(blockHash); + logger.info("blockHash:" + blockHash); + JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByHash", params); + logger.info("requestBody:" + requestBody); + HttpMethed.waitToProduceOneBlock(httpFullNode); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + String transactionNum = responseContent.getString("result").substring(2); + int transactionNumFromjsonRpcNodeForSolidity = Integer.parseInt(transactionNum, 16); + logger.info( + "transactionNumFromjsonRpcNodeForSolidity:" + transactionNumFromjsonRpcNodeForSolidity); + response = HttpMethed.getTransactionCountByBlocknumFromSolidity(solidityNode, blockNum); + responseContent = HttpMethed.parseResponseContent(response); + int transactionNumFromHttp = responseContent.getInteger("count"); + logger.info("transactionNumFromHttp:" + transactionNumFromHttp); + Assert.assertEquals(transactionNumFromHttp, transactionNumFromjsonRpcNodeForSolidity); + } + + @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") + public void test18JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { + JsonArray params = new JsonArray(); + params.add(blockNum); + logger.info(String.valueOf(blockNum)); + JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("response:" + response); + HttpMethed.waitToProduceOneBlock(httpFullNode); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + String transactionNum = responseContent.getString("result").substring(2); + int transactionNum1 = Integer.parseInt(transactionNum, 16); + logger.info(String.valueOf(transactionNum1)); + response = HttpMethed.getTransactionCountByBlocknumFromSolidity(solidityNode, blockNum); + responseContent = HttpMethed.parseResponseContent(response); + int transactionNum2 = responseContent.getInteger("count"); + logger.info(String.valueOf(transactionNum2)); + Assert.assertEquals(transactionNum1, transactionNum2); + } + + @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockHashAndIndex") + public void test19JsonRpcApiTestForEthGetTransactionByBlockHashAndIndex() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x" + bid); + params.add(indexHex); + logger.info("indexHex:" + indexHex); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockHashAndIndex", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject resultForGetTransactionByBlockHashAndIndex = responseContent.getJSONObject("result"); + Assert.assertEquals(result, resultForGetTransactionByBlockHashAndIndex); + } + + @Test(enabled = true, description = "Json rpc api of eth_getTransactionByHash") + public void test20JsonRpcApiTestForEthGetTransactionByHash() throws Exception { + JsonArray params = new JsonArray(); + params.add(transacionHash); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionByHash", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject result1 = responseContent.getJSONObject("result"); + Assert.assertEquals(result, result1); + } + + @Test(enabled = true, description = "Json rpc api of eth_getTransactionReceipt") + public void test21JsonRpcApiTestForEthGetTransactionReceipt() throws Exception { + JsonArray params = new JsonArray(); + Thread.sleep(6000); + params.add(trc20Txid); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionReceipt", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("response:" + response); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject resultFromTransactionReceipt = responseContent.getJSONObject("result"); + logger.info("resultFromTransactionReceipt:" + resultFromTransactionReceipt); + JSONArray logs = resultFromTransactionReceipt.getJSONArray("logs"); + logger.info("logs:" + logs); + logger.info("result:" + resultFromTransactionReceipt.toString()); + response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNumForTrc20); + responseContent = HttpMethed.parseResponseContent(response); + int index = 0; + for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { + if (trc20Txid.equals( + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { + index = i; + break; + } + } + + JsonArray paramsForTransactionByBlockNumberAndIndex = new JsonArray(); + paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(blockNumForTrc20)); + paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(index)); + JsonObject requestBody1 = + getJsonRpcBody( + "eth_getTransactionByBlockNumberAndIndex", paramsForTransactionByBlockNumberAndIndex); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); + logger.info("requestBody1:" + requestBody1); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject resultFromTransactionByBlockNumberAndIndex = responseContent.getJSONObject("result"); + logger.info( + "resultFromTransactionByBlockNumberAndIndex:" + resultFromTransactionByBlockNumberAndIndex); + Assert.assertEquals( + resultFromTransactionReceipt.getString("blockHash"), + resultFromTransactionByBlockNumberAndIndex.getString("blockHash")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("blockNumber"), + resultFromTransactionByBlockNumberAndIndex.getString("blockNumber")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("transactionIndex"), + resultFromTransactionByBlockNumberAndIndex.getString("transactionIndex")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("transactionHash"), "0x" + trc20Txid); + Assert.assertEquals( + resultFromTransactionReceipt.getString("from"), + resultFromTransactionByBlockNumberAndIndex.getString("from")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("to"), + resultFromTransactionByBlockNumberAndIndex.getString("to")); + logger.info("effectiveGasPrice:" + resultFromTransactionReceipt.getString("effectiveGasPrice")); + logger.info("gasPriceFromHttp:" + Long.toHexString(gasPriceFromHttp)); + Assert.assertEquals( + resultFromTransactionReceipt.getString("effectiveGasPrice"), + "0x" + Long.toHexString(gasPriceFromHttp)); + /* Assert.assertEquals( + resultFromTransactionReceipt.getString("contractAddress").substring(2), + trc20AddressHex.substring(2));*/ + Assert.assertNull(resultFromTransactionReceipt.getString("contractAddress")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("logsBloom"), + "0x000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000"); + Assert.assertEquals("0x1", resultFromTransactionReceipt.getString("status")); + Assert.assertEquals("0x0", resultFromTransactionReceipt.getString("type")); + logger.info("gas:" + resultFromTransactionByBlockNumberAndIndex.getString("gas")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("gasUsed"), + resultFromTransactionByBlockNumberAndIndex.getString("gas")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("cumulativeGasUsed"), + resultFromTransactionByBlockNumberAndIndex.getString("gas")); + Assert.assertEquals( + logs.getJSONObject(0).getString("logIndex"), "0x" + Integer.toHexString(index)); + Assert.assertEquals(logs.getJSONObject(0).getString("removed"), "false"); + Assert.assertEquals( + logs.getJSONObject(0).getString("blockHash"), + resultFromTransactionReceipt.getString("blockHash")); + Assert.assertEquals( + logs.getJSONObject(0).getString("blockNumber"), + resultFromTransactionReceipt.getString("blockNumber")); + Assert.assertEquals( + logs.getJSONObject(0).getString("transactionIndex"), + resultFromTransactionReceipt.getString("transactionIndex")); + Assert.assertEquals( + logs.getJSONObject(0).getString("transactionHash"), + resultFromTransactionReceipt.getString("transactionHash")); + Assert.assertEquals( + logs.getJSONObject(0).getString("address"), resultFromTransactionReceipt.getString("to")); + response = HttpMethed.getTransactionInfoByBlocknumFromSolidity(solidityNode, blockNumForTrc20); + List responseContent1 = HttpMethed.parseResponseContentArray(response); + logger.info("responseContent1:" + responseContent1); + + response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNumForTrc20); + responseContent = HttpMethed.parseResponseContent(response); + Assert.assertEquals( + logs.getJSONObject(0).getString("data").substring(2), + responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("data")); + + Assert.assertEquals( + logs.getJSONObject(0).getString("topics").replace("0x", ""), + responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("topics")); + } + + @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockHashAndIndex") + public void test22JsonRpcApiTestForEthGetUncleByBlockHashAndIndex() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); + params.add("0x"); + JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockHashAndIndex", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertNull(result); + } + + @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockNumberAndIndex") + public void test23JsonRpcApiTestForEthGetUncleByBlockNumberAndIndex() throws Exception { + JsonArray params = new JsonArray(); + params.add("0xeb82f0"); + params.add("0x"); + JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockNumberAndIndex", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertNull(result); + } + + @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockHash") + public void test24JsonRpcApiTestForEthGetUncleCountByBlockHash() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); + JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockHash", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertEquals(result, "0x0"); + } + + @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockNumber") + public void test25JsonRpcApiTestForEthGetUncleCountByBlockNumber() throws Exception { + JsonArray params = new JsonArray(); + params.add("eth_getUncleCountByBlockNumber"); + JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockNumber", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertEquals(result, "0x0"); + } + + @Test(enabled = true, description = "Json rpc api of eth_getWork") + public void test26JsonRpcApiTestForEthGetWork() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_getWork", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + int resultLen = result.length(); + String resultFromjsonRpcNodeForSolidity = result.substring(4, resultLen - 12); + response = HttpMethed.getNowBlockFromSolidity(solidityNode); + responseContent = HttpMethed.parseResponseContent(response); + String resultFromHttp = responseContent.getString("blockID"); + logger.info("resultFromjsonRpcNodeForSolidity:" + resultFromjsonRpcNodeForSolidity); + logger.info("resultFromHttp:" + resultFromHttp); + Assert.assertEquals(resultFromjsonRpcNodeForSolidity, resultFromHttp); + } + + @Test(enabled = true, description = "Json rpc api of eth_hashrate") + public void test27JsonRpcApiTestForEthHashRate() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_hashrate", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertEquals("0x0", result); + } + + @Test(enabled = true, description = "Json rpc api of eth_mining") + public void test28JsonRpcApiTestForEthMining() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_mining", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertEquals(result, "true"); + } + + @Test(enabled = true, description = "Json rpc api of eth_protocolVersion") + public void test29JsonRpcApiTestForEthProtocolVersion() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_protocolVersion", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String protocolVersion = responseContent.getString("result").substring(2); + Long protocolVersion1 = Long.parseLong(protocolVersion, 16); + response = HttpMethed.getNowBlockFromSolidity(solidityNode); + responseContent = HttpMethed.parseResponseContent(response); + Long protocolVersion2 = + responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("version"); + logger.info(protocolVersion1.toString()); + logger.info(protocolVersion2.toString()); + Assert.assertEquals(protocolVersion1, protocolVersion2); + } + + @Test(enabled = true, description = "Json rpc api of eth_syncing") + public void test30JsonRpcApiTestForEthSyncing() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_syncing", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject temp = responseContent.getJSONObject("result"); + String currentNumFromRpc = temp.getString("currentBlock"); + logger.info(currentNumFromRpc); + logger.info(temp.toString()); + response = HttpMethed.getNowBlockFromSolidity(solidityNode); + responseContent = HttpMethed.parseResponseContent(response); + long currentNum = + responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); + logger.info("currentNum:" + currentNum); + logger.info("currentNumFromRpc:" + Long.parseLong(currentNumFromRpc.substring(2), 16)); + Assert.assertEquals(currentNum, Long.parseLong(currentNumFromRpc.substring(2), 16)); + Assert.assertTrue(temp.containsKey("startingBlock")); + Assert.assertTrue(temp.containsKey("currentBlock")); + Assert.assertTrue(temp.containsKey("highestBlock")); + } + + @Test(enabled = true, description = "Json rpc api of net_listening") + public void test31JsonRpcApiTestForNetListening() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("net_listening", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + Boolean temp = responseContent.getBoolean("result"); + logger.info(temp.toString()); + response = HttpMethed.getNodeInfo(solidityNode); + responseContent = HttpMethed.parseResponseContent(response); + boolean expect = false; + int num = responseContent.getInteger("activeConnectCount"); + if (num >= 1) { + expect = true; + } + Assert.assertEquals(temp, expect); + } + + @Test(enabled = true, description = "Json rpc api of net_peerCount") + public void test32JsonRpcApiTestForNetPeerCount() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("net_peerCount", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertNotNull(result); + } + + @Test(enabled = true, description = "Json rpc api of net_version") + public void test33JsonRpcApiTestForEthVersion() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("net_version", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String firstBlockHashFromJsonRpc = responseContent.getString("result").substring(2); + response = HttpMethed.getBlockByNumFromSolidity(solidityNode, 0); + responseContent = HttpMethed.parseResponseContent(response); + String firstBlockHashFromHttp = responseContent.getString("blockID").substring(56); + logger.info("firstBlockHashFromJsonRpc" + firstBlockHashFromJsonRpc); + logger.info("firstBlockHashFromHttp" + firstBlockHashFromHttp); + Assert.assertEquals(firstBlockHashFromJsonRpc, firstBlockHashFromHttp); + } + + @Test(enabled = true, description = "Json rpc api of web3_clientVersion") + public void test34JsonRpcApiTestForWeb3ClientVersion() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("web3_clientVersion", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + List resultList = new ArrayList<>(); + for (String str : result.split("/")) { + resultList.add(str); + } + Assert.assertEquals(resultList.size(), 5); + Assert.assertEquals(resultList.get(0), "TRON"); + Assert.assertEquals(resultList.get(1).substring(0, 1), "v"); + Assert.assertEquals(resultList.get(2), "Linux"); + Assert.assertEquals(resultList.get(3), "Java1.8"); + Assert.assertEquals(resultList.get(4).substring(0, 11), "GreatVoyage"); + } + + @Test(enabled = true, description = "Json rpc api of web3_sha3") + public void test35JsonRpcApiTestForWeb3Sha3() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x08"); + JsonObject requestBody1 = getJsonRpcBody("web3_sha3", params); + response = getEthHttps(ethHttpsNode, requestBody1); + responseContent = HttpMethed.parseResponseContent(response); + String result1 = responseContent.getString("result"); + JsonObject requestBody2 = getJsonRpcBody("web3_sha3", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody2); + responseContent = HttpMethed.parseResponseContent(response); + String result2 = responseContent.getString("result"); + Assert.assertEquals(result1, result2); + } + + @Test(enabled = true, description = "Json rpc api of eth_compileLLL") + public void test36JsonRpcApiTestForEthCompileLll() throws Exception { + JsonArray params = new JsonArray(); + params.add("(returnlll (suicide (caller)))"); + JsonObject requestBody1 = getJsonRpcBody("eth_compileLLL", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals(errorMessage, "the method eth_compileLLL does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_compileSerpent") + public void test37JsonRpcApiTestForEthCompileSerpent() throws Exception { + JsonArray params = new JsonArray(); + params.add("/* some serpent */"); + JsonObject requestBody = getJsonRpcBody("eth_compileSerpent", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_compileSerpent does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_compileSolidity") + public void test38JsonRpcApiTestForEthCompileSolidity() throws Exception { + JsonArray params = new JsonArray(); + params.add("contract test { function multiply(uint a) returns(uint d) { return a * 7; } }"); + JsonObject requestBody = getJsonRpcBody("eth_compileSolidity", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_compileSolidity does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_getCompilers") + public void test39JsonRpcApiTestForEthCompileSolidity() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_getCompilers", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_getCompilers does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_getTransactionCount") + public void test40JsonRpcApiTestForEthGetTransactionCount() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x407d73d8a49eeb85d32cf465507dd71d507100c1"); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionCount", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_getTransactionCount does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_sendRawTransaction") + public void test41JsonRpcApiTestForEthSendRawTransaction() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x234"); + JsonObject requestBody = getJsonRpcBody("eth_sendRawTransaction", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_sendRawTransaction does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_sendTransaction") + public void test42JsonRpcApiTestForEthSendTransaction() throws Exception { + JsonArray params = new JsonArray(); + JsonObject temp = new JsonObject(); + params.add(temp); + temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); + temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); + temp.addProperty("gas", "0x76c0"); + temp.addProperty("gasPrice", "0x9184e72a000"); + temp.addProperty( + "data", + "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); + temp.addProperty("value", "0x9184e72a"); + + JsonObject requestBody = getJsonRpcBody("eth_sendTransaction", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_sendTransaction does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_sign") + public void test43JsonRpcApiTestForEthSign() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); + params.add("0xdeadbeaf"); + JsonObject requestBody = getJsonRpcBody("eth_sign", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals(errorMessage, "the method eth_sign does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_signTransaction") + public void test44JsonRpcApiTestForEthSignTransaction() throws Exception { + JsonArray params = new JsonArray(); + JsonObject temp = new JsonObject(); + params.add(temp); + temp.addProperty( + "data", + "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); + temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); + temp.addProperty("gas", "0x76c0"); + temp.addProperty("gasPrice", "0x9184e72a000"); + temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); + temp.addProperty("value", "0x9184e72a"); + + JsonObject requestBody = getJsonRpcBody("eth_signTransaction", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_signTransaction does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_submitWork") + public void test45JsonRpcApiTestForEthSubmitWork() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x0000000000000001"); + params.add("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"); + params.add("0xD1GE5700000000000000000000000000D1GE5700000000000000000000000000"); + JsonObject requestBody = getJsonRpcBody("eth_submitWork", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals(errorMessage, "the method eth_submitWork does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of parity_nextNonce") + public void test46JsonRpcApiTestForParityNextNonce() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); + JsonObject requestBody = getJsonRpcBody("parity_nextNonce", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method parity_nextNonce does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_submitHashrate") + public void test47JsonRpcApiTestForEthSubmitHashrate() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x0000000000000000000000000000000000000000000000000000000000500000"); + params.add("0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c"); + JsonObject requestBody = getJsonRpcBody("eth_submitHashrate", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_submitHashrate does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_getBlockByHash params is false") + public void test48JsonRpcApiTestForEthGetBlockByHash() throws Exception { + response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNum); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("45getBlockByNumFromSolidityFromHttp:" + responseContent); + accountStateRoot = + responseContent + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getString("accountStateRoot"); + JsonArray params = new JsonArray(); + params.add(blockHash); + params.add(false); + JsonObject requestBody = getJsonRpcBody("eth_getBlockByHash", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject getBlockByHashResult = responseContent.getJSONObject("result"); + + Assert.assertNull(getBlockByHashResult.getString("nonce")); + Assert.assertNull(getBlockByHashResult.getString("sha3Uncles")); + Assert.assertNull(getBlockByHashResult.getString("receiptsRoot")); + Assert.assertNull(getBlockByHashResult.getString("difficulty")); + Assert.assertNull(getBlockByHashResult.getString("totalDifficulty")); + Assert.assertNull(getBlockByHashResult.getString("extraData")); + Assert.assertNull(getBlockByHashResult.getString("baseFeePerGas")); + Assert.assertNull(getBlockByHashResult.getString("mixHash")); + Assert.assertEquals(getBlockByHashResult.getString("uncles"), new ArrayList<>().toString()); + Assert.assertEquals(getBlockByHashResult.getString("stateRoot"), "0x" + accountStateRoot); + + Assert.assertEquals( + getBlockByHashResult.getString("logsBloom"), + "0x00000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000000000000000000000000" + + "000000000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000"); + Assert.assertEquals(getBlockByHashResult.getString("number"), blockNumHex); + Assert.assertEquals(getBlockByHashResult.getString("hash"), "0x" + bid); + Assert.assertEquals(getBlockByHashResult.getString("parentHash"), "0x" + parentHash); + Assert.assertEquals(getBlockByHashResult.getString("transactionsRoot"), "0x" + txTrieRoot); + Assert.assertEquals( + getBlockByHashResult.getString("miner"), "0x" + witnessAddress.substring(2)); + Assert.assertEquals(getBlockByHashResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); + Assert.assertEquals( + String.valueOf(Long.parseLong(getBlockByHashResult.getString("gasLimit").substring(2), 16)), + feeLimit); + Assert.assertEquals( + Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16), + blockTimeStamp); + final GrpcAPI.NumberMessage message = + GrpcAPI.NumberMessage.newBuilder().setNum(blockNum).build(); + HttpMethed.waitToProduceOneBlock(httpFullNode); + Block block = blockingStubFull.getBlockByNum(message); + logger.info("sizeFromJrpc:" + block.getSerializedSize()); + logger.info( + "sizeFromJsonRPc:" + + Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16)); + size = block.getSerializedSize(); + Assert.assertEquals( + Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16), + block.getSerializedSize()); + + Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16); + JSONArray transactionId = getBlockByHashResult.getJSONArray("transactions"); + List transactionIdListFromGetBlockByHash = new ArrayList<>(); + if (transactionId.size() > 0) { + for (int i = 0; i < transactionId.size(); i++) { + transactionIdListFromGetBlockByHash.add(transactionId.get(i).toString()); + } + } + Assert.assertEquals(transactionIdListFromGetBlockByHash, transactionIdList); + } + + @Test( + enabled = true, + description = "Json rpc api of eth_getBlockByNumFromSolidityber params is true") + public void test49JsonRpcApiTestForEthgetBlockByNumFromSolidityber() throws Exception { + + JsonArray params = new JsonArray(); + params.add(blockNumHex); + logger.info("46blockNumHex:" + blockNumHex); + params.add(true); + JsonObject requestBody = getJsonRpcBody("eth_getBlockByNumber", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + JSONObject getBlockByNumFromSolidityberResult = responseContent.getJSONObject("result"); + logger.info("getBlockByHashResult:" + getBlockByNumFromSolidityberResult); + + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("nonce")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("sha3Uncles")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("receiptsRoot")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("difficulty")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("totalDifficulty")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("extraData")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("baseFeePerGas")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("mixHash")); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("uncles"), new ArrayList<>().toString()); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("stateRoot"), "0x" + accountStateRoot); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("logsBloom"), + "0x00000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000000000000000" + + "000000000000000000000000000000000000000000000000000000000000000000000000" + + "000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000"); + Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("number"), blockNumHex); + Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("hash"), "0x" + bid); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("parentHash"), "0x" + parentHash); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("transactionsRoot"), "0x" + txTrieRoot); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("miner"), "0x" + witnessAddress.substring(2)); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); + Assert.assertEquals( + String.valueOf( + Long.parseLong( + getBlockByNumFromSolidityberResult.getString("gasLimit").substring(2), 16)), + feeLimit); + Assert.assertEquals( + Long.parseLong(getBlockByNumFromSolidityberResult.getString("timestamp").substring(2), 16), + blockTimeStamp); + logger.info("size:" + size); + Assert.assertEquals( + Long.parseLong(getBlockByNumFromSolidityberResult.getString("size").substring(2), 16), + size); + + JSONArray transactionsList = getBlockByNumFromSolidityberResult.getJSONArray("transactions"); + logger.info("transactionsList:" + transactionsList); + List transactionInfoListFromGetBlockByHash = new ArrayList<>(); + if (transactionsList.size() > 0) { + for (int i = 0; i < transactionsList.size(); i++) { + transactionInfoListFromGetBlockByHash.add(transactionsList.get(i).toString()); + } + } + List transactionInfoListFromTransactionByBlockNumberAndIndex = new ArrayList<>(); + for (int i = 0; i < transactionsList.size(); i++) { + JsonArray paramsForEthGetTransactionByBlockNumberAndIndex = new JsonArray(); + paramsForEthGetTransactionByBlockNumberAndIndex.add(blockNumHex); + String index = "0x" + Integer.toHexString(i); + logger.info("index:" + index); + paramsForEthGetTransactionByBlockNumberAndIndex.add(index); + logger.info( + "paramsForEthGetTransactionByBlockNumberAndIndex:" + + paramsForEthGetTransactionByBlockNumberAndIndex); + JsonObject requestBodyForTransactionByBlockNumberAndIndex = + getJsonRpcBody( + "eth_getTransactionByBlockNumberAndIndex", + paramsForEthGetTransactionByBlockNumberAndIndex); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForTransactionByBlockNumberAndIndex); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + result = responseContent.getJSONObject("result"); + logger.info("result:" + result); + transactionInfoListFromTransactionByBlockNumberAndIndex.add(result.toString()); + } + Assert.assertEquals( + transactionInfoListFromGetBlockByHash, + transactionInfoListFromTransactionByBlockNumberAndIndex); + } + + /** constructor. */ + @AfterClass + public void shutdown() throws InterruptedException { + if (channelFull != null) { + channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); + } + } +} From 8cedc371984b3d3a1d312feadf45e64a2adb65b1 Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Mon, 13 Dec 2021 18:00:40 +0800 Subject: [PATCH 14/24] add --- .../dailybuild/jsonrpc/Accounts002.java | 1427 +++++++++++++---- .../dailybuild/jsonrpc/Accounts003.java | 55 +- .../dailybuild/jsonrpc/Accounts004.java | 1376 +++------------- 3 files changed, 1429 insertions(+), 1429 deletions(-) diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java index 052accaaea5..735caf33130 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java @@ -1,373 +1,1242 @@ package stest.tron.wallet.dailybuild.jsonrpc; +import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.google.gson.JsonArray; import com.google.gson.JsonObject; +import io.grpc.ManagedChannelBuilder; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpResponse; import org.junit.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import org.tron.api.GrpcAPI; +import org.tron.api.WalletGrpc; +import org.tron.common.utils.ByteArray; +import org.tron.protos.Protocol.Block; import stest.tron.wallet.common.client.utils.HttpMethed; import stest.tron.wallet.common.client.utils.JsonRpcBase; +import stest.tron.wallet.common.client.utils.PublicMethed; @Slf4j public class Accounts002 extends JsonRpcBase { - JSONObject responseContent; - HttpResponse response; - String topic0 = null; - String topic1 = null; - String fromBlock = null; - String toBlock = null; - String newFilterResultIdfrom01 = null; - String newFilterResultIdfrom02 = null; + private JSONObject responseContent; + private HttpResponse response; + String realGasPrice; + String bid = null; + int indexNum = 0; + String indexHex = null; + JSONObject result = null; + String transacionHash = null; String blockHash = null; + String blockNumHex = null; + String parentHash = null; + String txTrieRoot = null; + String witnessAddress = null; + String feeLimit = null; + String accountStateRoot = null; + String energyUsed = "0x135c6"; - @Test(enabled = true, description = "Eth api of eth_newFilter contains nothing.") - public void test01GetNewFilterContainNothing() { - JsonObject paramBody = new JsonObject(); + List transactionIdList = null; + long size = 0; + long gas = 0; + long blockTimeStamp = 0; + long gasPriceFromHttp = 0; + + /** constructor. */ + @BeforeClass(enabled = true) + public void beforeClass() { + channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); + blockingStubFull = WalletGrpc.newBlockingStub(channelFull); + } + + @Test(enabled = true, description = "Json rpc api of eth_accounts") + public void test01JsonRpcApiTestForEthAccounts() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_accounts", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + List result = new ArrayList(); + logger.info(String.valueOf(result)); + Assert.assertEquals(responseContent.get("result"), result); + } + + @Test(enabled = true, description = "Json rpc api of eth_blockNumber") + public void test02JsonRpcApiTestForEthBlockNumber() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_blockNumber", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + responseContent.get("result"); + String blockNum = responseContent.getString("result").substring(2); + long blockNumFromjsonRpcNodeForSolidity = Long.parseLong(blockNum, 16); + response = HttpMethed.getNowBlockFromSolidity(solidityNode); + responseContent = HttpMethed.parseResponseContent(response); + long blockNumFromHttp = + responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); + logger.info("blocknumFromjsonRpcNodeForSolidity:" + blockNumFromjsonRpcNodeForSolidity); + logger.info("blocknumFromHttp:" + blockNumFromHttp); + Assert.assertTrue(Math.abs(blockNumFromjsonRpcNodeForSolidity - blockNumFromHttp) <= 3); + } + + @Test(enabled = true, description = "Json rpc api of eth_call") + public void test03JsonRpcApiTestForEthCall() throws Exception { + JsonObject param = new JsonObject(); + HttpMethed.waitToProduceOneBlock(httpFullNode); + param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); + param.addProperty("to", trc20AddressHex); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x0"); + param.addProperty("data", "0x06fdde03"); + JsonArray params = new JsonArray(); + params.add(param); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_call", params); + logger.info("03params:" + params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + Assert.assertEquals( + "0x000000000000000000000000000000000000000000000000000" + + "00000000000200000000000000000000000000000000000000000" + + "00000000000000000000000a546f6b656e5452433230000000000" + + "00000000000000000000000000000000000", + dataResult); + } + + @Test(enabled = true, description = "Json rpc api of eth_chainId") + public void test04JsonRpcApiTestForEthChainId() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_chainId", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + responseContent.get("result"); + String blockIdFromjsonRpcNodeForSolidity = + responseContent.get("result").toString().substring(2); + response = HttpMethed.getBlockByNumFromSolidity(solidityNode, 0); + responseContent = HttpMethed.parseResponseContent(response); + String blockIdFromHttp = responseContent.getString("blockID").substring(56); + logger.info("blockIdFromjsonRpcNodeForSolidity:" + blockIdFromjsonRpcNodeForSolidity); + logger.info("blockIdFromHttp:" + blockIdFromHttp); + Assert.assertEquals(blockIdFromjsonRpcNodeForSolidity, blockIdFromHttp); + } + + @Test(enabled = true, description = "Json rpc api of eth_coinbase") + public void test05JsonRpcApiTestForEthCoinbase() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_coinbase", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + + Assert.assertEquals( + "0x410be88a918d74d0dfd71dc84bd4abf036d0562991", responseContent.getString("result")); + } + + @Test(enabled = true, description = "Json rpc api of eth_estimateGas") + public void test06JsonRpcApiTestForEthEstimateGas() throws Exception { + JsonObject param = new JsonObject(); + param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); + param.addProperty("to", trc20AddressHex); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x0"); + param.addProperty("data", "0x1249c58b"); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("test06requestBody:" + requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + Assert.assertEquals("0x147", dataResult); + } + + @Test(enabled = true, description = "Json rpc api of eth_estimateGasHasPayable") + public void test07JsonRpcApiTestForEthEstimateGasHasPayable() throws Exception { + response = HttpMethed.getTransactionInfoByIdFromSolidity(solidityNode, txid); + responseContent = HttpMethed.parseResponseContent(response); + Long realEnergyUsed = responseContent.getJSONObject("receipt").getLong("energy_usage_total"); + logger.info("realEnergyUsed:" + realEnergyUsed); + JsonObject param = new JsonObject(); + param.addProperty("from", "0x" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2)); + param.addProperty("to", "0x" + contractAddressFrom58); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x1389"); + param.addProperty("data", data); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("test07requestBody:" + requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + Assert.assertEquals((long) realEnergyUsed, Long.parseLong(dataResult.substring(2), 16)); + } + + @Test(enabled = true, description = "Json rpc api of eth_estimateGasWithoutTo") + public void test08JsonRpcApiTestForEthEstimateGasWithoutTo() throws Exception { + JsonObject param = new JsonObject(); + param.addProperty("from", "0x6C0214C9995C6F3A61AB23F0EB84B0CDE7FD9C7C"); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x0"); + param.addProperty( + "data", + "0x6080604052d3600055d2600155346002556101418061001f6000396000f30060806040" + + "52600436106100565763ffffffff7c010000000000000000000000000000000000000000" + + "000000000000000060003504166305c24200811461005b5780633be9ece7146100815780" + + "6371dc08ce146100aa575b600080fd5b6100636100b2565b6040805193845260208401929" + + "0925282820152519081900360600190f35b6100a873ffffffffffffffffffffffffffffff" + + "ffffffffff600435166024356044356100c0565b005b61006361010d565b60005460015460" + + "0254909192565b60405173ffffffffffffffffffffffffffffffffffffffff841690821561" + + "08fc029083908590600081818185878a8ad0945050505050158015610107573d6000803e3d" + + "6000fd5b50505050565bd3d2349091925600a165627a7a72305820a2fb39541e90eda9a2f5" + + "f9e7905ef98e66e60dd4b38e00b05de418da3154e757002900000000000000000000000000" + + "00000000000000000000000000000090fa17bb"); JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test01GetNewFilterContainNothing_requestBody " + requestBody); + params.add(param); + JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("test08requestBody:" + requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + logger.info("dataResult:" + dataResult); + Assert.assertEquals(energyUsed, dataResult); + } + + @Test(enabled = true, description = "Json rpc api of eth_estimateGasSendTrx") + public void test09JsonRpcApiTestForEthEstimateGasSendTrx() throws Exception { + JsonObject param = new JsonObject(); + param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); + param.addProperty("to", "0xC1A74CD01732542093F5A87910A398AD70F04BD7"); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x1"); + param.addProperty("data", "0x0"); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("test09requestBody:" + requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + Assert.assertEquals("0x0", dataResult); + } + + @Test(enabled = true, description = "Json rpc api of eth_gasPrice") + public void test10JsonRpcApiTestForEthGasPrice() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_gasPrice", params); response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test01GetNewFilterContainNothing_responseContent" + responseContent); - logger.info("result:" + responseContent.getString("result")); - Assert.assertNotNull(responseContent.getString("result")); + responseContent.get("result"); + String gasPrice = responseContent.get("result").toString().substring(2); + long gasPriceFromJsonrpc = Long.parseLong(gasPrice, 16); + logger.info(String.valueOf(gasPriceFromJsonrpc)); + response = HttpMethed.getChainParameters(httpFullNode); + responseContent = HttpMethed.parseResponseContent(response); + JSONArray temp; + temp = responseContent.getJSONArray("chainParameter"); + for (int i = 0; i < temp.size(); i++) { + if (temp.getJSONObject(i).get("key").equals("getEnergyFee")) { + gasPriceFromHttp = temp.getJSONObject(i).getLong("value"); + } + } + logger.info("gasPriceFromHttp:" + gasPriceFromHttp); + Assert.assertEquals(gasPriceFromJsonrpc, gasPriceFromHttp); } - @Test( - enabled = true, - description = "Eth api of eth_newFilter contains address,fromBlock and toBlock.") - public void test02GetNewFilterContainAddress() { - if (blockNumForTrc20 - 10 < 0) { - fromBlock = "0"; + @Test(enabled = true, description = "Json rpc api of eth_getBalance") + public void test11JsonRpcApiTestForEthGetBalance() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x" + ByteArray.toHexString(foundationAccountAddress).substring(2)); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getBalance", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String balance = responseContent.getString("result").substring(2); + Long balance1 = Long.parseLong(balance, 16); + logger.info("balance1:" + balance1); + response = HttpMethed.getAccountFromSolidity(solidityNode, foundationAccountAddress); + responseContent = HttpMethed.parseResponseContent(response); + Long balance2 = responseContent.getLong("balance"); + logger.info(balance1.toString()); + logger.info(balance2.toString()); + Assert.assertEquals(balance1, balance2); + } + + @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") + public void test12JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { + response = HttpMethed.getNowBlockFromSolidity(solidityNode); + responseContent = HttpMethed.parseResponseContent(response); + JsonArray params = new JsonArray(); + params.add("earliest"); + JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String transactionNum = responseContent.getString("result").substring(2); + int transactionNum1 = Integer.parseInt(transactionNum, 16); + logger.info(String.valueOf(transactionNum1)); + response = HttpMethed.getTransactionCountByBlocknumFromSolidity(solidityNode, 0); + responseContent = HttpMethed.parseResponseContent(response); + int transactionNum2 = responseContent.getInteger("count"); + logger.info(String.valueOf(transactionNum2)); + Assert.assertEquals(transactionNum1, transactionNum2); + } + + @Test(enabled = true, description = "Json rpc api of eth_getCode") + public void test13JsonRpcApiTestForEthGetCode() throws Exception { + + JsonArray params = new JsonArray(); + params.add(contractAddressFrom58); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getCode", params); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String codeFromJsonRpc = responseContent.getString("result").substring(2); + logger.info(codeFromJsonRpc); + response = HttpMethed.getContractInfo(httpFullNode, contractAddressFrom58); + logger.info("13contractAddressFrom58:" + contractAddressFrom58); + responseContent = HttpMethed.parseResponseContent(response); + String codeFromHttp = responseContent.getString("runtimecode"); + logger.info(codeFromHttp); + Assert.assertEquals(codeFromJsonRpc, codeFromHttp); + } + + @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") + public void test14JsonRpcApiTestForEthGetStorageAt01() throws Exception { + + JsonArray params = new JsonArray(); + params.add(contractAddressFrom58); + params.add("0x0"); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("14responseContent:" + responseContent); + String result = responseContent.getString("result").substring(2); + long resultExpect = Long.parseLong(result, 16); + logger.info("result:" + resultExpect); + Assert.assertEquals("1234", String.valueOf(resultExpect)); + } + + @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") + public void test15JsonRpcApiTestForEthGetStorageAt02() throws Exception { + + String address = + "000000000000000000000000" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2); + String str = address + "0000000000000000000000000000000000000000000000000000000000000001"; + logger.info("str:" + str); + JsonArray paramsForSha3 = new JsonArray(); + paramsForSha3.add(str); + JsonObject requestBodyForSha3 = getJsonRpcBody("web3_sha3", paramsForSha3); + logger.info("requestBodyForSha3:" + requestBodyForSha3); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForSha3); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + String resultForSha3 = responseContent.getString("result"); + logger.info("resultForSha3:" + resultForSha3); + JsonArray params = new JsonArray(); + params.add(contractAddressFrom58); + params.add(resultForSha3); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("15responseContent:" + responseContent); + String result = responseContent.getString("result").substring(2); + logger.info("15result:" + result); + logger.info("mapResult:" + Integer.parseInt(result, 16)); + Assert.assertEquals("5678", String.valueOf(Integer.parseInt(result, 16))); + } + + @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockNumberAndIndex") + public void test16JsonRpcApiTestForEthGetTransactionByBlockNumberAndIndex() throws Exception { + logger.info("16blockNum:" + blockNum); + blockNumHex = "0x" + Integer.toHexString(blockNum); + logger.info("blockNumHex:" + blockNumHex); + JsonArray params = new JsonArray(); + params.add(blockNumHex); + indexNum = 0; + response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNum); + responseContent = HttpMethed.parseResponseContent(response); + parentHash = + responseContent + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getString("parentHash"); + txTrieRoot = + responseContent + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getString("txTrieRoot"); + witnessAddress = + responseContent + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getString("witness_address"); + feeLimit = + responseContent + .getJSONArray("transactions") + .getJSONObject(0) + .getJSONObject("raw_data") + .getString("fee_limit"); + logger.info(feeLimit); + + JSONObject getBlockByNumFromSolidityResult = null; + for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { + if (txid.equals( + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { + indexNum = i; + getBlockByNumFromSolidityResult = + responseContent.getJSONArray("transactions").getJSONObject(i); + bid = responseContent.getString("blockID"); + break; + } + } + transactionIdList = new ArrayList<>(); + if (responseContent.getJSONArray("transactions").size() > 0) { + for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { + transactionIdList.add( + "0x" + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID")); + } + } + logger.info("16transactionIdList:" + transactionIdList); + logger.info(String.valueOf(indexNum)); + indexHex = "0x" + Integer.toHexString(indexNum); + logger.info("indexHex:" + indexHex); + params.add(indexHex); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockNumberAndIndex", params); + logger.info("13requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + result = responseContent.getJSONObject("result"); + logger.info("16 result" + result); + Map jsonrpcResult = new HashMap(); + for (Map.Entry entry : result.entrySet()) { + jsonrpcResult.put(entry.getKey(), entry.getValue()); + } + transacionHash = jsonrpcResult.get("hash").toString(); + logger.info("transactionHash:" + transacionHash); + blockHash = jsonrpcResult.get("blockHash").toString(); + logger.info("jsonrpcResult:" + jsonrpcResult); + response = HttpMethed.getTransactionInfoByBlocknumFromSolidity(solidityNode, blockNum); + logger.info("response:" + response); + List responseContent1 = HttpMethed.parseResponseContentArray(response); + logger.info("responseContent1:" + responseContent1); + blockTimeStamp = responseContent1.get(0).getLong("blockTimeStamp"); + + for (int i = 0; i < responseContent1.size(); i++) { + if (responseContent1.get(i).getString("id").equals(transactionIdList.get(0).substring(2))) { + gas = responseContent1.get(i).getJSONObject("receipt").getLong("energy_usage_total"); + logger.info("gas:" + gas); + break; + } + } + + Assert.assertEquals(jsonrpcResult.get("gas").toString(), "0x" + Long.toHexString(gas)); + Assert.assertNull(jsonrpcResult.get("nonce")); + Assert.assertEquals( + jsonrpcResult.get("hash").toString(), + "0x" + getBlockByNumFromSolidityResult.getString("txID")); + Assert.assertEquals(jsonrpcResult.get("blockHash").toString(), "0x" + bid); + Assert.assertEquals(jsonrpcResult.get("blockNumber").toString(), blockNumHex); + Assert.assertEquals(jsonrpcResult.get("transactionIndex").toString(), indexHex); + Assert.assertEquals( + jsonrpcResult.get("from").toString(), + "0x" + + getBlockByNumFromSolidityResult + .getJSONObject("raw_data") + .getJSONArray("contract") + .getJSONObject(0) + .getJSONObject("parameter") + .getJSONObject("value") + .getString("owner_address") + .substring(2)); + Assert.assertEquals( + jsonrpcResult.get("to").toString(), + "0x" + + getBlockByNumFromSolidityResult + .getJSONObject("raw_data") + .getJSONArray("contract") + .getJSONObject(0) + .getJSONObject("parameter") + .getJSONObject("value") + .getString("contract_address") + .substring(2)); + + Assert.assertEquals(jsonrpcResult.get("value").toString(), "0x1389"); + String data; + if (getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data") == null) { + data = "0x"; } else { - fromBlock = "0x" + Integer.toHexString(blockNumForTrc20 - 10); + data = + getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data").substring(2); } - toBlock = "0x" + Integer.toHexString(blockNumForTrc20 + 10); - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test02GetNewFilterContainAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + Assert.assertEquals(jsonrpcResult.get("input").toString(), data); + + long temp = + Long.parseLong( + getBlockByNumFromSolidityResult.getString("signature").substring(130, 131), 16); + long v = + Long.parseLong( + getBlockByNumFromSolidityResult.getString("signature").substring(130, 132), 16); + if (temp < 27) { + v += 27; + } + Assert.assertEquals(Long.parseLong(jsonrpcResult.get("v").toString().substring(2), 16), v); + Assert.assertEquals( + jsonrpcResult.get("r").toString().substring(2), + getBlockByNumFromSolidityResult.getString("signature").substring(2, 66)); + Assert.assertEquals( + jsonrpcResult.get("s").toString().substring(2), + getBlockByNumFromSolidityResult.getString("signature").substring(66, 130)); + } + + @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByHash") + public void test17JsonRpcApiTestForEthGetBlockTransactionCountByHash() throws Exception { + logger.info("blockNum:" + blockNum); + JsonArray params = new JsonArray(); + params.add(blockHash); + logger.info("blockHash:" + blockHash); + JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByHash", params); + logger.info("requestBody:" + requestBody); + HttpMethed.waitToProduceOneBlock(httpFullNode); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test02GetNewFilterContainAddress_responseContent" + responseContent); - newFilterResultIdfrom01 = responseContent.getString("result"); - logger.info("test02GetNewFilterContainAddress_id:" + responseContent.getString("result")); + logger.info("responseContent:" + responseContent); + String transactionNum = responseContent.getString("result").substring(2); + int transactionNumFromjsonRpcNodeForSolidity = Integer.parseInt(transactionNum, 16); + logger.info( + "transactionNumFromjsonRpcNodeForSolidity:" + transactionNumFromjsonRpcNodeForSolidity); + response = HttpMethed.getTransactionCountByBlocknumFromSolidity(solidityNode, blockNum); + responseContent = HttpMethed.parseResponseContent(response); + int transactionNumFromHttp = responseContent.getInteger("count"); + logger.info("transactionNumFromHttp:" + transactionNumFromHttp); + Assert.assertEquals(transactionNumFromHttp, transactionNumFromjsonRpcNodeForSolidity); } - @Test( - enabled = true, - description = "Eth api of eth_newFilter contains topic fromBlock and toBlock.") - public void test03GetNewFilterContainTopic() { - response = HttpMethed.getBlockByNum(httpFullNode, blockNumForTrc20); + @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") + public void test18JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { + JsonArray params = new JsonArray(); + params.add(blockNum); + logger.info(String.valueOf(blockNum)); + JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("response:" + response); + HttpMethed.waitToProduceOneBlock(httpFullNode); responseContent = HttpMethed.parseResponseContent(response); logger.info("responseContent:" + responseContent); - logger.info("blockHash:" + responseContent.getString("blockID")); - - blockHash = responseContent.getString("blockID"); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - JsonObject paramBody = new JsonObject(); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test03GetNewFilterContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + String transactionNum = responseContent.getString("result").substring(2); + int transactionNum1 = Integer.parseInt(transactionNum, 16); + logger.info(String.valueOf(transactionNum1)); + response = HttpMethed.getTransactionCountByBlocknumFromSolidity(solidityNode, blockNum); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test03GetNewFilterContainTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - newFilterResultIdfrom02 = responseContent.getString("result"); - logger.info("test03GetNewFilterContainTopic_id:" + newFilterResultIdfrom02); + int transactionNum2 = responseContent.getInteger("count"); + logger.info(String.valueOf(transactionNum2)); + Assert.assertEquals(transactionNum1, transactionNum2); } - @Test(enabled = true, description = "Eth api of eth_newFilter contains topic and address.") - public void test04GetNewFilterContainsTopicAndAddress() { + @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockHashAndIndex") + public void test19JsonRpcApiTestForEthGetTransactionByBlockHashAndIndex() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x" + bid); + params.add(indexHex); + logger.info("indexHex:" + indexHex); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockHashAndIndex", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject resultForGetTransactionByBlockHashAndIndex = responseContent.getJSONObject("result"); + Assert.assertEquals(result, resultForGetTransactionByBlockHashAndIndex); + } - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); + @Test(enabled = true, description = "Json rpc api of eth_getTransactionByHash") + public void test20JsonRpcApiTestForEthGetTransactionByHash() throws Exception { JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test04GetNewFilterContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + params.add(transacionHash); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionByHash", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test04GetNewFilterContainsTopicAndAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); + JSONObject result1 = responseContent.getJSONObject("result"); + Assert.assertEquals(result, result1); } - @Test(enabled = true, description = "Eth api of eth_newFilter only contain topic and blockHash.") - public void test05GetNewFilterOnlyContainTopic() { - JsonObject paramBody = new JsonObject(); - paramBody.addProperty("blockHash", blockHash); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - paramBody.add("topics", topicArray); + @Test(enabled = true, description = "Json rpc api of eth_getTransactionReceipt") + public void test21JsonRpcApiTestForEthGetTransactionReceipt() throws Exception { JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test05GetNewFilterOnlyContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + Thread.sleep(6000); + params.add(trc20Txid); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionReceipt", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("response:" + response); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject resultFromTransactionReceipt = responseContent.getJSONObject("result"); + logger.info("resultFromTransactionReceipt:" + resultFromTransactionReceipt); + JSONArray logs = resultFromTransactionReceipt.getJSONArray("logs"); + logger.info("logs:" + logs); + logger.info("result:" + resultFromTransactionReceipt.toString()); + response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNumForTrc20); + responseContent = HttpMethed.parseResponseContent(response); + int index = 0; + for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { + if (trc20Txid.equals( + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { + index = i; + break; + } + } + + JsonArray paramsForTransactionByBlockNumberAndIndex = new JsonArray(); + paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(blockNumForTrc20)); + paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(index)); + JsonObject requestBody1 = + getJsonRpcBody( + "eth_getTransactionByBlockNumberAndIndex", paramsForTransactionByBlockNumberAndIndex); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); + logger.info("requestBody1:" + requestBody1); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject resultFromTransactionByBlockNumberAndIndex = responseContent.getJSONObject("result"); + logger.info( + "resultFromTransactionByBlockNumberAndIndex:" + resultFromTransactionByBlockNumberAndIndex); + Assert.assertEquals( + resultFromTransactionReceipt.getString("blockHash"), + resultFromTransactionByBlockNumberAndIndex.getString("blockHash")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("blockNumber"), + resultFromTransactionByBlockNumberAndIndex.getString("blockNumber")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("transactionIndex"), + resultFromTransactionByBlockNumberAndIndex.getString("transactionIndex")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("transactionHash"), "0x" + trc20Txid); + Assert.assertEquals( + resultFromTransactionReceipt.getString("from"), + resultFromTransactionByBlockNumberAndIndex.getString("from")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("to"), + resultFromTransactionByBlockNumberAndIndex.getString("to")); + logger.info("effectiveGasPrice:" + resultFromTransactionReceipt.getString("effectiveGasPrice")); + logger.info("gasPriceFromHttp:" + Long.toHexString(gasPriceFromHttp)); + Assert.assertEquals( + resultFromTransactionReceipt.getString("effectiveGasPrice"), + "0x" + Long.toHexString(gasPriceFromHttp)); + /* Assert.assertEquals( + resultFromTransactionReceipt.getString("contractAddress").substring(2), + trc20AddressHex.substring(2));*/ + Assert.assertNull(resultFromTransactionReceipt.getString("contractAddress")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("logsBloom"), + "0x000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000"); + Assert.assertEquals("0x1", resultFromTransactionReceipt.getString("status")); + Assert.assertEquals("0x0", resultFromTransactionReceipt.getString("type")); + logger.info("gas:" + resultFromTransactionByBlockNumberAndIndex.getString("gas")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("gasUsed"), + resultFromTransactionByBlockNumberAndIndex.getString("gas")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("cumulativeGasUsed"), + resultFromTransactionByBlockNumberAndIndex.getString("gas")); + Assert.assertEquals( + logs.getJSONObject(0).getString("logIndex"), "0x" + Integer.toHexString(index)); + Assert.assertEquals(logs.getJSONObject(0).getString("removed"), "false"); + Assert.assertEquals( + logs.getJSONObject(0).getString("blockHash"), + resultFromTransactionReceipt.getString("blockHash")); + Assert.assertEquals( + logs.getJSONObject(0).getString("blockNumber"), + resultFromTransactionReceipt.getString("blockNumber")); + Assert.assertEquals( + logs.getJSONObject(0).getString("transactionIndex"), + resultFromTransactionReceipt.getString("transactionIndex")); + Assert.assertEquals( + logs.getJSONObject(0).getString("transactionHash"), + resultFromTransactionReceipt.getString("transactionHash")); + Assert.assertEquals( + logs.getJSONObject(0).getString("address"), resultFromTransactionReceipt.getString("to")); + response = HttpMethed.getTransactionInfoByBlocknumFromSolidity(solidityNode, blockNumForTrc20); + List responseContent1 = HttpMethed.parseResponseContentArray(response); + logger.info("responseContent1:" + responseContent1); + + response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNumForTrc20); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test05GetNewFilterOnlyContainTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); + Assert.assertEquals( + logs.getJSONObject(0).getString("data").substring(2), + responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("data")); + + Assert.assertEquals( + logs.getJSONObject(0).getString("topics").replace("0x", ""), + responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("topics")); } - @Test(enabled = true, description = "Eth api of eth_newFilter which only contains blockHash.") - public void test06GetNewFilterHasOnlyBlockHash() { + @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockHashAndIndex") + public void test22JsonRpcApiTestForEthGetUncleByBlockHashAndIndex() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); + params.add("0x"); + JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockHashAndIndex", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertNull(result); + } - response = HttpMethed.getNowBlock(httpFullNode); + @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockNumberAndIndex") + public void test23JsonRpcApiTestForEthGetUncleByBlockNumberAndIndex() throws Exception { + JsonArray params = new JsonArray(); + params.add("0xeb82f0"); + params.add("0x"); + JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockNumberAndIndex", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - String blockHash = responseContent.getString("blockID"); - JsonObject paramBody = new JsonObject(); - paramBody.addProperty("blockHash", blockHash); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertNull(result); + } + + @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockHash") + public void test24JsonRpcApiTestForEthGetUncleCountByBlockHash() throws Exception { JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test06GetNewFilterHasOnlyBlockHash_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); + JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockHash", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test06GetNewFilterHasOnlyBlockHash_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertEquals(result, "0x0"); } - @Test(enabled = true, description = "Eth api of eth_newFilter check new and after block.") - public void test07GetNewFilterCheckNewBlock() { - JsonObject paramBody = new JsonObject(); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - paramBody.add("topics", topicArray); + @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockNumber") + public void test25JsonRpcApiTestForEthGetUncleCountByBlockNumber() throws Exception { JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test07GetNewFilterCheckNewBlock_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + params.add("eth_getUncleCountByBlockNumber"); + JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockNumber", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test07GetNewFilterCheckNewBlock_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertEquals(result, "0x0"); } - @Test(enabled = true, description = "Eth api of eth_newBlockFilter") - public void test08GetEthNewBlockFilter() { + @Test(enabled = true, description = "Json rpc api of eth_getWork") + public void test26JsonRpcApiTestForEthGetWork() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_getWork", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + int resultLen = result.length(); + String resultFromjsonRpcNodeForSolidity = result.substring(4, resultLen - 12); + response = HttpMethed.getNowBlockFromSolidity(solidityNode); + responseContent = HttpMethed.parseResponseContent(response); + String resultFromHttp = responseContent.getString("blockID"); + logger.info("resultFromjsonRpcNodeForSolidity:" + resultFromjsonRpcNodeForSolidity); + logger.info("resultFromHttp:" + resultFromHttp); + Assert.assertEquals(resultFromjsonRpcNodeForSolidity, resultFromHttp); + } + @Test(enabled = true, description = "Json rpc api of eth_hashrate") + public void test27JsonRpcApiTestForEthHashRate() throws Exception { JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test08GetEthNewBlockFilter_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + JsonObject requestBody = getJsonRpcBody("eth_hashrate", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test08GetEthNewBlockFilter_responseContent:" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertEquals("0x0", result); } - @Test(enabled = true, description = "Eth api of eth_getFilterChanges has less 20 elements.") - public void test09GetFilterChanges() { + @Test(enabled = true, description = "Json rpc api of eth_mining") + public void test28JsonRpcApiTestForEthMining() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_mining", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertEquals(result, "true"); + } + @Test(enabled = true, description = "Json rpc api of eth_protocolVersion") + public void test29JsonRpcApiTestForEthProtocolVersion() throws Exception { JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + JsonObject requestBody = getJsonRpcBody("eth_protocolVersion", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); - String ethNewBlockFilterResult = responseContent.get("result").toString(); - logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); - String newFilterId = responseContent.getString("result"); - logger.info("newFilterId:" + newFilterId); - params = new JsonArray(); - params.add(newFilterId); - requestBody = getJsonRpcBody("eth_getFilterChanges", params); - logger.info("test09GetFilterChanges_requestBody: " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + String protocolVersion = responseContent.getString("result").substring(2); + Long protocolVersion1 = Long.parseLong(protocolVersion, 16); + response = HttpMethed.getNowBlockFromSolidity(solidityNode); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test09GetFilterChanges_responseContent:" + responseContent); - Assert.assertEquals("[]", responseContent.getString("result")); + Long protocolVersion2 = + responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("version"); + logger.info(protocolVersion1.toString()); + logger.info(protocolVersion2.toString()); + Assert.assertEquals(protocolVersion1, protocolVersion2); } - @Test( - enabled = true, - description = "Eth api of eth_getLogs contains address ,fromBlock and toBlock.") - public void test10GetLogsOnlyContainAddress() { - JsonArray addressArray = new JsonArray(); - logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); - addressArray.add(contractTrc20AddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - logger.info("blockNumForTrc20:" + blockNumForTrc20); - paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 20))); - paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 20))); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); - logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + @Test(enabled = true, description = "Json rpc api of eth_syncing") + public void test30JsonRpcApiTestForEthSyncing() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_syncing", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test10GetLogsOnlyContainAddress_responseContent:" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - String address = - responseContent.getJSONArray("result").getJSONObject(0).getString("address").substring(2); - Assert.assertEquals(address, contractTrc20AddressFrom58.substring(2)); - topic0 = responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); - } - - @Test(enabled = true, description = "Eth api of eth_getLogs both contains topic and address.") - public void test11GetLogsContainsTopicAndAddress() { - JsonArray topicArray = new JsonArray(); - topicArray.add(topic0); - JsonObject paramBody = new JsonObject(); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 10))); - paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 10))); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); - logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + JSONObject temp = responseContent.getJSONObject("result"); + String currentNumFromRpc = temp.getString("currentBlock"); + logger.info(currentNumFromRpc); + logger.info(temp.toString()); + response = HttpMethed.getNowBlockFromSolidity(solidityNode); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test11GetLogsContainsTopicAndAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - String topicFromResult = - responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); - Assert.assertEquals(topicFromResult, topic0); + long currentNum = + responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); + logger.info("currentNum:" + currentNum); + logger.info("currentNumFromRpc:" + Long.parseLong(currentNumFromRpc.substring(2), 16)); + Assert.assertEquals(currentNum, Long.parseLong(currentNumFromRpc.substring(2), 16)); + Assert.assertTrue(temp.containsKey("startingBlock")); + Assert.assertTrue(temp.containsKey("currentBlock")); + Assert.assertTrue(temp.containsKey("highestBlock")); } - @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") - public void test12GetFilterLogsContainsAddress() { + @Test(enabled = true, description = "Json rpc api of net_listening") + public void test31JsonRpcApiTestForNetListening() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("net_listening", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + Boolean temp = responseContent.getBoolean("result"); + logger.info(temp.toString()); + response = HttpMethed.getNodeInfo(solidityNode); + responseContent = HttpMethed.parseResponseContent(response); + boolean expect = false; + int num = responseContent.getInteger("activeConnectCount"); + if (num >= 1) { + expect = true; + } + Assert.assertEquals(temp, expect); + } + @Test(enabled = true, description = "Json rpc api of net_peerCount") + public void test32JsonRpcApiTestForNetPeerCount() throws Exception { JsonArray params = new JsonArray(); - params.add(newFilterResultIdfrom01); - JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); - logger.info("test12GetFilterLogsContainsAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + JsonObject requestBody = getJsonRpcBody("net_peerCount", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test12GetFilterLogsContainsAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertNotNull(result); } - @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") - public void test13GetFilterLogsContainsTopic() { + @Test(enabled = true, description = "Json rpc api of net_version") + public void test33JsonRpcApiTestForEthVersion() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("net_version", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String firstBlockHashFromJsonRpc = responseContent.getString("result").substring(2); + response = HttpMethed.getBlockByNumFromSolidity(solidityNode, 0); + responseContent = HttpMethed.parseResponseContent(response); + String firstBlockHashFromHttp = responseContent.getString("blockID").substring(56); + logger.info("firstBlockHashFromJsonRpc" + firstBlockHashFromJsonRpc); + logger.info("firstBlockHashFromHttp" + firstBlockHashFromHttp); + Assert.assertEquals(firstBlockHashFromJsonRpc, firstBlockHashFromHttp); + } + @Test(enabled = true, description = "Json rpc api of web3_clientVersion") + public void test34JsonRpcApiTestForWeb3ClientVersion() throws Exception { JsonArray params = new JsonArray(); - params.add(newFilterResultIdfrom02); - JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); - logger.info("test13GetFilterLogsContainsTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + JsonObject requestBody = getJsonRpcBody("web3_clientVersion", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test13GetFilterLogsContainsTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); + String result = responseContent.getString("result"); + List resultList = new ArrayList<>(); + for (String str : result.split("/")) { + resultList.add(str); + } + Assert.assertEquals(resultList.size(), 5); + Assert.assertEquals(resultList.get(0), "TRON"); + Assert.assertEquals(resultList.get(1).substring(0, 1), "v"); + Assert.assertEquals(resultList.get(2), "Linux"); + Assert.assertEquals(resultList.get(3), "Java1.8"); + Assert.assertEquals(resultList.get(4).substring(0, 11), "GreatVoyage"); } - @Test( - enabled = true, - description = - "Eth api of eth_uninstallFilter which method is eth_newFilter" - + " and params has one element ") - public void test14EthUninstallFilter() { - // create ID - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.addProperty("fromBlock", "0x1f8b6a7"); - paramBody.addProperty("toBlock", "0x1f8b6a7"); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test14_newfilter " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + @Test(enabled = true, description = "Json rpc api of web3_sha3") + public void test35JsonRpcApiTestForWeb3Sha3() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x08"); + JsonObject requestBody1 = getJsonRpcBody("web3_sha3", params); + response = getEthHttps(ethHttpsNode, requestBody1); + responseContent = HttpMethed.parseResponseContent(response); + String result1 = responseContent.getString("result"); + JsonObject requestBody2 = getJsonRpcBody("web3_sha3", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody2); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_newfilter_responseContentr" + responseContent); - String ethNewFilterResult = responseContent.get("result").toString(); - logger.info("EthNewFilterResult:" + ethNewFilterResult); - Assert.assertNotNull(responseContent.getString("result")); + String result2 = responseContent.getString("result"); + Assert.assertEquals(result1, result2); + } - // verify ID invalid + @Test(enabled = true, description = "Json rpc api of eth_compileLLL") + public void test36JsonRpcApiTestForEthCompileLll() throws Exception { + JsonArray params = new JsonArray(); + params.add("(returnlll (suicide (caller)))"); + JsonObject requestBody1 = getJsonRpcBody("eth_compileLLL", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals(errorMessage, "the method eth_compileLLL does not exist/is not available"); + } - // first time - params = new JsonArray(); - params.add(responseContent.get("result").toString()); - requestBody = getJsonRpcBody("eth_uninstallFilter", params); - logger.info("test14_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + @Test(enabled = true, description = "Json rpc api of eth_compileSerpent") + public void test37JsonRpcApiTestForEthCompileSerpent() throws Exception { + JsonArray params = new JsonArray(); + params.add("/* some serpent */"); + JsonObject requestBody = getJsonRpcBody("eth_compileSerpent", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_eth_uninstallFilter_responseContentr_first" + responseContent); - Assert.assertEquals(responseContent.get("result"), true); - // second time - logger.info("test14_eth_uninstallFilter_second " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_compileSerpent does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_compileSolidity") + public void test38JsonRpcApiTestForEthCompileSolidity() throws Exception { + JsonArray params = new JsonArray(); + params.add("contract test { function multiply(uint a) returns(uint d) { return a * 7; } }"); + JsonObject requestBody = getJsonRpcBody("eth_compileSolidity", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_eth_uninstallFilter_responseContentr_second " + responseContent); + String errorMessage = responseContent.getJSONObject("error").getString("message"); Assert.assertEquals( - responseContent.getJSONObject("error").getString("message"), "filter not found"); + errorMessage, "the method eth_compileSolidity does not exist/is not available"); + } - // query getFilterChanges to verify ID has invalid - params = new JsonArray(); - params.add(ethNewFilterResult); - requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNode, requestBody); + @Test(enabled = true, description = "Json rpc api of eth_getCompilers") + public void test39JsonRpcApiTestForEthCompileSolidity() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_getCompilers", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14EthUninstallFilter_responseContent" + responseContent); - String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; - Assert.assertEquals(responseContent.get("error").toString(), expectResult); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_getCompilers does not exist/is not available"); } - @Test( - enabled = true, - description = - "Eth api of eth_uninstallFilter which method is eth_newBlockFilter" - + " and params has one element ") - public void test15EthUninstallFilter() { - // create ID + @Test(enabled = true, description = "Json rpc api of eth_getTransactionCount") + public void test40JsonRpcApiTestForEthGetTransactionCount() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x407d73d8a49eeb85d32cf465507dd71d507100c1"); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionCount", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_getTransactionCount does not exist/is not available"); + } + @Test(enabled = true, description = "Json rpc api of eth_sendRawTransaction") + public void test41JsonRpcApiTestForEthSendRawTransaction() throws Exception { JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + params.add("0x234"); + JsonObject requestBody = getJsonRpcBody("eth_sendRawTransaction", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); - String ethNewBlockFilterResult = responseContent.get("result").toString(); - logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); - Assert.assertNotNull(responseContent.getString("result")); - - // verify ID invalid - // first time - params = new JsonArray(); - params.add(responseContent.get("result").toString()); - requestBody = getJsonRpcBody("eth_uninstallFilter", params); - logger.info("test15_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_sendRawTransaction does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_sendTransaction") + public void test42JsonRpcApiTestForEthSendTransaction() throws Exception { + JsonArray params = new JsonArray(); + JsonObject temp = new JsonObject(); + params.add(temp); + temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); + temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); + temp.addProperty("gas", "0x76c0"); + temp.addProperty("gasPrice", "0x9184e72a000"); + temp.addProperty( + "data", + "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); + temp.addProperty("value", "0x9184e72a"); + + JsonObject requestBody = getJsonRpcBody("eth_sendTransaction", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15_eth_uninstallFilter_responseContentr_first" + responseContent); - Assert.assertEquals(responseContent.get("result"), true); - // second time - response = getJsonRpc(jsonRpcNode, requestBody); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_sendTransaction does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_sign") + public void test43JsonRpcApiTestForEthSign() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); + params.add("0xdeadbeaf"); + JsonObject requestBody = getJsonRpcBody("eth_sign", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15_eth_uninstallFilter_responseContentr_second" + responseContent); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals(errorMessage, "the method eth_sign does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_signTransaction") + public void test44JsonRpcApiTestForEthSignTransaction() throws Exception { + JsonArray params = new JsonArray(); + JsonObject temp = new JsonObject(); + params.add(temp); + temp.addProperty( + "data", + "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); + temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); + temp.addProperty("gas", "0x76c0"); + temp.addProperty("gasPrice", "0x9184e72a000"); + temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); + temp.addProperty("value", "0x9184e72a"); + + JsonObject requestBody = getJsonRpcBody("eth_signTransaction", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); Assert.assertEquals( - responseContent.getJSONObject("error").getString("message"), "filter not found"); - // query getFilterChanges to verify ID has invalid - params = new JsonArray(); - params.add(ethNewBlockFilterResult); - requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNode, requestBody); + errorMessage, "the method eth_signTransaction does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_submitWork") + public void test45JsonRpcApiTestForEthSubmitWork() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x0000000000000001"); + params.add("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"); + params.add("0xD1GE5700000000000000000000000000D1GE5700000000000000000000000000"); + JsonObject requestBody = getJsonRpcBody("eth_submitWork", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_responseContent" + responseContent); - String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; - Assert.assertEquals(responseContent.get("error").toString(), expectResult); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals(errorMessage, "the method eth_submitWork does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of parity_nextNonce") + public void test46JsonRpcApiTestForParityNextNonce() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); + JsonObject requestBody = getJsonRpcBody("parity_nextNonce", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method parity_nextNonce does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_submitHashrate") + public void test47JsonRpcApiTestForEthSubmitHashrate() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x0000000000000000000000000000000000000000000000000000000000500000"); + params.add("0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c"); + JsonObject requestBody = getJsonRpcBody("eth_submitHashrate", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_submitHashrate does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_getBlockByHash params is false") + public void test48JsonRpcApiTestForEthGetBlockByHash() throws Exception { + response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNum); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("45getBlockByNumFromSolidityFromHttp:" + responseContent); + accountStateRoot = + responseContent + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getString("accountStateRoot"); + JsonArray params = new JsonArray(); + params.add(blockHash); + params.add(false); + JsonObject requestBody = getJsonRpcBody("eth_getBlockByHash", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject getBlockByHashResult = responseContent.getJSONObject("result"); + + Assert.assertNull(getBlockByHashResult.getString("nonce")); + Assert.assertNull(getBlockByHashResult.getString("sha3Uncles")); + Assert.assertNull(getBlockByHashResult.getString("receiptsRoot")); + Assert.assertNull(getBlockByHashResult.getString("difficulty")); + Assert.assertNull(getBlockByHashResult.getString("totalDifficulty")); + Assert.assertNull(getBlockByHashResult.getString("extraData")); + Assert.assertNull(getBlockByHashResult.getString("baseFeePerGas")); + Assert.assertNull(getBlockByHashResult.getString("mixHash")); + Assert.assertEquals(getBlockByHashResult.getString("uncles"), new ArrayList<>().toString()); + Assert.assertEquals(getBlockByHashResult.getString("stateRoot"), "0x" + accountStateRoot); + + Assert.assertEquals( + getBlockByHashResult.getString("logsBloom"), + "0x00000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000000000000000000000000" + + "000000000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000"); + Assert.assertEquals(getBlockByHashResult.getString("number"), blockNumHex); + Assert.assertEquals(getBlockByHashResult.getString("hash"), "0x" + bid); + Assert.assertEquals(getBlockByHashResult.getString("parentHash"), "0x" + parentHash); + Assert.assertEquals(getBlockByHashResult.getString("transactionsRoot"), "0x" + txTrieRoot); + Assert.assertEquals( + getBlockByHashResult.getString("miner"), "0x" + witnessAddress.substring(2)); + Assert.assertEquals(getBlockByHashResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); + Assert.assertEquals( + String.valueOf(Long.parseLong(getBlockByHashResult.getString("gasLimit").substring(2), 16)), + feeLimit); + Assert.assertEquals( + Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16), + blockTimeStamp); + final GrpcAPI.NumberMessage message = + GrpcAPI.NumberMessage.newBuilder().setNum(blockNum).build(); + HttpMethed.waitToProduceOneBlock(httpFullNode); + Block block = blockingStubFull.getBlockByNum(message); + logger.info("sizeFromJrpc:" + block.getSerializedSize()); + logger.info( + "sizeFromJsonRPc:" + + Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16)); + size = block.getSerializedSize(); + Assert.assertEquals( + Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16), + block.getSerializedSize()); + + Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16); + JSONArray transactionId = getBlockByHashResult.getJSONArray("transactions"); + List transactionIdListFromGetBlockByHash = new ArrayList<>(); + if (transactionId.size() > 0) { + for (int i = 0; i < transactionId.size(); i++) { + transactionIdListFromGetBlockByHash.add(transactionId.get(i).toString()); + } + } + Assert.assertEquals(transactionIdListFromGetBlockByHash, transactionIdList); + } + + @Test( + enabled = true, + description = "Json rpc api of eth_getBlockByNumFromSolidityber params is true") + public void test49JsonRpcApiTestForEthgetBlockByNumFromSolidityber() throws Exception { + + JsonArray params = new JsonArray(); + params.add(blockNumHex); + logger.info("46blockNumHex:" + blockNumHex); + params.add(true); + JsonObject requestBody = getJsonRpcBody("eth_getBlockByNumber", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + JSONObject getBlockByNumFromSolidityberResult = responseContent.getJSONObject("result"); + logger.info("getBlockByHashResult:" + getBlockByNumFromSolidityberResult); + + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("nonce")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("sha3Uncles")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("receiptsRoot")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("difficulty")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("totalDifficulty")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("extraData")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("baseFeePerGas")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("mixHash")); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("uncles"), new ArrayList<>().toString()); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("stateRoot"), "0x" + accountStateRoot); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("logsBloom"), + "0x00000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000000000000000" + + "000000000000000000000000000000000000000000000000000000000000000000000000" + + "000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000"); + Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("number"), blockNumHex); + Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("hash"), "0x" + bid); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("parentHash"), "0x" + parentHash); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("transactionsRoot"), "0x" + txTrieRoot); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("miner"), "0x" + witnessAddress.substring(2)); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); + Assert.assertEquals( + String.valueOf( + Long.parseLong( + getBlockByNumFromSolidityberResult.getString("gasLimit").substring(2), 16)), + feeLimit); + Assert.assertEquals( + Long.parseLong(getBlockByNumFromSolidityberResult.getString("timestamp").substring(2), 16), + blockTimeStamp); + logger.info("size:" + size); + Assert.assertEquals( + Long.parseLong(getBlockByNumFromSolidityberResult.getString("size").substring(2), 16), + size); + + JSONArray transactionsList = getBlockByNumFromSolidityberResult.getJSONArray("transactions"); + logger.info("transactionsList:" + transactionsList); + List transactionInfoListFromGetBlockByHash = new ArrayList<>(); + if (transactionsList.size() > 0) { + for (int i = 0; i < transactionsList.size(); i++) { + transactionInfoListFromGetBlockByHash.add(transactionsList.get(i).toString()); + } + } + List transactionInfoListFromTransactionByBlockNumberAndIndex = new ArrayList<>(); + for (int i = 0; i < transactionsList.size(); i++) { + JsonArray paramsForEthGetTransactionByBlockNumberAndIndex = new JsonArray(); + paramsForEthGetTransactionByBlockNumberAndIndex.add(blockNumHex); + String index = "0x" + Integer.toHexString(i); + logger.info("index:" + index); + paramsForEthGetTransactionByBlockNumberAndIndex.add(index); + logger.info( + "paramsForEthGetTransactionByBlockNumberAndIndex:" + + paramsForEthGetTransactionByBlockNumberAndIndex); + JsonObject requestBodyForTransactionByBlockNumberAndIndex = + getJsonRpcBody( + "eth_getTransactionByBlockNumberAndIndex", + paramsForEthGetTransactionByBlockNumberAndIndex); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForTransactionByBlockNumberAndIndex); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + result = responseContent.getJSONObject("result"); + logger.info("result:" + result); + transactionInfoListFromTransactionByBlockNumberAndIndex.add(result.toString()); + } + Assert.assertEquals( + transactionInfoListFromGetBlockByHash, + transactionInfoListFromTransactionByBlockNumberAndIndex); + } + + /** constructor. */ + @AfterClass + public void shutdown() throws InterruptedException { + if (channelFull != null) { + channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); + } } } diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java index a8cc54adac1..c566fc5532c 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java @@ -29,7 +29,7 @@ public void test01GetNewFilterContainNothing() { params.add(paramBody); JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); logger.info("test01GetNewFilterContainNothing_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test01GetNewFilterContainNothing_responseContent" + responseContent); logger.info("result:" + responseContent.getString("result")); @@ -56,7 +56,7 @@ public void test02GetNewFilterContainAddress() { params.add(paramBody); JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); logger.info("test02GetNewFilterContainAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test02GetNewFilterContainAddress_responseContent" + responseContent); newFilterResultIdfrom01 = responseContent.getString("result"); @@ -67,10 +67,11 @@ public void test02GetNewFilterContainAddress() { enabled = true, description = "Eth api of eth_newFilter contains topic fromBlock and toBlock.") public void test03GetNewFilterContainTopic() { - response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNumForTrc20); + response = HttpMethed.getBlockByNum(httpFullNode, blockNumForTrc20); responseContent = HttpMethed.parseResponseContent(response); logger.info("responseContent:" + responseContent); logger.info("blockHash:" + responseContent.getString("blockID")); + blockHash = responseContent.getString("blockID"); JsonArray topicArray = new JsonArray(); topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); @@ -82,7 +83,7 @@ public void test03GetNewFilterContainTopic() { params.add(paramBody); JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); logger.info("test03GetNewFilterContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test03GetNewFilterContainTopic_responseContent" + responseContent); Assert.assertNotNull(responseContent.getString("result")); @@ -106,14 +107,14 @@ public void test04GetNewFilterContainsTopicAndAddress() { params.add(paramBody); JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); logger.info("test04GetNewFilterContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test04GetNewFilterContainsTopicAndAddress_responseContent" + responseContent); Assert.assertNotNull(responseContent.getString("result")); } @Test(enabled = true, description = "Eth api of eth_newFilter only contain topic and blockHash.") - public void test05GetNewFilterOnlyContainTopic() throws InterruptedException { + public void test05GetNewFilterOnlyContainTopic() { JsonObject paramBody = new JsonObject(); paramBody.addProperty("blockHash", blockHash); JsonArray topicArray = new JsonArray(); @@ -123,25 +124,25 @@ public void test05GetNewFilterOnlyContainTopic() throws InterruptedException { params.add(paramBody); JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); logger.info("test05GetNewFilterOnlyContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test05GetNewFilterOnlyContainTopic_responseContent" + responseContent); Assert.assertNotNull(responseContent.getString("result")); } @Test(enabled = true, description = "Eth api of eth_newFilter which only contains blockHash.") - public void test06GetNewFilterHasOnlyBlockHash() throws InterruptedException { - response = HttpMethed.getNowBlockFromSolidity(solidityNode); + public void test06GetNewFilterHasOnlyBlockHash() { + + response = HttpMethed.getNowBlock(httpFullNode); responseContent = HttpMethed.parseResponseContent(response); String blockHash = responseContent.getString("blockID"); - Thread.sleep(30000); JsonObject paramBody = new JsonObject(); paramBody.addProperty("blockHash", blockHash); JsonArray params = new JsonArray(); params.add(paramBody); JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); logger.info("test06GetNewFilterHasOnlyBlockHash_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test06GetNewFilterHasOnlyBlockHash_responseContent" + responseContent); Assert.assertNotNull(responseContent.getString("result")); @@ -157,7 +158,7 @@ public void test07GetNewFilterCheckNewBlock() { params.add(paramBody); JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); logger.info("test07GetNewFilterCheckNewBlock_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test07GetNewFilterCheckNewBlock_responseContent" + responseContent); Assert.assertNotNull(responseContent.getString("result")); @@ -169,7 +170,7 @@ public void test08GetEthNewBlockFilter() { JsonArray params = new JsonArray(); JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); logger.info("test08GetEthNewBlockFilter_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test08GetEthNewBlockFilter_responseContent:" + responseContent); Assert.assertNotNull(responseContent.getString("result")); @@ -181,7 +182,7 @@ public void test09GetFilterChanges() { JsonArray params = new JsonArray(); JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); String ethNewBlockFilterResult = responseContent.get("result").toString(); @@ -192,7 +193,7 @@ public void test09GetFilterChanges() { params.add(newFilterId); requestBody = getJsonRpcBody("eth_getFilterChanges", params); logger.info("test09GetFilterChanges_requestBody: " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test09GetFilterChanges_responseContent:" + responseContent); Assert.assertEquals("[]", responseContent.getString("result")); @@ -214,7 +215,7 @@ public void test10GetLogsOnlyContainAddress() { params.add(paramBody); JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test10GetLogsOnlyContainAddress_responseContent:" + responseContent); Assert.assertNotNull(responseContent.getString("result")); @@ -236,7 +237,7 @@ public void test11GetLogsContainsTopicAndAddress() { params.add(paramBody); JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test11GetLogsContainsTopicAndAddress_responseContent" + responseContent); Assert.assertNotNull(responseContent.getString("result")); @@ -252,7 +253,7 @@ public void test12GetFilterLogsContainsAddress() { params.add(newFilterResultIdfrom01); JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); logger.info("test12GetFilterLogsContainsAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test12GetFilterLogsContainsAddress_responseContent" + responseContent); Assert.assertNotNull(responseContent.getString("result")); @@ -265,7 +266,7 @@ public void test13GetFilterLogsContainsTopic() { params.add(newFilterResultIdfrom02); JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); logger.info("test13GetFilterLogsContainsTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test13GetFilterLogsContainsTopic_responseContent" + responseContent); Assert.assertNotNull(responseContent.getString("result")); @@ -288,7 +289,7 @@ public void test14EthUninstallFilter() { params.add(paramBody); JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); logger.info("test14_newfilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test14_newfilter_responseContentr" + responseContent); String ethNewFilterResult = responseContent.get("result").toString(); @@ -302,13 +303,13 @@ public void test14EthUninstallFilter() { params.add(responseContent.get("result").toString()); requestBody = getJsonRpcBody("eth_uninstallFilter", params); logger.info("test14_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test14_eth_uninstallFilter_responseContentr_first" + responseContent); Assert.assertEquals(responseContent.get("result"), true); // second time logger.info("test14_eth_uninstallFilter_second " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test14_eth_uninstallFilter_responseContentr_second " + responseContent); Assert.assertEquals( @@ -318,7 +319,7 @@ public void test14EthUninstallFilter() { params = new JsonArray(); params.add(ethNewFilterResult); requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test14EthUninstallFilter_responseContent" + responseContent); String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; @@ -336,7 +337,7 @@ public void test15EthUninstallFilter() { JsonArray params = new JsonArray(); JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); String ethNewBlockFilterResult = responseContent.get("result").toString(); @@ -349,12 +350,12 @@ public void test15EthUninstallFilter() { params.add(responseContent.get("result").toString()); requestBody = getJsonRpcBody("eth_uninstallFilter", params); logger.info("test15_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test15_eth_uninstallFilter_responseContentr_first" + responseContent); Assert.assertEquals(responseContent.get("result"), true); // second time - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test15_eth_uninstallFilter_responseContentr_second" + responseContent); Assert.assertEquals( @@ -363,7 +364,7 @@ public void test15EthUninstallFilter() { params = new JsonArray(); params.add(ethNewBlockFilterResult); requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); responseContent = HttpMethed.parseResponseContent(response); logger.info("test15EthUninstallFilter_responseContent" + responseContent); String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java index f1e1cb8304b..fda69348e23 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java @@ -1,1242 +1,372 @@ package stest.tron.wallet.dailybuild.jsonrpc; -import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.google.gson.JsonArray; import com.google.gson.JsonObject; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpResponse; import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.utils.ByteArray; -import org.tron.protos.Protocol.Block; import stest.tron.wallet.common.client.utils.HttpMethed; import stest.tron.wallet.common.client.utils.JsonRpcBase; -import stest.tron.wallet.common.client.utils.PublicMethed; @Slf4j public class Accounts004 extends JsonRpcBase { - private JSONObject responseContent; - private HttpResponse response; - String realGasPrice; - String bid = null; - int indexNum = 0; - String indexHex = null; - JSONObject result = null; - String transacionHash = null; + JSONObject responseContent; + HttpResponse response; + String topic0 = null; + String topic1 = null; + String fromBlock = null; + String toBlock = null; + String newFilterResultIdfrom01 = null; + String newFilterResultIdfrom02 = null; String blockHash = null; - String blockNumHex = null; - String parentHash = null; - String txTrieRoot = null; - String witnessAddress = null; - String feeLimit = null; - String accountStateRoot = null; - String energyUsed = "0x135c6"; - List transactionIdList = null; - long size = 0; - long gas = 0; - long blockTimeStamp = 0; - long gasPriceFromHttp = 0; - - /** constructor. */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Json rpc api of eth_accounts") - public void test01JsonRpcApiTestForEthAccounts() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_accounts", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - List result = new ArrayList(); - logger.info(String.valueOf(result)); - Assert.assertEquals(responseContent.get("result"), result); - } - - @Test(enabled = true, description = "Json rpc api of eth_blockNumber") - public void test02JsonRpcApiTestForEthBlockNumber() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_blockNumber", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String blockNum = responseContent.getString("result").substring(2); - long blockNumFromjsonRpcNodeForSolidity = Long.parseLong(blockNum, 16); - response = HttpMethed.getNowBlockFromSolidity(solidityNode); - responseContent = HttpMethed.parseResponseContent(response); - long blockNumFromHttp = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - logger.info("blocknumFromjsonRpcNodeForSolidity:" + blockNumFromjsonRpcNodeForSolidity); - logger.info("blocknumFromHttp:" + blockNumFromHttp); - Assert.assertTrue(Math.abs(blockNumFromjsonRpcNodeForSolidity - blockNumFromHttp) <= 3); - } - - @Test(enabled = true, description = "Json rpc api of eth_call") - public void test03JsonRpcApiTestForEthCall() throws Exception { - JsonObject param = new JsonObject(); - HttpMethed.waitToProduceOneBlock(httpFullNode); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x06fdde03"); - JsonArray params = new JsonArray(); - params.add(param); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_call", params); - logger.info("03params:" + params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals( - "0x000000000000000000000000000000000000000000000000000" - + "00000000000200000000000000000000000000000000000000000" - + "00000000000000000000000a546f6b656e5452433230000000000" - + "00000000000000000000000000000000000", - dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_chainId") - public void test04JsonRpcApiTestForEthChainId() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_chainId", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String blockIdFromjsonRpcNodeForSolidity = - responseContent.get("result").toString().substring(2); - response = HttpMethed.getBlockByNumFromSolidity(solidityNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - String blockIdFromHttp = responseContent.getString("blockID").substring(56); - logger.info("blockIdFromjsonRpcNodeForSolidity:" + blockIdFromjsonRpcNodeForSolidity); - logger.info("blockIdFromHttp:" + blockIdFromHttp); - Assert.assertEquals(blockIdFromjsonRpcNodeForSolidity, blockIdFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_coinbase") - public void test05JsonRpcApiTestForEthCoinbase() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_coinbase", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - - Assert.assertEquals( - "0x410be88a918d74d0dfd71dc84bd4abf036d0562991", responseContent.getString("result")); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGas") - public void test06JsonRpcApiTestForEthEstimateGas() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x1249c58b"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test06requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals("0x147", dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasHasPayable") - public void test07JsonRpcApiTestForEthEstimateGasHasPayable() throws Exception { - response = HttpMethed.getTransactionInfoByIdFromSolidity(solidityNode, txid); - responseContent = HttpMethed.parseResponseContent(response); - Long realEnergyUsed = responseContent.getJSONObject("receipt").getLong("energy_usage_total"); - logger.info("realEnergyUsed:" + realEnergyUsed); - JsonObject param = new JsonObject(); - param.addProperty("from", "0x" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2)); - param.addProperty("to", "0x" + contractAddressFrom58); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x1389"); - param.addProperty("data", data); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test07requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals((long) realEnergyUsed, Long.parseLong(dataResult.substring(2), 16)); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasWithoutTo") - public void test08JsonRpcApiTestForEthEstimateGasWithoutTo() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", "0x6C0214C9995C6F3A61AB23F0EB84B0CDE7FD9C7C"); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty( - "data", - "0x6080604052d3600055d2600155346002556101418061001f6000396000f30060806040" - + "52600436106100565763ffffffff7c010000000000000000000000000000000000000000" - + "000000000000000060003504166305c24200811461005b5780633be9ece7146100815780" - + "6371dc08ce146100aa575b600080fd5b6100636100b2565b6040805193845260208401929" - + "0925282820152519081900360600190f35b6100a873ffffffffffffffffffffffffffffff" - + "ffffffffff600435166024356044356100c0565b005b61006361010d565b60005460015460" - + "0254909192565b60405173ffffffffffffffffffffffffffffffffffffffff841690821561" - + "08fc029083908590600081818185878a8ad0945050505050158015610107573d6000803e3d" - + "6000fd5b50505050565bd3d2349091925600a165627a7a72305820a2fb39541e90eda9a2f5" - + "f9e7905ef98e66e60dd4b38e00b05de418da3154e757002900000000000000000000000000" - + "00000000000000000000000000000090fa17bb"); + @Test(enabled = true, description = "Eth api of eth_newFilter contains nothing.") + public void test01GetNewFilterContainNothing() { + JsonObject paramBody = new JsonObject(); JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test01GetNewFilterContainNothing_requestBody " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test08requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - logger.info("dataResult:" + dataResult); - Assert.assertEquals(energyUsed, dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasSendTrx") - public void test09JsonRpcApiTestForEthEstimateGasSendTrx() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", "0xC1A74CD01732542093F5A87910A398AD70F04BD7"); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x1"); - param.addProperty("data", "0x0"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test09requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals("0x0", dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_gasPrice") - public void test10JsonRpcApiTestForEthGasPrice() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_gasPrice", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String gasPrice = responseContent.get("result").toString().substring(2); - long gasPriceFromJsonrpc = Long.parseLong(gasPrice, 16); - logger.info(String.valueOf(gasPriceFromJsonrpc)); - response = HttpMethed.getChainParameters(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - JSONArray temp; - temp = responseContent.getJSONArray("chainParameter"); - for (int i = 0; i < temp.size(); i++) { - if (temp.getJSONObject(i).get("key").equals("getEnergyFee")) { - gasPriceFromHttp = temp.getJSONObject(i).getLong("value"); - } - } - logger.info("gasPriceFromHttp:" + gasPriceFromHttp); - Assert.assertEquals(gasPriceFromJsonrpc, gasPriceFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBalance") - public void test11JsonRpcApiTestForEthGetBalance() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x" + ByteArray.toHexString(foundationAccountAddress).substring(2)); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getBalance", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String balance = responseContent.getString("result").substring(2); - Long balance1 = Long.parseLong(balance, 16); - logger.info("balance1:" + balance1); - response = HttpMethed.getAccountFromSolidity(solidityNode, foundationAccountAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long balance2 = responseContent.getLong("balance"); - logger.info(balance1.toString()); - logger.info(balance2.toString()); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") - public void test12JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { - response = HttpMethed.getNowBlockFromSolidity(solidityNode); - responseContent = HttpMethed.parseResponseContent(response); - JsonArray params = new JsonArray(); - params.add("earliest"); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNum1 = Integer.parseInt(transactionNum, 16); - logger.info(String.valueOf(transactionNum1)); - response = HttpMethed.getTransactionCountByBlocknumFromSolidity(solidityNode, 0); responseContent = HttpMethed.parseResponseContent(response); - int transactionNum2 = responseContent.getInteger("count"); - logger.info(String.valueOf(transactionNum2)); - Assert.assertEquals(transactionNum1, transactionNum2); + logger.info("test01GetNewFilterContainNothing_responseContent" + responseContent); + logger.info("result:" + responseContent.getString("result")); + Assert.assertNotNull(responseContent.getString("result")); } - @Test(enabled = true, description = "Json rpc api of eth_getCode") - public void test13JsonRpcApiTestForEthGetCode() throws Exception { - - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getCode", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String codeFromJsonRpc = responseContent.getString("result").substring(2); - logger.info(codeFromJsonRpc); - response = HttpMethed.getContractInfo(httpFullNode, contractAddressFrom58); - logger.info("13contractAddressFrom58:" + contractAddressFrom58); - responseContent = HttpMethed.parseResponseContent(response); - String codeFromHttp = responseContent.getString("runtimecode"); - logger.info(codeFromHttp); - Assert.assertEquals(codeFromJsonRpc, codeFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") - public void test14JsonRpcApiTestForEthGetStorageAt01() throws Exception { - - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add("0x0"); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("14responseContent:" + responseContent); - String result = responseContent.getString("result").substring(2); - long resultExpect = Long.parseLong(result, 16); - logger.info("result:" + resultExpect); - Assert.assertEquals("1234", String.valueOf(resultExpect)); - } - - @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") - public void test15JsonRpcApiTestForEthGetStorageAt02() throws Exception { - - String address = - "000000000000000000000000" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2); - String str = address + "0000000000000000000000000000000000000000000000000000000000000001"; - logger.info("str:" + str); - JsonArray paramsForSha3 = new JsonArray(); - paramsForSha3.add(str); - JsonObject requestBodyForSha3 = getJsonRpcBody("web3_sha3", paramsForSha3); - logger.info("requestBodyForSha3:" + requestBodyForSha3); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForSha3); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String resultForSha3 = responseContent.getString("result"); - logger.info("resultForSha3:" + resultForSha3); - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add(resultForSha3); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("15responseContent:" + responseContent); - String result = responseContent.getString("result").substring(2); - logger.info("15result:" + result); - logger.info("mapResult:" + Integer.parseInt(result, 16)); - Assert.assertEquals("5678", String.valueOf(Integer.parseInt(result, 16))); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockNumberAndIndex") - public void test16JsonRpcApiTestForEthGetTransactionByBlockNumberAndIndex() throws Exception { - logger.info("16blockNum:" + blockNum); - blockNumHex = "0x" + Integer.toHexString(blockNum); - logger.info("blockNumHex:" + blockNumHex); - JsonArray params = new JsonArray(); - params.add(blockNumHex); - indexNum = 0; - response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - parentHash = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("parentHash"); - txTrieRoot = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("txTrieRoot"); - witnessAddress = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("witness_address"); - feeLimit = - responseContent - .getJSONArray("transactions") - .getJSONObject(0) - .getJSONObject("raw_data") - .getString("fee_limit"); - logger.info(feeLimit); - - JSONObject getBlockByNumFromSolidityResult = null; - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - if (txid.equals( - responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { - indexNum = i; - getBlockByNumFromSolidityResult = - responseContent.getJSONArray("transactions").getJSONObject(i); - bid = responseContent.getString("blockID"); - break; - } - } - transactionIdList = new ArrayList<>(); - if (responseContent.getJSONArray("transactions").size() > 0) { - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - transactionIdList.add( - "0x" + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID")); - } - } - logger.info("16transactionIdList:" + transactionIdList); - logger.info(String.valueOf(indexNum)); - indexHex = "0x" + Integer.toHexString(indexNum); - logger.info("indexHex:" + indexHex); - params.add(indexHex); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockNumberAndIndex", params); - logger.info("13requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - result = responseContent.getJSONObject("result"); - logger.info("16 result" + result); - Map jsonrpcResult = new HashMap(); - for (Map.Entry entry : result.entrySet()) { - jsonrpcResult.put(entry.getKey(), entry.getValue()); - } - transacionHash = jsonrpcResult.get("hash").toString(); - logger.info("transactionHash:" + transacionHash); - blockHash = jsonrpcResult.get("blockHash").toString(); - logger.info("jsonrpcResult:" + jsonrpcResult); - response = HttpMethed.getTransactionInfoByBlocknumFromSolidity(solidityNode, blockNum); - logger.info("response:" + response); - List responseContent1 = HttpMethed.parseResponseContentArray(response); - logger.info("responseContent1:" + responseContent1); - blockTimeStamp = responseContent1.get(0).getLong("blockTimeStamp"); - - for (int i = 0; i < responseContent1.size(); i++) { - if (responseContent1.get(i).getString("id").equals(transactionIdList.get(0).substring(2))) { - gas = responseContent1.get(i).getJSONObject("receipt").getLong("energy_usage_total"); - logger.info("gas:" + gas); - break; - } - } - - Assert.assertEquals(jsonrpcResult.get("gas").toString(), "0x" + Long.toHexString(gas)); - Assert.assertNull(jsonrpcResult.get("nonce")); - Assert.assertEquals( - jsonrpcResult.get("hash").toString(), - "0x" + getBlockByNumFromSolidityResult.getString("txID")); - Assert.assertEquals(jsonrpcResult.get("blockHash").toString(), "0x" + bid); - Assert.assertEquals(jsonrpcResult.get("blockNumber").toString(), blockNumHex); - Assert.assertEquals(jsonrpcResult.get("transactionIndex").toString(), indexHex); - Assert.assertEquals( - jsonrpcResult.get("from").toString(), - "0x" - + getBlockByNumFromSolidityResult - .getJSONObject("raw_data") - .getJSONArray("contract") - .getJSONObject(0) - .getJSONObject("parameter") - .getJSONObject("value") - .getString("owner_address") - .substring(2)); - Assert.assertEquals( - jsonrpcResult.get("to").toString(), - "0x" - + getBlockByNumFromSolidityResult - .getJSONObject("raw_data") - .getJSONArray("contract") - .getJSONObject(0) - .getJSONObject("parameter") - .getJSONObject("value") - .getString("contract_address") - .substring(2)); - - Assert.assertEquals(jsonrpcResult.get("value").toString(), "0x1389"); - String data; - if (getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data") == null) { - data = "0x"; + @Test( + enabled = true, + description = "Eth api of eth_newFilter contains address,fromBlock and toBlock.") + public void test02GetNewFilterContainAddress() { + if (blockNumForTrc20 - 10 < 0) { + fromBlock = "0"; } else { - data = - getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data").substring(2); - } - Assert.assertEquals(jsonrpcResult.get("input").toString(), data); - - long temp = - Long.parseLong( - getBlockByNumFromSolidityResult.getString("signature").substring(130, 131), 16); - long v = - Long.parseLong( - getBlockByNumFromSolidityResult.getString("signature").substring(130, 132), 16); - if (temp < 27) { - v += 27; + fromBlock = "0x" + Integer.toHexString(blockNumForTrc20 - 10); } - Assert.assertEquals(Long.parseLong(jsonrpcResult.get("v").toString().substring(2), 16), v); - Assert.assertEquals( - jsonrpcResult.get("r").toString().substring(2), - getBlockByNumFromSolidityResult.getString("signature").substring(2, 66)); - Assert.assertEquals( - jsonrpcResult.get("s").toString().substring(2), - getBlockByNumFromSolidityResult.getString("signature").substring(66, 130)); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByHash") - public void test17JsonRpcApiTestForEthGetBlockTransactionCountByHash() throws Exception { - logger.info("blockNum:" + blockNum); + toBlock = "0x" + Integer.toHexString(blockNumForTrc20 + 10); + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); JsonArray params = new JsonArray(); - params.add(blockHash); - logger.info("blockHash:" + blockHash); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByHash", params); - logger.info("requestBody:" + requestBody); - HttpMethed.waitToProduceOneBlock(httpFullNode); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test02GetNewFilterContainAddress_requestBody " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNumFromjsonRpcNodeForSolidity = Integer.parseInt(transactionNum, 16); - logger.info( - "transactionNumFromjsonRpcNodeForSolidity:" + transactionNumFromjsonRpcNodeForSolidity); - response = HttpMethed.getTransactionCountByBlocknumFromSolidity(solidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNumFromHttp = responseContent.getInteger("count"); - logger.info("transactionNumFromHttp:" + transactionNumFromHttp); - Assert.assertEquals(transactionNumFromHttp, transactionNumFromjsonRpcNodeForSolidity); + logger.info("test02GetNewFilterContainAddress_responseContent" + responseContent); + newFilterResultIdfrom01 = responseContent.getString("result"); + logger.info("test02GetNewFilterContainAddress_id:" + responseContent.getString("result")); } - @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") - public void test18JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { - JsonArray params = new JsonArray(); - params.add(blockNum); - logger.info(String.valueOf(blockNum)); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("response:" + response); - HttpMethed.waitToProduceOneBlock(httpFullNode); + @Test( + enabled = true, + description = "Eth api of eth_newFilter contains topic fromBlock and toBlock.") + public void test03GetNewFilterContainTopic() { + response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNumForTrc20); responseContent = HttpMethed.parseResponseContent(response); logger.info("responseContent:" + responseContent); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNum1 = Integer.parseInt(transactionNum, 16); - logger.info(String.valueOf(transactionNum1)); - response = HttpMethed.getTransactionCountByBlocknumFromSolidity(solidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNum2 = responseContent.getInteger("count"); - logger.info(String.valueOf(transactionNum2)); - Assert.assertEquals(transactionNum1, transactionNum2); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockHashAndIndex") - public void test19JsonRpcApiTestForEthGetTransactionByBlockHashAndIndex() throws Exception { + logger.info("blockHash:" + responseContent.getString("blockID")); + blockHash = responseContent.getString("blockID"); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + JsonObject paramBody = new JsonObject(); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); JsonArray params = new JsonArray(); - params.add("0x" + bid); - params.add(indexHex); - logger.info("indexHex:" + indexHex); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockHashAndIndex", params); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test03GetNewFilterContainTopic_requestBody " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultForGetTransactionByBlockHashAndIndex = responseContent.getJSONObject("result"); - Assert.assertEquals(result, resultForGetTransactionByBlockHashAndIndex); + logger.info("test03GetNewFilterContainTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + newFilterResultIdfrom02 = responseContent.getString("result"); + logger.info("test03GetNewFilterContainTopic_id:" + newFilterResultIdfrom02); } - @Test(enabled = true, description = "Json rpc api of eth_getTransactionByHash") - public void test20JsonRpcApiTestForEthGetTransactionByHash() throws Exception { - JsonArray params = new JsonArray(); - params.add(transacionHash); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByHash", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject result1 = responseContent.getJSONObject("result"); - Assert.assertEquals(result, result1); - } + @Test(enabled = true, description = "Eth api of eth_newFilter contains topic and address.") + public void test04GetNewFilterContainsTopicAndAddress() { - @Test(enabled = true, description = "Json rpc api of eth_getTransactionReceipt") - public void test21JsonRpcApiTestForEthGetTransactionReceipt() throws Exception { + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); JsonArray params = new JsonArray(); - Thread.sleep(6000); - params.add(trc20Txid); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionReceipt", params); - logger.info("requestBody:" + requestBody); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test04GetNewFilterContainsTopicAndAddress_requestBody " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("response:" + response); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultFromTransactionReceipt = responseContent.getJSONObject("result"); - logger.info("resultFromTransactionReceipt:" + resultFromTransactionReceipt); - JSONArray logs = resultFromTransactionReceipt.getJSONArray("logs"); - logger.info("logs:" + logs); - logger.info("result:" + resultFromTransactionReceipt.toString()); - response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNumForTrc20); responseContent = HttpMethed.parseResponseContent(response); - int index = 0; - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - if (trc20Txid.equals( - responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { - index = i; - break; - } - } - - JsonArray paramsForTransactionByBlockNumberAndIndex = new JsonArray(); - paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(blockNumForTrc20)); - paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(index)); - JsonObject requestBody1 = - getJsonRpcBody( - "eth_getTransactionByBlockNumberAndIndex", paramsForTransactionByBlockNumberAndIndex); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); - logger.info("requestBody1:" + requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultFromTransactionByBlockNumberAndIndex = responseContent.getJSONObject("result"); - logger.info( - "resultFromTransactionByBlockNumberAndIndex:" + resultFromTransactionByBlockNumberAndIndex); - Assert.assertEquals( - resultFromTransactionReceipt.getString("blockHash"), - resultFromTransactionByBlockNumberAndIndex.getString("blockHash")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("blockNumber"), - resultFromTransactionByBlockNumberAndIndex.getString("blockNumber")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("transactionIndex"), - resultFromTransactionByBlockNumberAndIndex.getString("transactionIndex")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("transactionHash"), "0x" + trc20Txid); - Assert.assertEquals( - resultFromTransactionReceipt.getString("from"), - resultFromTransactionByBlockNumberAndIndex.getString("from")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("to"), - resultFromTransactionByBlockNumberAndIndex.getString("to")); - logger.info("effectiveGasPrice:" + resultFromTransactionReceipt.getString("effectiveGasPrice")); - logger.info("gasPriceFromHttp:" + Long.toHexString(gasPriceFromHttp)); - Assert.assertEquals( - resultFromTransactionReceipt.getString("effectiveGasPrice"), - "0x" + Long.toHexString(gasPriceFromHttp)); - /* Assert.assertEquals( - resultFromTransactionReceipt.getString("contractAddress").substring(2), - trc20AddressHex.substring(2));*/ - Assert.assertNull(resultFromTransactionReceipt.getString("contractAddress")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("logsBloom"), - "0x000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000"); - Assert.assertEquals("0x1", resultFromTransactionReceipt.getString("status")); - Assert.assertEquals("0x0", resultFromTransactionReceipt.getString("type")); - logger.info("gas:" + resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("gasUsed"), - resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("cumulativeGasUsed"), - resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - logs.getJSONObject(0).getString("logIndex"), "0x" + Integer.toHexString(index)); - Assert.assertEquals(logs.getJSONObject(0).getString("removed"), "false"); - Assert.assertEquals( - logs.getJSONObject(0).getString("blockHash"), - resultFromTransactionReceipt.getString("blockHash")); - Assert.assertEquals( - logs.getJSONObject(0).getString("blockNumber"), - resultFromTransactionReceipt.getString("blockNumber")); - Assert.assertEquals( - logs.getJSONObject(0).getString("transactionIndex"), - resultFromTransactionReceipt.getString("transactionIndex")); - Assert.assertEquals( - logs.getJSONObject(0).getString("transactionHash"), - resultFromTransactionReceipt.getString("transactionHash")); - Assert.assertEquals( - logs.getJSONObject(0).getString("address"), resultFromTransactionReceipt.getString("to")); - response = HttpMethed.getTransactionInfoByBlocknumFromSolidity(solidityNode, blockNumForTrc20); - List responseContent1 = HttpMethed.parseResponseContentArray(response); - logger.info("responseContent1:" + responseContent1); - - response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertEquals( - logs.getJSONObject(0).getString("data").substring(2), - responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("data")); - - Assert.assertEquals( - logs.getJSONObject(0).getString("topics").replace("0x", ""), - responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("topics")); + logger.info("test04GetNewFilterContainsTopicAndAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); } - @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockHashAndIndex") - public void test22JsonRpcApiTestForEthGetUncleByBlockHashAndIndex() throws Exception { + @Test(enabled = true, description = "Eth api of eth_newFilter only contain topic and blockHash.") + public void test05GetNewFilterOnlyContainTopic() throws InterruptedException { + JsonObject paramBody = new JsonObject(); + paramBody.addProperty("blockHash", blockHash); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + paramBody.add("topics", topicArray); JsonArray params = new JsonArray(); - params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); - params.add("0x"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockHashAndIndex", params); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test05GetNewFilterOnlyContainTopic_requestBody " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNull(result); + logger.info("test05GetNewFilterOnlyContainTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); } - @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockNumberAndIndex") - public void test23JsonRpcApiTestForEthGetUncleByBlockNumberAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0xeb82f0"); - params.add("0x"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockNumberAndIndex", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + @Test(enabled = true, description = "Eth api of eth_newFilter which only contains blockHash.") + public void test06GetNewFilterHasOnlyBlockHash() throws InterruptedException { + response = HttpMethed.getNowBlockFromSolidity(solidityNode); responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNull(result); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockHash") - public void test24JsonRpcApiTestForEthGetUncleCountByBlockHash() throws Exception { + String blockHash = responseContent.getString("blockID"); + Thread.sleep(30000); + JsonObject paramBody = new JsonObject(); + paramBody.addProperty("blockHash", blockHash); JsonArray params = new JsonArray(); - params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockHash", params); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test06GetNewFilterHasOnlyBlockHash_requestBody " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "0x0"); + logger.info("test06GetNewFilterHasOnlyBlockHash_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); } - @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockNumber") - public void test25JsonRpcApiTestForEthGetUncleCountByBlockNumber() throws Exception { + @Test(enabled = true, description = "Eth api of eth_newFilter check new and after block.") + public void test07GetNewFilterCheckNewBlock() { + JsonObject paramBody = new JsonObject(); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + paramBody.add("topics", topicArray); JsonArray params = new JsonArray(); - params.add("eth_getUncleCountByBlockNumber"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockNumber", params); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test07GetNewFilterCheckNewBlock_requestBody " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "0x0"); + logger.info("test07GetNewFilterCheckNewBlock_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); } - @Test(enabled = true, description = "Json rpc api of eth_getWork") - public void test26JsonRpcApiTestForEthGetWork() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_getWork", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - int resultLen = result.length(); - String resultFromjsonRpcNodeForSolidity = result.substring(4, resultLen - 12); - response = HttpMethed.getNowBlockFromSolidity(solidityNode); - responseContent = HttpMethed.parseResponseContent(response); - String resultFromHttp = responseContent.getString("blockID"); - logger.info("resultFromjsonRpcNodeForSolidity:" + resultFromjsonRpcNodeForSolidity); - logger.info("resultFromHttp:" + resultFromHttp); - Assert.assertEquals(resultFromjsonRpcNodeForSolidity, resultFromHttp); - } + @Test(enabled = true, description = "Eth api of eth_newBlockFilter") + public void test08GetEthNewBlockFilter() { - @Test(enabled = true, description = "Json rpc api of eth_hashrate") - public void test27JsonRpcApiTestForEthHashRate() throws Exception { JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_hashrate", params); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test08GetEthNewBlockFilter_requestBody " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals("0x0", result); + logger.info("test08GetEthNewBlockFilter_responseContent:" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); } - @Test(enabled = true, description = "Json rpc api of eth_mining") - public void test28JsonRpcApiTestForEthMining() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_mining", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "true"); - } + @Test(enabled = true, description = "Eth api of eth_getFilterChanges has less 20 elements.") + public void test09GetFilterChanges() { - @Test(enabled = true, description = "Json rpc api of eth_protocolVersion") - public void test29JsonRpcApiTestForEthProtocolVersion() throws Exception { JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_protocolVersion", params); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - String protocolVersion = responseContent.getString("result").substring(2); - Long protocolVersion1 = Long.parseLong(protocolVersion, 16); - response = HttpMethed.getNowBlockFromSolidity(solidityNode); - responseContent = HttpMethed.parseResponseContent(response); - Long protocolVersion2 = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("version"); - logger.info(protocolVersion1.toString()); - logger.info(protocolVersion2.toString()); - Assert.assertEquals(protocolVersion1, protocolVersion2); - } - - @Test(enabled = true, description = "Json rpc api of eth_syncing") - public void test30JsonRpcApiTestForEthSyncing() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_syncing", params); + logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); + String ethNewBlockFilterResult = responseContent.get("result").toString(); + logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); + String newFilterId = responseContent.getString("result"); + logger.info("newFilterId:" + newFilterId); + params = new JsonArray(); + params.add(newFilterId); + requestBody = getJsonRpcBody("eth_getFilterChanges", params); + logger.info("test09GetFilterChanges_requestBody: " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - JSONObject temp = responseContent.getJSONObject("result"); - String currentNumFromRpc = temp.getString("currentBlock"); - logger.info(currentNumFromRpc); - logger.info(temp.toString()); - response = HttpMethed.getNowBlockFromSolidity(solidityNode); - responseContent = HttpMethed.parseResponseContent(response); - long currentNum = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - logger.info("currentNum:" + currentNum); - logger.info("currentNumFromRpc:" + Long.parseLong(currentNumFromRpc.substring(2), 16)); - Assert.assertEquals(currentNum, Long.parseLong(currentNumFromRpc.substring(2), 16)); - Assert.assertTrue(temp.containsKey("startingBlock")); - Assert.assertTrue(temp.containsKey("currentBlock")); - Assert.assertTrue(temp.containsKey("highestBlock")); + logger.info("test09GetFilterChanges_responseContent:" + responseContent); + Assert.assertEquals("[]", responseContent.getString("result")); } - @Test(enabled = true, description = "Json rpc api of net_listening") - public void test31JsonRpcApiTestForNetListening() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_listening", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - Boolean temp = responseContent.getBoolean("result"); - logger.info(temp.toString()); - response = HttpMethed.getNodeInfo(solidityNode); - responseContent = HttpMethed.parseResponseContent(response); - boolean expect = false; - int num = responseContent.getInteger("activeConnectCount"); - if (num >= 1) { - expect = true; - } - Assert.assertEquals(temp, expect); + @Test( + enabled = true, + description = "Eth api of eth_getLogs contains address ,fromBlock and toBlock.") + public void test10GetLogsOnlyContainAddress() { + JsonArray addressArray = new JsonArray(); + logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); + addressArray.add(contractTrc20AddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + logger.info("blockNumForTrc20:" + blockNumForTrc20); + paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 20))); + paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 20))); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); + logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test10GetLogsOnlyContainAddress_responseContent:" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + String address = + responseContent.getJSONArray("result").getJSONObject(0).getString("address").substring(2); + Assert.assertEquals(address, contractTrc20AddressFrom58.substring(2)); + topic0 = responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); } - @Test(enabled = true, description = "Json rpc api of net_peerCount") - public void test32JsonRpcApiTestForNetPeerCount() throws Exception { + @Test(enabled = true, description = "Eth api of eth_getLogs both contains topic and address.") + public void test11GetLogsContainsTopicAndAddress() { + JsonArray topicArray = new JsonArray(); + topicArray.add(topic0); + JsonObject paramBody = new JsonObject(); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 10))); + paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 10))); JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_peerCount", params); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); + logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNotNull(result); + logger.info("test11GetLogsContainsTopicAndAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + String topicFromResult = + responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); + Assert.assertEquals(topicFromResult, topic0); } - @Test(enabled = true, description = "Json rpc api of net_version") - public void test33JsonRpcApiTestForEthVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_version", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String firstBlockHashFromJsonRpc = responseContent.getString("result").substring(2); - response = HttpMethed.getBlockByNumFromSolidity(solidityNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - String firstBlockHashFromHttp = responseContent.getString("blockID").substring(56); - logger.info("firstBlockHashFromJsonRpc" + firstBlockHashFromJsonRpc); - logger.info("firstBlockHashFromHttp" + firstBlockHashFromHttp); - Assert.assertEquals(firstBlockHashFromJsonRpc, firstBlockHashFromHttp); - } + @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") + public void test12GetFilterLogsContainsAddress() { - @Test(enabled = true, description = "Json rpc api of web3_clientVersion") - public void test34JsonRpcApiTestForWeb3ClientVersion() throws Exception { JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("web3_clientVersion", params); + params.add(newFilterResultIdfrom01); + JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); + logger.info("test12GetFilterLogsContainsAddress_requestBody " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - List resultList = new ArrayList<>(); - for (String str : result.split("/")) { - resultList.add(str); - } - Assert.assertEquals(resultList.size(), 5); - Assert.assertEquals(resultList.get(0), "TRON"); - Assert.assertEquals(resultList.get(1).substring(0, 1), "v"); - Assert.assertEquals(resultList.get(2), "Linux"); - Assert.assertEquals(resultList.get(3), "Java1.8"); - Assert.assertEquals(resultList.get(4).substring(0, 11), "GreatVoyage"); - } - - @Test(enabled = true, description = "Json rpc api of web3_sha3") - public void test35JsonRpcApiTestForWeb3Sha3() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x08"); - JsonObject requestBody1 = getJsonRpcBody("web3_sha3", params); - response = getEthHttps(ethHttpsNode, requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - String result1 = responseContent.getString("result"); - JsonObject requestBody2 = getJsonRpcBody("web3_sha3", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody2); - responseContent = HttpMethed.parseResponseContent(response); - String result2 = responseContent.getString("result"); - Assert.assertEquals(result1, result2); + logger.info("test12GetFilterLogsContainsAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); } - @Test(enabled = true, description = "Json rpc api of eth_compileLLL") - public void test36JsonRpcApiTestForEthCompileLll() throws Exception { - JsonArray params = new JsonArray(); - params.add("(returnlll (suicide (caller)))"); - JsonObject requestBody1 = getJsonRpcBody("eth_compileLLL", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_compileLLL does not exist/is not available"); - } + @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") + public void test13GetFilterLogsContainsTopic() { - @Test(enabled = true, description = "Json rpc api of eth_compileSerpent") - public void test37JsonRpcApiTestForEthCompileSerpent() throws Exception { JsonArray params = new JsonArray(); - params.add("/* some serpent */"); - JsonObject requestBody = getJsonRpcBody("eth_compileSerpent", params); + params.add(newFilterResultIdfrom02); + JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); + logger.info("test13GetFilterLogsContainsTopic_requestBody " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_compileSerpent does not exist/is not available"); + logger.info("test13GetFilterLogsContainsTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); } - @Test(enabled = true, description = "Json rpc api of eth_compileSolidity") - public void test38JsonRpcApiTestForEthCompileSolidity() throws Exception { - JsonArray params = new JsonArray(); - params.add("contract test { function multiply(uint a) returns(uint d) { return a * 7; } }"); - JsonObject requestBody = getJsonRpcBody("eth_compileSolidity", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_compileSolidity does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getCompilers") - public void test39JsonRpcApiTestForEthCompileSolidity() throws Exception { + @Test( + enabled = true, + description = + "Eth api of eth_uninstallFilter which method is eth_newFilter" + + " and params has one element ") + public void test14EthUninstallFilter() { + // create ID + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.addProperty("fromBlock", "0x1f8b6a7"); + paramBody.addProperty("toBlock", "0x1f8b6a7"); JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_getCompilers", params); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test14_newfilter " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_getCompilers does not exist/is not available"); - } + logger.info("test14_newfilter_responseContentr" + responseContent); + String ethNewFilterResult = responseContent.get("result").toString(); + logger.info("EthNewFilterResult:" + ethNewFilterResult); + Assert.assertNotNull(responseContent.getString("result")); - @Test(enabled = true, description = "Json rpc api of eth_getTransactionCount") - public void test40JsonRpcApiTestForEthGetTransactionCount() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x407d73d8a49eeb85d32cf465507dd71d507100c1"); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionCount", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_getTransactionCount does not exist/is not available"); - } + // verify ID invalid - @Test(enabled = true, description = "Json rpc api of eth_sendRawTransaction") - public void test41JsonRpcApiTestForEthSendRawTransaction() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x234"); - JsonObject requestBody = getJsonRpcBody("eth_sendRawTransaction", params); + // first time + params = new JsonArray(); + params.add(responseContent.get("result").toString()); + requestBody = getJsonRpcBody("eth_uninstallFilter", params); + logger.info("test14_eth_uninstallFilter " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_sendRawTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sendTransaction") - public void test42JsonRpcApiTestForEthSendTransaction() throws Exception { - JsonArray params = new JsonArray(); - JsonObject temp = new JsonObject(); - params.add(temp); - temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); - temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); - temp.addProperty("gas", "0x76c0"); - temp.addProperty("gasPrice", "0x9184e72a000"); - temp.addProperty( - "data", - "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); - temp.addProperty("value", "0x9184e72a"); - - JsonObject requestBody = getJsonRpcBody("eth_sendTransaction", params); + logger.info("test14_eth_uninstallFilter_responseContentr_first" + responseContent); + Assert.assertEquals(responseContent.get("result"), true); + // second time + logger.info("test14_eth_uninstallFilter_second " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); + logger.info("test14_eth_uninstallFilter_responseContentr_second " + responseContent); Assert.assertEquals( - errorMessage, "the method eth_sendTransaction does not exist/is not available"); - } + responseContent.getJSONObject("error").getString("message"), "filter not found"); - @Test(enabled = true, description = "Json rpc api of eth_sign") - public void test43JsonRpcApiTestForEthSign() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); - params.add("0xdeadbeaf"); - JsonObject requestBody = getJsonRpcBody("eth_sign", params); + // query getFilterChanges to verify ID has invalid + params = new JsonArray(); + params.add(ethNewFilterResult); + requestBody = getJsonRpcBody("getFilterChanges", params); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_sign does not exist/is not available"); + logger.info("test14EthUninstallFilter_responseContent" + responseContent); + String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; + Assert.assertEquals(responseContent.get("error").toString(), expectResult); } - @Test(enabled = true, description = "Json rpc api of eth_signTransaction") - public void test44JsonRpcApiTestForEthSignTransaction() throws Exception { - JsonArray params = new JsonArray(); - JsonObject temp = new JsonObject(); - params.add(temp); - temp.addProperty( - "data", - "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); - temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); - temp.addProperty("gas", "0x76c0"); - temp.addProperty("gasPrice", "0x9184e72a000"); - temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); - temp.addProperty("value", "0x9184e72a"); - - JsonObject requestBody = getJsonRpcBody("eth_signTransaction", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_signTransaction does not exist/is not available"); - } + @Test( + enabled = true, + description = + "Eth api of eth_uninstallFilter which method is eth_newBlockFilter" + + " and params has one element ") + public void test15EthUninstallFilter() { + // create ID - @Test(enabled = true, description = "Json rpc api of eth_submitWork") - public void test45JsonRpcApiTestForEthSubmitWork() throws Exception { JsonArray params = new JsonArray(); - params.add("0x0000000000000001"); - params.add("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"); - params.add("0xD1GE5700000000000000000000000000D1GE5700000000000000000000000000"); - JsonObject requestBody = getJsonRpcBody("eth_submitWork", params); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_submitWork does not exist/is not available"); - } + logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); + String ethNewBlockFilterResult = responseContent.get("result").toString(); + logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); + Assert.assertNotNull(responseContent.getString("result")); - @Test(enabled = true, description = "Json rpc api of parity_nextNonce") - public void test46JsonRpcApiTestForParityNextNonce() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); - JsonObject requestBody = getJsonRpcBody("parity_nextNonce", params); + // verify ID invalid + // first time + params = new JsonArray(); + params.add(responseContent.get("result").toString()); + requestBody = getJsonRpcBody("eth_uninstallFilter", params); + logger.info("test15_eth_uninstallFilter " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method parity_nextNonce does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_submitHashrate") - public void test47JsonRpcApiTestForEthSubmitHashrate() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000000000000000000000000000000000000000000000000000500000"); - params.add("0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c"); - JsonObject requestBody = getJsonRpcBody("eth_submitHashrate", params); + logger.info("test15_eth_uninstallFilter_responseContentr_first" + responseContent); + Assert.assertEquals(responseContent.get("result"), true); + // second time response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); + logger.info("test15_eth_uninstallFilter_responseContentr_second" + responseContent); Assert.assertEquals( - errorMessage, "the method eth_submitHashrate does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockByHash params is false") - public void test48JsonRpcApiTestForEthGetBlockByHash() throws Exception { - response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("45getBlockByNumFromSolidityFromHttp:" + responseContent); - accountStateRoot = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("accountStateRoot"); - JsonArray params = new JsonArray(); - params.add(blockHash); - params.add(false); - JsonObject requestBody = getJsonRpcBody("eth_getBlockByHash", params); + responseContent.getJSONObject("error").getString("message"), "filter not found"); + // query getFilterChanges to verify ID has invalid + params = new JsonArray(); + params.add(ethNewBlockFilterResult); + requestBody = getJsonRpcBody("getFilterChanges", params); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); responseContent = HttpMethed.parseResponseContent(response); - JSONObject getBlockByHashResult = responseContent.getJSONObject("result"); - - Assert.assertNull(getBlockByHashResult.getString("nonce")); - Assert.assertNull(getBlockByHashResult.getString("sha3Uncles")); - Assert.assertNull(getBlockByHashResult.getString("receiptsRoot")); - Assert.assertNull(getBlockByHashResult.getString("difficulty")); - Assert.assertNull(getBlockByHashResult.getString("totalDifficulty")); - Assert.assertNull(getBlockByHashResult.getString("extraData")); - Assert.assertNull(getBlockByHashResult.getString("baseFeePerGas")); - Assert.assertNull(getBlockByHashResult.getString("mixHash")); - Assert.assertEquals(getBlockByHashResult.getString("uncles"), new ArrayList<>().toString()); - Assert.assertEquals(getBlockByHashResult.getString("stateRoot"), "0x" + accountStateRoot); - - Assert.assertEquals( - getBlockByHashResult.getString("logsBloom"), - "0x00000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000"); - Assert.assertEquals(getBlockByHashResult.getString("number"), blockNumHex); - Assert.assertEquals(getBlockByHashResult.getString("hash"), "0x" + bid); - Assert.assertEquals(getBlockByHashResult.getString("parentHash"), "0x" + parentHash); - Assert.assertEquals(getBlockByHashResult.getString("transactionsRoot"), "0x" + txTrieRoot); - Assert.assertEquals( - getBlockByHashResult.getString("miner"), "0x" + witnessAddress.substring(2)); - Assert.assertEquals(getBlockByHashResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); - Assert.assertEquals( - String.valueOf(Long.parseLong(getBlockByHashResult.getString("gasLimit").substring(2), 16)), - feeLimit); - Assert.assertEquals( - Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16), - blockTimeStamp); - final GrpcAPI.NumberMessage message = - GrpcAPI.NumberMessage.newBuilder().setNum(blockNum).build(); - HttpMethed.waitToProduceOneBlock(httpFullNode); - Block block = blockingStubFull.getBlockByNum(message); - logger.info("sizeFromJrpc:" + block.getSerializedSize()); - logger.info( - "sizeFromJsonRPc:" - + Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16)); - size = block.getSerializedSize(); - Assert.assertEquals( - Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16), - block.getSerializedSize()); - - Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16); - JSONArray transactionId = getBlockByHashResult.getJSONArray("transactions"); - List transactionIdListFromGetBlockByHash = new ArrayList<>(); - if (transactionId.size() > 0) { - for (int i = 0; i < transactionId.size(); i++) { - transactionIdListFromGetBlockByHash.add(transactionId.get(i).toString()); - } - } - Assert.assertEquals(transactionIdListFromGetBlockByHash, transactionIdList); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getBlockByNumFromSolidityber params is true") - public void test49JsonRpcApiTestForEthgetBlockByNumFromSolidityber() throws Exception { - - JsonArray params = new JsonArray(); - params.add(blockNumHex); - logger.info("46blockNumHex:" + blockNumHex); - params.add(true); - JsonObject requestBody = getJsonRpcBody("eth_getBlockByNumber", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - JSONObject getBlockByNumFromSolidityberResult = responseContent.getJSONObject("result"); - logger.info("getBlockByHashResult:" + getBlockByNumFromSolidityberResult); - - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("nonce")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("sha3Uncles")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("receiptsRoot")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("difficulty")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("totalDifficulty")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("extraData")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("baseFeePerGas")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("mixHash")); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("uncles"), new ArrayList<>().toString()); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("stateRoot"), "0x" + accountStateRoot); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("logsBloom"), - "0x00000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000"); - Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("number"), blockNumHex); - Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("hash"), "0x" + bid); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("parentHash"), "0x" + parentHash); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("transactionsRoot"), "0x" + txTrieRoot); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("miner"), "0x" + witnessAddress.substring(2)); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); - Assert.assertEquals( - String.valueOf( - Long.parseLong( - getBlockByNumFromSolidityberResult.getString("gasLimit").substring(2), 16)), - feeLimit); - Assert.assertEquals( - Long.parseLong(getBlockByNumFromSolidityberResult.getString("timestamp").substring(2), 16), - blockTimeStamp); - logger.info("size:" + size); - Assert.assertEquals( - Long.parseLong(getBlockByNumFromSolidityberResult.getString("size").substring(2), 16), - size); - - JSONArray transactionsList = getBlockByNumFromSolidityberResult.getJSONArray("transactions"); - logger.info("transactionsList:" + transactionsList); - List transactionInfoListFromGetBlockByHash = new ArrayList<>(); - if (transactionsList.size() > 0) { - for (int i = 0; i < transactionsList.size(); i++) { - transactionInfoListFromGetBlockByHash.add(transactionsList.get(i).toString()); - } - } - List transactionInfoListFromTransactionByBlockNumberAndIndex = new ArrayList<>(); - for (int i = 0; i < transactionsList.size(); i++) { - JsonArray paramsForEthGetTransactionByBlockNumberAndIndex = new JsonArray(); - paramsForEthGetTransactionByBlockNumberAndIndex.add(blockNumHex); - String index = "0x" + Integer.toHexString(i); - logger.info("index:" + index); - paramsForEthGetTransactionByBlockNumberAndIndex.add(index); - logger.info( - "paramsForEthGetTransactionByBlockNumberAndIndex:" - + paramsForEthGetTransactionByBlockNumberAndIndex); - JsonObject requestBodyForTransactionByBlockNumberAndIndex = - getJsonRpcBody( - "eth_getTransactionByBlockNumberAndIndex", - paramsForEthGetTransactionByBlockNumberAndIndex); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForTransactionByBlockNumberAndIndex); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - result = responseContent.getJSONObject("result"); - logger.info("result:" + result); - transactionInfoListFromTransactionByBlockNumberAndIndex.add(result.toString()); - } - Assert.assertEquals( - transactionInfoListFromGetBlockByHash, - transactionInfoListFromTransactionByBlockNumberAndIndex); - } - - /** constructor. */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } + logger.info("test15EthUninstallFilter_responseContent" + responseContent); + String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; + Assert.assertEquals(responseContent.get("error").toString(), expectResult); } } From 946226bb40ab4bf3d7dfc448a3d2217ea2b18741 Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Mon, 13 Dec 2021 18:11:37 +0800 Subject: [PATCH 15/24] add --- framework/src/test/resources/testng.conf | 1 + 1 file changed, 1 insertion(+) diff --git a/framework/src/test/resources/testng.conf b/framework/src/test/resources/testng.conf index a45891de8ca..2e5b9a375e0 100644 --- a/framework/src/test/resources/testng.conf +++ b/framework/src/test/resources/testng.conf @@ -85,6 +85,7 @@ jsonRpcNode = { ip.list = [ #"101.200.46.37:50545", "127.0.0.1:50545", + "127.0.0.1:50555", ] } From 41d1fde3b8ad30e738b8ee0d0a9efbc0fde129da Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Mon, 13 Dec 2021 19:33:36 +0800 Subject: [PATCH 16/24] add --- .../java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java index fda69348e23..8cfa74de312 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java @@ -212,6 +212,7 @@ public void test10GetLogsOnlyContainAddress() { paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 20))); JsonArray params = new JsonArray(); params.add(paramBody); + HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode,solidityNode); JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); @@ -234,6 +235,7 @@ public void test11GetLogsContainsTopicAndAddress() { paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 10))); JsonArray params = new JsonArray(); params.add(paramBody); + HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode,solidityNode); JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); From 8029efad407587105bd65a876b24a4af0932c456 Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Mon, 13 Dec 2021 19:34:46 +0800 Subject: [PATCH 17/24] add --- .../java/stest/tron/wallet/dailybuild/jsonrpc/Accounts001.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts001.java index d654364ce18..b1899052632 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts001.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts001.java @@ -1058,6 +1058,9 @@ public void test48JsonRpcApiTestForEthGetBlockByHash() throws Exception { .getJSONObject("block_header") .getJSONObject("raw_data") .getString("accountStateRoot"); + if (accountStateRoot == null) { + accountStateRoot = ""; + } JsonArray params = new JsonArray(); params.add(blockHash); params.add(false); From 6e807a1081fc088fe132f69ebc68289a2e2ca2c9 Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Tue, 14 Dec 2021 12:27:28 +0800 Subject: [PATCH 18/24] fix --- .../tron/wallet/dailybuild/http/HttpTestExchange001.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestExchange001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestExchange001.java index ce06d8f9f39..7d38b0540c6 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestExchange001.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestExchange001.java @@ -151,7 +151,7 @@ public void test05GetExchangeById() { response = HttpMethed.getExchangeById(httpnode, exchangeId); responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getInteger("exchange_id") == exchangeId); + Assert.assertTrue(responseContent.getInteger("exchange_id").equals(exchangeId)); Assert.assertEquals(responseContent.getString("creator_address"), ByteArray.toHexString(exchangeOwnerAddress)); beforeInjectBalance = responseContent.getLong("first_token_balance"); @@ -167,7 +167,7 @@ public void test06GetExchangeByIdFromSolidity() { response = HttpMethed.getExchangeByIdFromSolidity(httpSoliditynode, exchangeId); responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getInteger("exchange_id") == exchangeId); + Assert.assertTrue(responseContent.getInteger("exchange_id").equals(exchangeId)); Assert.assertEquals(responseContent.getString("creator_address"), ByteArray.toHexString(exchangeOwnerAddress)); beforeInjectBalance = responseContent.getLong("first_token_balance"); @@ -183,7 +183,7 @@ public void test07GetExchangeByIdFromPbft() { response = HttpMethed.getExchangeByIdFromPbft(httpPbftNode, exchangeId); responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getInteger("exchange_id") == exchangeId); + Assert.assertTrue(responseContent.getInteger("exchange_id").equals(exchangeId)); Assert.assertEquals(responseContent.getString("creator_address"), ByteArray.toHexString(exchangeOwnerAddress)); beforeInjectBalance = responseContent.getLong("first_token_balance"); From 24d606ead7be4f86f63f8665de8ec3f15461deb6 Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Tue, 14 Dec 2021 15:24:37 +0800 Subject: [PATCH 19/24] fix --- .../common/client/utils/JsonRpcBase.java | 4 +- .../dailybuild/jsonrpc/Accounts002.java | 2394 +++++++++-------- .../dailybuild/jsonrpc/Accounts004.java | 8 +- 3 files changed, 1206 insertions(+), 1200 deletions(-) diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java index 584a16f95e8..f017feb7478 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java @@ -60,8 +60,8 @@ public class JsonRpcBase { Configuration.getByPath("testng.conf").getStringList("jsonRpcNode.ip.list").get(1); public static String httpFullNode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(0); - public static String solidityNode = - Configuration.getByPath("testng.conf").getStringList("solidityNode.ip.list").get(0); + public static String httpsolidityNode = + Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(2); public static String ethHttpsNode = Configuration.getByPath("testng.conf").getStringList("ethHttpsNode.host.list").get(0); diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java index 735caf33130..11cec94ffb3 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java @@ -5,11 +5,13 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; import io.grpc.ManagedChannelBuilder; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; + import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpResponse; import org.junit.Assert; @@ -26,1217 +28,1221 @@ @Slf4j public class Accounts002 extends JsonRpcBase { - private JSONObject responseContent; - private HttpResponse response; - String realGasPrice; - String bid = null; - int indexNum = 0; - String indexHex = null; - JSONObject result = null; - String transacionHash = null; - String blockHash = null; - String blockNumHex = null; - String parentHash = null; - String txTrieRoot = null; - String witnessAddress = null; - String feeLimit = null; - String accountStateRoot = null; - String energyUsed = "0x135c6"; - - List transactionIdList = null; - long size = 0; - long gas = 0; - long blockTimeStamp = 0; - long gasPriceFromHttp = 0; - - /** constructor. */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Json rpc api of eth_accounts") - public void test01JsonRpcApiTestForEthAccounts() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_accounts", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - List result = new ArrayList(); - logger.info(String.valueOf(result)); - Assert.assertEquals(responseContent.get("result"), result); - } - - @Test(enabled = true, description = "Json rpc api of eth_blockNumber") - public void test02JsonRpcApiTestForEthBlockNumber() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_blockNumber", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String blockNum = responseContent.getString("result").substring(2); - long blockNumFromjsonRpcNodeForSolidity = Long.parseLong(blockNum, 16); - response = HttpMethed.getNowBlockFromSolidity(solidityNode); - responseContent = HttpMethed.parseResponseContent(response); - long blockNumFromHttp = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - logger.info("blocknumFromjsonRpcNodeForSolidity:" + blockNumFromjsonRpcNodeForSolidity); - logger.info("blocknumFromHttp:" + blockNumFromHttp); - Assert.assertTrue(Math.abs(blockNumFromjsonRpcNodeForSolidity - blockNumFromHttp) <= 3); - } - - @Test(enabled = true, description = "Json rpc api of eth_call") - public void test03JsonRpcApiTestForEthCall() throws Exception { - JsonObject param = new JsonObject(); - HttpMethed.waitToProduceOneBlock(httpFullNode); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x06fdde03"); - JsonArray params = new JsonArray(); - params.add(param); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_call", params); - logger.info("03params:" + params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals( - "0x000000000000000000000000000000000000000000000000000" - + "00000000000200000000000000000000000000000000000000000" - + "00000000000000000000000a546f6b656e5452433230000000000" - + "00000000000000000000000000000000000", - dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_chainId") - public void test04JsonRpcApiTestForEthChainId() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_chainId", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String blockIdFromjsonRpcNodeForSolidity = - responseContent.get("result").toString().substring(2); - response = HttpMethed.getBlockByNumFromSolidity(solidityNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - String blockIdFromHttp = responseContent.getString("blockID").substring(56); - logger.info("blockIdFromjsonRpcNodeForSolidity:" + blockIdFromjsonRpcNodeForSolidity); - logger.info("blockIdFromHttp:" + blockIdFromHttp); - Assert.assertEquals(blockIdFromjsonRpcNodeForSolidity, blockIdFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_coinbase") - public void test05JsonRpcApiTestForEthCoinbase() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_coinbase", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - - Assert.assertEquals( - "0x410be88a918d74d0dfd71dc84bd4abf036d0562991", responseContent.getString("result")); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGas") - public void test06JsonRpcApiTestForEthEstimateGas() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x1249c58b"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test06requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals("0x147", dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasHasPayable") - public void test07JsonRpcApiTestForEthEstimateGasHasPayable() throws Exception { - response = HttpMethed.getTransactionInfoByIdFromSolidity(solidityNode, txid); - responseContent = HttpMethed.parseResponseContent(response); - Long realEnergyUsed = responseContent.getJSONObject("receipt").getLong("energy_usage_total"); - logger.info("realEnergyUsed:" + realEnergyUsed); - JsonObject param = new JsonObject(); - param.addProperty("from", "0x" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2)); - param.addProperty("to", "0x" + contractAddressFrom58); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x1389"); - param.addProperty("data", data); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test07requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals((long) realEnergyUsed, Long.parseLong(dataResult.substring(2), 16)); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasWithoutTo") - public void test08JsonRpcApiTestForEthEstimateGasWithoutTo() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", "0x6C0214C9995C6F3A61AB23F0EB84B0CDE7FD9C7C"); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty( - "data", - "0x6080604052d3600055d2600155346002556101418061001f6000396000f30060806040" - + "52600436106100565763ffffffff7c010000000000000000000000000000000000000000" - + "000000000000000060003504166305c24200811461005b5780633be9ece7146100815780" - + "6371dc08ce146100aa575b600080fd5b6100636100b2565b6040805193845260208401929" - + "0925282820152519081900360600190f35b6100a873ffffffffffffffffffffffffffffff" - + "ffffffffff600435166024356044356100c0565b005b61006361010d565b60005460015460" - + "0254909192565b60405173ffffffffffffffffffffffffffffffffffffffff841690821561" - + "08fc029083908590600081818185878a8ad0945050505050158015610107573d6000803e3d" - + "6000fd5b50505050565bd3d2349091925600a165627a7a72305820a2fb39541e90eda9a2f5" - + "f9e7905ef98e66e60dd4b38e00b05de418da3154e757002900000000000000000000000000" - + "00000000000000000000000000000090fa17bb"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test08requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - logger.info("dataResult:" + dataResult); - Assert.assertEquals(energyUsed, dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasSendTrx") - public void test09JsonRpcApiTestForEthEstimateGasSendTrx() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", "0xC1A74CD01732542093F5A87910A398AD70F04BD7"); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x1"); - param.addProperty("data", "0x0"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test09requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals("0x0", dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_gasPrice") - public void test10JsonRpcApiTestForEthGasPrice() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_gasPrice", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String gasPrice = responseContent.get("result").toString().substring(2); - long gasPriceFromJsonrpc = Long.parseLong(gasPrice, 16); - logger.info(String.valueOf(gasPriceFromJsonrpc)); - response = HttpMethed.getChainParameters(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - JSONArray temp; - temp = responseContent.getJSONArray("chainParameter"); - for (int i = 0; i < temp.size(); i++) { - if (temp.getJSONObject(i).get("key").equals("getEnergyFee")) { - gasPriceFromHttp = temp.getJSONObject(i).getLong("value"); - } + private JSONObject responseContent; + private HttpResponse response; + String realGasPrice; + String bid = null; + int indexNum = 0; + String indexHex = null; + JSONObject result = null; + String transacionHash = null; + String blockHash = null; + String blockNumHex = null; + String parentHash = null; + String txTrieRoot = null; + String witnessAddress = null; + String feeLimit = null; + String accountStateRoot = null; + String energyUsed = "0x135c6"; + + List transactionIdList = null; + long size = 0; + long gas = 0; + long blockTimeStamp = 0; + long gasPriceFromHttp = 0; + + /** + * constructor. + */ + @BeforeClass(enabled = true) + public void beforeClass() { + channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); + blockingStubFull = WalletGrpc.newBlockingStub(channelFull); + } + + @Test(enabled = true, description = "Json rpc api of eth_accounts") + public void test01JsonRpcApiTestForEthAccounts() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_accounts", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + List result = new ArrayList(); + logger.info(String.valueOf(result)); + Assert.assertEquals(responseContent.get("result"), result); + } + + @Test(enabled = true, description = "Json rpc api of eth_blockNumber") + public void test02JsonRpcApiTestForEthBlockNumber() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_blockNumber", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + responseContent.get("result"); + String blockNum = responseContent.getString("result").substring(2); + long blockNumFromjsonRpcNodeForSolidity = Long.parseLong(blockNum, 16); + response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + long blockNumFromHttp = + responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); + logger.info("blocknumFromjsonRpcNodeForSolidity:" + blockNumFromjsonRpcNodeForSolidity); + logger.info("blocknumFromHttp:" + blockNumFromHttp); + Assert.assertTrue(Math.abs(blockNumFromjsonRpcNodeForSolidity - blockNumFromHttp) <= 3); + } + + @Test(enabled = true, description = "Json rpc api of eth_call") + public void test03JsonRpcApiTestForEthCall() throws Exception { + JsonObject param = new JsonObject(); + HttpMethed.waitToProduceOneBlock(httpFullNode); + param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); + param.addProperty("to", trc20AddressHex); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x0"); + param.addProperty("data", "0x06fdde03"); + JsonArray params = new JsonArray(); + params.add(param); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_call", params); + logger.info("03params:" + params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + Assert.assertEquals( + "0x000000000000000000000000000000000000000000000000000" + + "00000000000200000000000000000000000000000000000000000" + + "00000000000000000000000a546f6b656e5452433230000000000" + + "00000000000000000000000000000000000", + dataResult); + } + + @Test(enabled = true, description = "Json rpc api of eth_chainId") + public void test04JsonRpcApiTestForEthChainId() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_chainId", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + responseContent.get("result"); + String blockIdFromjsonRpcNodeForSolidity = + responseContent.get("result").toString().substring(2); + response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, 0); + responseContent = HttpMethed.parseResponseContent(response); + String blockIdFromHttp = responseContent.getString("blockID").substring(56); + logger.info("blockIdFromjsonRpcNodeForSolidity:" + blockIdFromjsonRpcNodeForSolidity); + logger.info("blockIdFromHttp:" + blockIdFromHttp); + Assert.assertEquals(blockIdFromjsonRpcNodeForSolidity, blockIdFromHttp); + } + + @Test(enabled = true, description = "Json rpc api of eth_coinbase") + public void test05JsonRpcApiTestForEthCoinbase() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_coinbase", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + + Assert.assertEquals( + "0x410be88a918d74d0dfd71dc84bd4abf036d0562991", responseContent.getString("result")); + } + + @Test(enabled = true, description = "Json rpc api of eth_estimateGas") + public void test06JsonRpcApiTestForEthEstimateGas() throws Exception { + JsonObject param = new JsonObject(); + param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); + param.addProperty("to", trc20AddressHex); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x0"); + param.addProperty("data", "0x1249c58b"); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("test06requestBody:" + requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + Assert.assertEquals("0x147", dataResult); + } + + @Test(enabled = true, description = "Json rpc api of eth_estimateGasHasPayable") + public void test07JsonRpcApiTestForEthEstimateGasHasPayable() throws Exception { + response = HttpMethed.getTransactionInfoByIdFromSolidity(httpsolidityNode, txid); + responseContent = HttpMethed.parseResponseContent(response); + Long realEnergyUsed = responseContent.getJSONObject("receipt").getLong("energy_usage_total"); + logger.info("realEnergyUsed:" + realEnergyUsed); + JsonObject param = new JsonObject(); + param.addProperty("from", "0x" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2)); + param.addProperty("to", "0x" + contractAddressFrom58); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x1389"); + param.addProperty("data", data); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("test07requestBody:" + requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + Assert.assertEquals((long) realEnergyUsed, Long.parseLong(dataResult.substring(2), 16)); + } + + @Test(enabled = true, description = "Json rpc api of eth_estimateGasWithoutTo") + public void test08JsonRpcApiTestForEthEstimateGasWithoutTo() throws Exception { + JsonObject param = new JsonObject(); + param.addProperty("from", "0x6C0214C9995C6F3A61AB23F0EB84B0CDE7FD9C7C"); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x0"); + param.addProperty( + "data", + "0x6080604052d3600055d2600155346002556101418061001f6000396000f30060806040" + + "52600436106100565763ffffffff7c010000000000000000000000000000000000000000" + + "000000000000000060003504166305c24200811461005b5780633be9ece7146100815780" + + "6371dc08ce146100aa575b600080fd5b6100636100b2565b6040805193845260208401929" + + "0925282820152519081900360600190f35b6100a873ffffffffffffffffffffffffffffff" + + "ffffffffff600435166024356044356100c0565b005b61006361010d565b60005460015460" + + "0254909192565b60405173ffffffffffffffffffffffffffffffffffffffff841690821561" + + "08fc029083908590600081818185878a8ad0945050505050158015610107573d6000803e3d" + + "6000fd5b50505050565bd3d2349091925600a165627a7a72305820a2fb39541e90eda9a2f5" + + "f9e7905ef98e66e60dd4b38e00b05de418da3154e757002900000000000000000000000000" + + "00000000000000000000000000000090fa17bb"); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("test08requestBody:" + requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + logger.info("dataResult:" + dataResult); + Assert.assertEquals(energyUsed, dataResult); + } + + @Test(enabled = true, description = "Json rpc api of eth_estimateGasSendTrx") + public void test09JsonRpcApiTestForEthEstimateGasSendTrx() throws Exception { + JsonObject param = new JsonObject(); + param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); + param.addProperty("to", "0xC1A74CD01732542093F5A87910A398AD70F04BD7"); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x1"); + param.addProperty("data", "0x0"); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("test09requestBody:" + requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + Assert.assertEquals("0x0", dataResult); + } + + @Test(enabled = true, description = "Json rpc api of eth_gasPrice") + public void test10JsonRpcApiTestForEthGasPrice() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_gasPrice", params); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + responseContent.get("result"); + String gasPrice = responseContent.get("result").toString().substring(2); + long gasPriceFromJsonrpc = Long.parseLong(gasPrice, 16); + logger.info(String.valueOf(gasPriceFromJsonrpc)); + response = HttpMethed.getChainParameters(httpFullNode); + responseContent = HttpMethed.parseResponseContent(response); + JSONArray temp; + temp = responseContent.getJSONArray("chainParameter"); + for (int i = 0; i < temp.size(); i++) { + if (temp.getJSONObject(i).get("key").equals("getEnergyFee")) { + gasPriceFromHttp = temp.getJSONObject(i).getLong("value"); + } + } + logger.info("gasPriceFromHttp:" + gasPriceFromHttp); + Assert.assertEquals(gasPriceFromJsonrpc, gasPriceFromHttp); + } + + @Test(enabled = true, description = "Json rpc api of eth_getBalance") + public void test11JsonRpcApiTestForEthGetBalance() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x" + ByteArray.toHexString(foundationAccountAddress).substring(2)); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getBalance", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String balance = responseContent.getString("result").substring(2); + Long balance1 = Long.parseLong(balance, 16); + logger.info("balance1:" + balance1); + response = HttpMethed.getAccountFromSolidity(httpsolidityNode, foundationAccountAddress); + responseContent = HttpMethed.parseResponseContent(response); + Long balance2 = responseContent.getLong("balance"); + logger.info(balance1.toString()); + logger.info(balance2.toString()); + Assert.assertEquals(balance1, balance2); } - logger.info("gasPriceFromHttp:" + gasPriceFromHttp); - Assert.assertEquals(gasPriceFromJsonrpc, gasPriceFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBalance") - public void test11JsonRpcApiTestForEthGetBalance() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x" + ByteArray.toHexString(foundationAccountAddress).substring(2)); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getBalance", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String balance = responseContent.getString("result").substring(2); - Long balance1 = Long.parseLong(balance, 16); - logger.info("balance1:" + balance1); - response = HttpMethed.getAccountFromSolidity(solidityNode, foundationAccountAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long balance2 = responseContent.getLong("balance"); - logger.info(balance1.toString()); - logger.info(balance2.toString()); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") - public void test12JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { - response = HttpMethed.getNowBlockFromSolidity(solidityNode); - responseContent = HttpMethed.parseResponseContent(response); - JsonArray params = new JsonArray(); - params.add("earliest"); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNum1 = Integer.parseInt(transactionNum, 16); - logger.info(String.valueOf(transactionNum1)); - response = HttpMethed.getTransactionCountByBlocknumFromSolidity(solidityNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNum2 = responseContent.getInteger("count"); - logger.info(String.valueOf(transactionNum2)); - Assert.assertEquals(transactionNum1, transactionNum2); - } - - @Test(enabled = true, description = "Json rpc api of eth_getCode") - public void test13JsonRpcApiTestForEthGetCode() throws Exception { - - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getCode", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String codeFromJsonRpc = responseContent.getString("result").substring(2); - logger.info(codeFromJsonRpc); - response = HttpMethed.getContractInfo(httpFullNode, contractAddressFrom58); - logger.info("13contractAddressFrom58:" + contractAddressFrom58); - responseContent = HttpMethed.parseResponseContent(response); - String codeFromHttp = responseContent.getString("runtimecode"); - logger.info(codeFromHttp); - Assert.assertEquals(codeFromJsonRpc, codeFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") - public void test14JsonRpcApiTestForEthGetStorageAt01() throws Exception { - - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add("0x0"); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("14responseContent:" + responseContent); - String result = responseContent.getString("result").substring(2); - long resultExpect = Long.parseLong(result, 16); - logger.info("result:" + resultExpect); - Assert.assertEquals("1234", String.valueOf(resultExpect)); - } - - @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") - public void test15JsonRpcApiTestForEthGetStorageAt02() throws Exception { - - String address = - "000000000000000000000000" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2); - String str = address + "0000000000000000000000000000000000000000000000000000000000000001"; - logger.info("str:" + str); - JsonArray paramsForSha3 = new JsonArray(); - paramsForSha3.add(str); - JsonObject requestBodyForSha3 = getJsonRpcBody("web3_sha3", paramsForSha3); - logger.info("requestBodyForSha3:" + requestBodyForSha3); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForSha3); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String resultForSha3 = responseContent.getString("result"); - logger.info("resultForSha3:" + resultForSha3); - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add(resultForSha3); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("15responseContent:" + responseContent); - String result = responseContent.getString("result").substring(2); - logger.info("15result:" + result); - logger.info("mapResult:" + Integer.parseInt(result, 16)); - Assert.assertEquals("5678", String.valueOf(Integer.parseInt(result, 16))); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockNumberAndIndex") - public void test16JsonRpcApiTestForEthGetTransactionByBlockNumberAndIndex() throws Exception { - logger.info("16blockNum:" + blockNum); - blockNumHex = "0x" + Integer.toHexString(blockNum); - logger.info("blockNumHex:" + blockNumHex); - JsonArray params = new JsonArray(); - params.add(blockNumHex); - indexNum = 0; - response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - parentHash = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("parentHash"); - txTrieRoot = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("txTrieRoot"); - witnessAddress = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("witness_address"); - feeLimit = - responseContent - .getJSONArray("transactions") - .getJSONObject(0) - .getJSONObject("raw_data") - .getString("fee_limit"); - logger.info(feeLimit); - - JSONObject getBlockByNumFromSolidityResult = null; - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - if (txid.equals( - responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { - indexNum = i; - getBlockByNumFromSolidityResult = - responseContent.getJSONArray("transactions").getJSONObject(i); - bid = responseContent.getString("blockID"); - break; - } + + @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") + public void test12JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { + response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + JsonArray params = new JsonArray(); + params.add("earliest"); + JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String transactionNum = responseContent.getString("result").substring(2); + int transactionNum1 = Integer.parseInt(transactionNum, 16); + logger.info(String.valueOf(transactionNum1)); + response = HttpMethed.getTransactionCountByBlocknumFromSolidity(httpsolidityNode, 0); + responseContent = HttpMethed.parseResponseContent(response); + int transactionNum2 = responseContent.getInteger("count"); + logger.info(String.valueOf(transactionNum2)); + Assert.assertEquals(transactionNum1, transactionNum2); } - transactionIdList = new ArrayList<>(); - if (responseContent.getJSONArray("transactions").size() > 0) { - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - transactionIdList.add( - "0x" + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID")); - } + + @Test(enabled = true, description = "Json rpc api of eth_getCode") + public void test13JsonRpcApiTestForEthGetCode() throws Exception { + + JsonArray params = new JsonArray(); + params.add(contractAddressFrom58); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getCode", params); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String codeFromJsonRpc = responseContent.getString("result").substring(2); + logger.info(codeFromJsonRpc); + response = HttpMethed.getContractInfo(httpFullNode, contractAddressFrom58); + logger.info("13contractAddressFrom58:" + contractAddressFrom58); + responseContent = HttpMethed.parseResponseContent(response); + String codeFromHttp = responseContent.getString("runtimecode"); + logger.info(codeFromHttp); + Assert.assertEquals(codeFromJsonRpc, codeFromHttp); } - logger.info("16transactionIdList:" + transactionIdList); - logger.info(String.valueOf(indexNum)); - indexHex = "0x" + Integer.toHexString(indexNum); - logger.info("indexHex:" + indexHex); - params.add(indexHex); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockNumberAndIndex", params); - logger.info("13requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - result = responseContent.getJSONObject("result"); - logger.info("16 result" + result); - Map jsonrpcResult = new HashMap(); - for (Map.Entry entry : result.entrySet()) { - jsonrpcResult.put(entry.getKey(), entry.getValue()); + + @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") + public void test14JsonRpcApiTestForEthGetStorageAt01() throws Exception { + + JsonArray params = new JsonArray(); + params.add(contractAddressFrom58); + params.add("0x0"); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("14responseContent:" + responseContent); + String result = responseContent.getString("result").substring(2); + long resultExpect = Long.parseLong(result, 16); + logger.info("result:" + resultExpect); + Assert.assertEquals("1234", String.valueOf(resultExpect)); } - transacionHash = jsonrpcResult.get("hash").toString(); - logger.info("transactionHash:" + transacionHash); - blockHash = jsonrpcResult.get("blockHash").toString(); - logger.info("jsonrpcResult:" + jsonrpcResult); - response = HttpMethed.getTransactionInfoByBlocknumFromSolidity(solidityNode, blockNum); - logger.info("response:" + response); - List responseContent1 = HttpMethed.parseResponseContentArray(response); - logger.info("responseContent1:" + responseContent1); - blockTimeStamp = responseContent1.get(0).getLong("blockTimeStamp"); - - for (int i = 0; i < responseContent1.size(); i++) { - if (responseContent1.get(i).getString("id").equals(transactionIdList.get(0).substring(2))) { - gas = responseContent1.get(i).getJSONObject("receipt").getLong("energy_usage_total"); - logger.info("gas:" + gas); - break; - } + + @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") + public void test15JsonRpcApiTestForEthGetStorageAt02() throws Exception { + + String address = + "000000000000000000000000" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2); + String str = address + "0000000000000000000000000000000000000000000000000000000000000001"; + logger.info("str:" + str); + JsonArray paramsForSha3 = new JsonArray(); + paramsForSha3.add(str); + JsonObject requestBodyForSha3 = getJsonRpcBody("web3_sha3", paramsForSha3); + logger.info("requestBodyForSha3:" + requestBodyForSha3); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForSha3); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + String resultForSha3 = responseContent.getString("result"); + logger.info("resultForSha3:" + resultForSha3); + JsonArray params = new JsonArray(); + params.add(contractAddressFrom58); + params.add(resultForSha3); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("15responseContent:" + responseContent); + String result = responseContent.getString("result").substring(2); + logger.info("15result:" + result); + logger.info("mapResult:" + Integer.parseInt(result, 16)); + Assert.assertEquals("5678", String.valueOf(Integer.parseInt(result, 16))); + } + + @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockNumberAndIndex") + public void test16JsonRpcApiTestForEthGetTransactionByBlockNumberAndIndex() throws Exception { + logger.info("16blockNum:" + blockNum); + blockNumHex = "0x" + Integer.toHexString(blockNum); + logger.info("blockNumHex:" + blockNumHex); + JsonArray params = new JsonArray(); + params.add(blockNumHex); + indexNum = 0; + response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNum); + responseContent = HttpMethed.parseResponseContent(response); + parentHash = + responseContent + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getString("parentHash"); + txTrieRoot = + responseContent + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getString("txTrieRoot"); + witnessAddress = + responseContent + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getString("witness_address"); + feeLimit = + responseContent + .getJSONArray("transactions") + .getJSONObject(0) + .getJSONObject("raw_data") + .getString("fee_limit"); + logger.info(feeLimit); + + JSONObject getBlockByNumFromSolidityResult = null; + for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { + if (txid.equals( + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { + indexNum = i; + getBlockByNumFromSolidityResult = + responseContent.getJSONArray("transactions").getJSONObject(i); + bid = responseContent.getString("blockID"); + break; + } + } + transactionIdList = new ArrayList<>(); + if (responseContent.getJSONArray("transactions").size() > 0) { + for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { + transactionIdList.add( + "0x" + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID")); + } + } + logger.info("16transactionIdList:" + transactionIdList); + logger.info(String.valueOf(indexNum)); + indexHex = "0x" + Integer.toHexString(indexNum); + logger.info("indexHex:" + indexHex); + params.add(indexHex); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockNumberAndIndex", params); + logger.info("13requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + result = responseContent.getJSONObject("result"); + logger.info("16 result" + result); + Map jsonrpcResult = new HashMap(); + for (Map.Entry entry : result.entrySet()) { + jsonrpcResult.put(entry.getKey(), entry.getValue()); + } + transacionHash = jsonrpcResult.get("hash").toString(); + logger.info("transactionHash:" + transacionHash); + blockHash = jsonrpcResult.get("blockHash").toString(); + logger.info("jsonrpcResult:" + jsonrpcResult); + response = HttpMethed.getTransactionInfoByBlocknumFromSolidity(httpsolidityNode, blockNum); + logger.info("response:" + response); + List responseContent1 = HttpMethed.parseResponseContentArray(response); + logger.info("responseContent1:" + responseContent1); + blockTimeStamp = responseContent1.get(0).getLong("blockTimeStamp"); + + for (int i = 0; i < responseContent1.size(); i++) { + if (responseContent1.get(i).getString("id").equals(transactionIdList.get(0).substring(2))) { + gas = responseContent1.get(i).getJSONObject("receipt").getLong("energy_usage_total"); + logger.info("gas:" + gas); + break; + } + } + + Assert.assertEquals(jsonrpcResult.get("gas").toString(), "0x" + Long.toHexString(gas)); + Assert.assertNull(jsonrpcResult.get("nonce")); + Assert.assertEquals( + jsonrpcResult.get("hash").toString(), + "0x" + getBlockByNumFromSolidityResult.getString("txID")); + Assert.assertEquals(jsonrpcResult.get("blockHash").toString(), "0x" + bid); + Assert.assertEquals(jsonrpcResult.get("blockNumber").toString(), blockNumHex); + Assert.assertEquals(jsonrpcResult.get("transactionIndex").toString(), indexHex); + Assert.assertEquals( + jsonrpcResult.get("from").toString(), + "0x" + + getBlockByNumFromSolidityResult + .getJSONObject("raw_data") + .getJSONArray("contract") + .getJSONObject(0) + .getJSONObject("parameter") + .getJSONObject("value") + .getString("owner_address") + .substring(2)); + Assert.assertEquals( + jsonrpcResult.get("to").toString(), + "0x" + + getBlockByNumFromSolidityResult + .getJSONObject("raw_data") + .getJSONArray("contract") + .getJSONObject(0) + .getJSONObject("parameter") + .getJSONObject("value") + .getString("contract_address") + .substring(2)); + + Assert.assertEquals(jsonrpcResult.get("value").toString(), "0x1389"); + String data; + if (getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data") == null) { + data = "0x"; + } else { + data = + getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data").substring(2); + } + Assert.assertEquals(jsonrpcResult.get("input").toString(), data); + + long temp = + Long.parseLong( + getBlockByNumFromSolidityResult.getString("signature").substring(130, 131), 16); + long v = + Long.parseLong( + getBlockByNumFromSolidityResult.getString("signature").substring(130, 132), 16); + if (temp < 27) { + v += 27; + } + Assert.assertEquals(Long.parseLong(jsonrpcResult.get("v").toString().substring(2), 16), v); + Assert.assertEquals( + jsonrpcResult.get("r").toString().substring(2), + getBlockByNumFromSolidityResult.getString("signature").substring(2, 66)); + Assert.assertEquals( + jsonrpcResult.get("s").toString().substring(2), + getBlockByNumFromSolidityResult.getString("signature").substring(66, 130)); + } + + @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByHash") + public void test17JsonRpcApiTestForEthGetBlockTransactionCountByHash() throws Exception { + logger.info("blockNum:" + blockNum); + JsonArray params = new JsonArray(); + params.add(blockHash); + logger.info("blockHash:" + blockHash); + JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByHash", params); + logger.info("requestBody:" + requestBody); + HttpMethed.waitToProduceOneBlock(httpFullNode); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + String transactionNum = responseContent.getString("result").substring(2); + int transactionNumFromjsonRpcNodeForSolidity = Integer.parseInt(transactionNum, 16); + logger.info( + "transactionNumFromjsonRpcNodeForSolidity:" + transactionNumFromjsonRpcNodeForSolidity); + response = HttpMethed.getTransactionCountByBlocknumFromSolidity(httpsolidityNode, blockNum); + responseContent = HttpMethed.parseResponseContent(response); + int transactionNumFromHttp = responseContent.getInteger("count"); + logger.info("transactionNumFromHttp:" + transactionNumFromHttp); + Assert.assertEquals(transactionNumFromHttp, transactionNumFromjsonRpcNodeForSolidity); } - Assert.assertEquals(jsonrpcResult.get("gas").toString(), "0x" + Long.toHexString(gas)); - Assert.assertNull(jsonrpcResult.get("nonce")); - Assert.assertEquals( - jsonrpcResult.get("hash").toString(), - "0x" + getBlockByNumFromSolidityResult.getString("txID")); - Assert.assertEquals(jsonrpcResult.get("blockHash").toString(), "0x" + bid); - Assert.assertEquals(jsonrpcResult.get("blockNumber").toString(), blockNumHex); - Assert.assertEquals(jsonrpcResult.get("transactionIndex").toString(), indexHex); - Assert.assertEquals( - jsonrpcResult.get("from").toString(), - "0x" - + getBlockByNumFromSolidityResult - .getJSONObject("raw_data") - .getJSONArray("contract") - .getJSONObject(0) - .getJSONObject("parameter") - .getJSONObject("value") - .getString("owner_address") - .substring(2)); - Assert.assertEquals( - jsonrpcResult.get("to").toString(), - "0x" - + getBlockByNumFromSolidityResult - .getJSONObject("raw_data") - .getJSONArray("contract") - .getJSONObject(0) - .getJSONObject("parameter") - .getJSONObject("value") - .getString("contract_address") - .substring(2)); - - Assert.assertEquals(jsonrpcResult.get("value").toString(), "0x1389"); - String data; - if (getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data") == null) { - data = "0x"; - } else { - data = - getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data").substring(2); + @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") + public void test18JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { + JsonArray params = new JsonArray(); + params.add(blockNum); + logger.info(String.valueOf(blockNum)); + JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("response:" + response); + HttpMethed.waitToProduceOneBlock(httpFullNode); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + String transactionNum = responseContent.getString("result").substring(2); + int transactionNum1 = Integer.parseInt(transactionNum, 16); + logger.info(String.valueOf(transactionNum1)); + response = HttpMethed.getTransactionCountByBlocknumFromSolidity(httpsolidityNode, blockNum); + responseContent = HttpMethed.parseResponseContent(response); + int transactionNum2 = responseContent.getInteger("count"); + logger.info(String.valueOf(transactionNum2)); + Assert.assertEquals(transactionNum1, transactionNum2); } - Assert.assertEquals(jsonrpcResult.get("input").toString(), data); - - long temp = - Long.parseLong( - getBlockByNumFromSolidityResult.getString("signature").substring(130, 131), 16); - long v = - Long.parseLong( - getBlockByNumFromSolidityResult.getString("signature").substring(130, 132), 16); - if (temp < 27) { - v += 27; + + @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockHashAndIndex") + public void test19JsonRpcApiTestForEthGetTransactionByBlockHashAndIndex() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x" + bid); + params.add(indexHex); + logger.info("indexHex:" + indexHex); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockHashAndIndex", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject resultForGetTransactionByBlockHashAndIndex = responseContent.getJSONObject("result"); + Assert.assertEquals(result, resultForGetTransactionByBlockHashAndIndex); } - Assert.assertEquals(Long.parseLong(jsonrpcResult.get("v").toString().substring(2), 16), v); - Assert.assertEquals( - jsonrpcResult.get("r").toString().substring(2), - getBlockByNumFromSolidityResult.getString("signature").substring(2, 66)); - Assert.assertEquals( - jsonrpcResult.get("s").toString().substring(2), - getBlockByNumFromSolidityResult.getString("signature").substring(66, 130)); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByHash") - public void test17JsonRpcApiTestForEthGetBlockTransactionCountByHash() throws Exception { - logger.info("blockNum:" + blockNum); - JsonArray params = new JsonArray(); - params.add(blockHash); - logger.info("blockHash:" + blockHash); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByHash", params); - logger.info("requestBody:" + requestBody); - HttpMethed.waitToProduceOneBlock(httpFullNode); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNumFromjsonRpcNodeForSolidity = Integer.parseInt(transactionNum, 16); - logger.info( - "transactionNumFromjsonRpcNodeForSolidity:" + transactionNumFromjsonRpcNodeForSolidity); - response = HttpMethed.getTransactionCountByBlocknumFromSolidity(solidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNumFromHttp = responseContent.getInteger("count"); - logger.info("transactionNumFromHttp:" + transactionNumFromHttp); - Assert.assertEquals(transactionNumFromHttp, transactionNumFromjsonRpcNodeForSolidity); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") - public void test18JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { - JsonArray params = new JsonArray(); - params.add(blockNum); - logger.info(String.valueOf(blockNum)); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("response:" + response); - HttpMethed.waitToProduceOneBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNum1 = Integer.parseInt(transactionNum, 16); - logger.info(String.valueOf(transactionNum1)); - response = HttpMethed.getTransactionCountByBlocknumFromSolidity(solidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNum2 = responseContent.getInteger("count"); - logger.info(String.valueOf(transactionNum2)); - Assert.assertEquals(transactionNum1, transactionNum2); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockHashAndIndex") - public void test19JsonRpcApiTestForEthGetTransactionByBlockHashAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x" + bid); - params.add(indexHex); - logger.info("indexHex:" + indexHex); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockHashAndIndex", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultForGetTransactionByBlockHashAndIndex = responseContent.getJSONObject("result"); - Assert.assertEquals(result, resultForGetTransactionByBlockHashAndIndex); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionByHash") - public void test20JsonRpcApiTestForEthGetTransactionByHash() throws Exception { - JsonArray params = new JsonArray(); - params.add(transacionHash); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByHash", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject result1 = responseContent.getJSONObject("result"); - Assert.assertEquals(result, result1); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionReceipt") - public void test21JsonRpcApiTestForEthGetTransactionReceipt() throws Exception { - JsonArray params = new JsonArray(); - Thread.sleep(6000); - params.add(trc20Txid); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionReceipt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("response:" + response); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultFromTransactionReceipt = responseContent.getJSONObject("result"); - logger.info("resultFromTransactionReceipt:" + resultFromTransactionReceipt); - JSONArray logs = resultFromTransactionReceipt.getJSONArray("logs"); - logger.info("logs:" + logs); - logger.info("result:" + resultFromTransactionReceipt.toString()); - response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - int index = 0; - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - if (trc20Txid.equals( - responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { - index = i; - break; - } + + @Test(enabled = true, description = "Json rpc api of eth_getTransactionByHash") + public void test20JsonRpcApiTestForEthGetTransactionByHash() throws Exception { + JsonArray params = new JsonArray(); + params.add(transacionHash); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionByHash", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject result1 = responseContent.getJSONObject("result"); + Assert.assertEquals(result, result1); } - JsonArray paramsForTransactionByBlockNumberAndIndex = new JsonArray(); - paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(blockNumForTrc20)); - paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(index)); - JsonObject requestBody1 = - getJsonRpcBody( - "eth_getTransactionByBlockNumberAndIndex", paramsForTransactionByBlockNumberAndIndex); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); - logger.info("requestBody1:" + requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultFromTransactionByBlockNumberAndIndex = responseContent.getJSONObject("result"); - logger.info( - "resultFromTransactionByBlockNumberAndIndex:" + resultFromTransactionByBlockNumberAndIndex); - Assert.assertEquals( - resultFromTransactionReceipt.getString("blockHash"), - resultFromTransactionByBlockNumberAndIndex.getString("blockHash")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("blockNumber"), - resultFromTransactionByBlockNumberAndIndex.getString("blockNumber")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("transactionIndex"), - resultFromTransactionByBlockNumberAndIndex.getString("transactionIndex")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("transactionHash"), "0x" + trc20Txid); - Assert.assertEquals( - resultFromTransactionReceipt.getString("from"), - resultFromTransactionByBlockNumberAndIndex.getString("from")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("to"), - resultFromTransactionByBlockNumberAndIndex.getString("to")); - logger.info("effectiveGasPrice:" + resultFromTransactionReceipt.getString("effectiveGasPrice")); - logger.info("gasPriceFromHttp:" + Long.toHexString(gasPriceFromHttp)); - Assert.assertEquals( - resultFromTransactionReceipt.getString("effectiveGasPrice"), - "0x" + Long.toHexString(gasPriceFromHttp)); + @Test(enabled = true, description = "Json rpc api of eth_getTransactionReceipt") + public void test21JsonRpcApiTestForEthGetTransactionReceipt() throws Exception { + JsonArray params = new JsonArray(); + Thread.sleep(6000); + params.add(trc20Txid); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionReceipt", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("response:" + response); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject resultFromTransactionReceipt = responseContent.getJSONObject("result"); + logger.info("resultFromTransactionReceipt:" + resultFromTransactionReceipt); + JSONArray logs = resultFromTransactionReceipt.getJSONArray("logs"); + logger.info("logs:" + logs); + logger.info("result:" + resultFromTransactionReceipt.toString()); + response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNumForTrc20); + responseContent = HttpMethed.parseResponseContent(response); + int index = 0; + for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { + if (trc20Txid.equals( + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { + index = i; + break; + } + } + + JsonArray paramsForTransactionByBlockNumberAndIndex = new JsonArray(); + paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(blockNumForTrc20)); + paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(index)); + JsonObject requestBody1 = + getJsonRpcBody( + "eth_getTransactionByBlockNumberAndIndex", paramsForTransactionByBlockNumberAndIndex); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); + logger.info("requestBody1:" + requestBody1); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject resultFromTransactionByBlockNumberAndIndex = responseContent.getJSONObject("result"); + logger.info( + "resultFromTransactionByBlockNumberAndIndex:" + resultFromTransactionByBlockNumberAndIndex); + Assert.assertEquals( + resultFromTransactionReceipt.getString("blockHash"), + resultFromTransactionByBlockNumberAndIndex.getString("blockHash")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("blockNumber"), + resultFromTransactionByBlockNumberAndIndex.getString("blockNumber")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("transactionIndex"), + resultFromTransactionByBlockNumberAndIndex.getString("transactionIndex")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("transactionHash"), "0x" + trc20Txid); + Assert.assertEquals( + resultFromTransactionReceipt.getString("from"), + resultFromTransactionByBlockNumberAndIndex.getString("from")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("to"), + resultFromTransactionByBlockNumberAndIndex.getString("to")); + logger.info("effectiveGasPrice:" + resultFromTransactionReceipt.getString("effectiveGasPrice")); + logger.info("gasPriceFromHttp:" + Long.toHexString(gasPriceFromHttp)); + Assert.assertEquals( + resultFromTransactionReceipt.getString("effectiveGasPrice"), + "0x" + Long.toHexString(gasPriceFromHttp)); /* Assert.assertEquals( resultFromTransactionReceipt.getString("contractAddress").substring(2), trc20AddressHex.substring(2));*/ - Assert.assertNull(resultFromTransactionReceipt.getString("contractAddress")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("logsBloom"), - "0x000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000"); - Assert.assertEquals("0x1", resultFromTransactionReceipt.getString("status")); - Assert.assertEquals("0x0", resultFromTransactionReceipt.getString("type")); - logger.info("gas:" + resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("gasUsed"), - resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("cumulativeGasUsed"), - resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - logs.getJSONObject(0).getString("logIndex"), "0x" + Integer.toHexString(index)); - Assert.assertEquals(logs.getJSONObject(0).getString("removed"), "false"); - Assert.assertEquals( - logs.getJSONObject(0).getString("blockHash"), - resultFromTransactionReceipt.getString("blockHash")); - Assert.assertEquals( - logs.getJSONObject(0).getString("blockNumber"), - resultFromTransactionReceipt.getString("blockNumber")); - Assert.assertEquals( - logs.getJSONObject(0).getString("transactionIndex"), - resultFromTransactionReceipt.getString("transactionIndex")); - Assert.assertEquals( - logs.getJSONObject(0).getString("transactionHash"), - resultFromTransactionReceipt.getString("transactionHash")); - Assert.assertEquals( - logs.getJSONObject(0).getString("address"), resultFromTransactionReceipt.getString("to")); - response = HttpMethed.getTransactionInfoByBlocknumFromSolidity(solidityNode, blockNumForTrc20); - List responseContent1 = HttpMethed.parseResponseContentArray(response); - logger.info("responseContent1:" + responseContent1); - - response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertEquals( - logs.getJSONObject(0).getString("data").substring(2), - responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("data")); - - Assert.assertEquals( - logs.getJSONObject(0).getString("topics").replace("0x", ""), - responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("topics")); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockHashAndIndex") - public void test22JsonRpcApiTestForEthGetUncleByBlockHashAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); - params.add("0x"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockHashAndIndex", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNull(result); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockNumberAndIndex") - public void test23JsonRpcApiTestForEthGetUncleByBlockNumberAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0xeb82f0"); - params.add("0x"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockNumberAndIndex", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNull(result); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockHash") - public void test24JsonRpcApiTestForEthGetUncleCountByBlockHash() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockHash", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "0x0"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockNumber") - public void test25JsonRpcApiTestForEthGetUncleCountByBlockNumber() throws Exception { - JsonArray params = new JsonArray(); - params.add("eth_getUncleCountByBlockNumber"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockNumber", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "0x0"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getWork") - public void test26JsonRpcApiTestForEthGetWork() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_getWork", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - int resultLen = result.length(); - String resultFromjsonRpcNodeForSolidity = result.substring(4, resultLen - 12); - response = HttpMethed.getNowBlockFromSolidity(solidityNode); - responseContent = HttpMethed.parseResponseContent(response); - String resultFromHttp = responseContent.getString("blockID"); - logger.info("resultFromjsonRpcNodeForSolidity:" + resultFromjsonRpcNodeForSolidity); - logger.info("resultFromHttp:" + resultFromHttp); - Assert.assertEquals(resultFromjsonRpcNodeForSolidity, resultFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_hashrate") - public void test27JsonRpcApiTestForEthHashRate() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_hashrate", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals("0x0", result); - } - - @Test(enabled = true, description = "Json rpc api of eth_mining") - public void test28JsonRpcApiTestForEthMining() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_mining", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "true"); - } - - @Test(enabled = true, description = "Json rpc api of eth_protocolVersion") - public void test29JsonRpcApiTestForEthProtocolVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_protocolVersion", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String protocolVersion = responseContent.getString("result").substring(2); - Long protocolVersion1 = Long.parseLong(protocolVersion, 16); - response = HttpMethed.getNowBlockFromSolidity(solidityNode); - responseContent = HttpMethed.parseResponseContent(response); - Long protocolVersion2 = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("version"); - logger.info(protocolVersion1.toString()); - logger.info(protocolVersion2.toString()); - Assert.assertEquals(protocolVersion1, protocolVersion2); - } - - @Test(enabled = true, description = "Json rpc api of eth_syncing") - public void test30JsonRpcApiTestForEthSyncing() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_syncing", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject temp = responseContent.getJSONObject("result"); - String currentNumFromRpc = temp.getString("currentBlock"); - logger.info(currentNumFromRpc); - logger.info(temp.toString()); - response = HttpMethed.getNowBlockFromSolidity(solidityNode); - responseContent = HttpMethed.parseResponseContent(response); - long currentNum = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - logger.info("currentNum:" + currentNum); - logger.info("currentNumFromRpc:" + Long.parseLong(currentNumFromRpc.substring(2), 16)); - Assert.assertEquals(currentNum, Long.parseLong(currentNumFromRpc.substring(2), 16)); - Assert.assertTrue(temp.containsKey("startingBlock")); - Assert.assertTrue(temp.containsKey("currentBlock")); - Assert.assertTrue(temp.containsKey("highestBlock")); - } - - @Test(enabled = true, description = "Json rpc api of net_listening") - public void test31JsonRpcApiTestForNetListening() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_listening", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - Boolean temp = responseContent.getBoolean("result"); - logger.info(temp.toString()); - response = HttpMethed.getNodeInfo(solidityNode); - responseContent = HttpMethed.parseResponseContent(response); - boolean expect = false; - int num = responseContent.getInteger("activeConnectCount"); - if (num >= 1) { - expect = true; + Assert.assertNull(resultFromTransactionReceipt.getString("contractAddress")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("logsBloom"), + "0x000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000"); + Assert.assertEquals("0x1", resultFromTransactionReceipt.getString("status")); + Assert.assertEquals("0x0", resultFromTransactionReceipt.getString("type")); + logger.info("gas:" + resultFromTransactionByBlockNumberAndIndex.getString("gas")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("gasUsed"), + resultFromTransactionByBlockNumberAndIndex.getString("gas")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("cumulativeGasUsed"), + resultFromTransactionByBlockNumberAndIndex.getString("gas")); + Assert.assertEquals( + logs.getJSONObject(0).getString("logIndex"), "0x" + Integer.toHexString(index)); + Assert.assertEquals(logs.getJSONObject(0).getString("removed"), "false"); + Assert.assertEquals( + logs.getJSONObject(0).getString("blockHash"), + resultFromTransactionReceipt.getString("blockHash")); + Assert.assertEquals( + logs.getJSONObject(0).getString("blockNumber"), + resultFromTransactionReceipt.getString("blockNumber")); + Assert.assertEquals( + logs.getJSONObject(0).getString("transactionIndex"), + resultFromTransactionReceipt.getString("transactionIndex")); + Assert.assertEquals( + logs.getJSONObject(0).getString("transactionHash"), + resultFromTransactionReceipt.getString("transactionHash")); + Assert.assertEquals( + logs.getJSONObject(0).getString("address"), resultFromTransactionReceipt.getString("to")); + response = HttpMethed.getTransactionInfoByBlocknumFromSolidity(httpsolidityNode, blockNumForTrc20); + List responseContent1 = HttpMethed.parseResponseContentArray(response); + logger.info("responseContent1:" + responseContent1); + + response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNumForTrc20); + responseContent = HttpMethed.parseResponseContent(response); + Assert.assertEquals( + logs.getJSONObject(0).getString("data").substring(2), + responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("data")); + + Assert.assertEquals( + logs.getJSONObject(0).getString("topics").replace("0x", ""), + responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("topics")); + } + + @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockHashAndIndex") + public void test22JsonRpcApiTestForEthGetUncleByBlockHashAndIndex() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); + params.add("0x"); + JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockHashAndIndex", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertNull(result); + } + + @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockNumberAndIndex") + public void test23JsonRpcApiTestForEthGetUncleByBlockNumberAndIndex() throws Exception { + JsonArray params = new JsonArray(); + params.add("0xeb82f0"); + params.add("0x"); + JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockNumberAndIndex", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertNull(result); + } + + @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockHash") + public void test24JsonRpcApiTestForEthGetUncleCountByBlockHash() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); + JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockHash", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertEquals(result, "0x0"); + } + + @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockNumber") + public void test25JsonRpcApiTestForEthGetUncleCountByBlockNumber() throws Exception { + JsonArray params = new JsonArray(); + params.add("eth_getUncleCountByBlockNumber"); + JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockNumber", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertEquals(result, "0x0"); + } + + @Test(enabled = true, description = "Json rpc api of eth_getWork") + public void test26JsonRpcApiTestForEthGetWork() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_getWork", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + int resultLen = result.length(); + String resultFromjsonRpcNodeForSolidity = result.substring(4, resultLen - 12); + response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + String resultFromHttp = responseContent.getString("blockID"); + logger.info("resultFromjsonRpcNodeForSolidity:" + resultFromjsonRpcNodeForSolidity); + logger.info("resultFromHttp:" + resultFromHttp); + Assert.assertEquals(resultFromjsonRpcNodeForSolidity, resultFromHttp); + } + + @Test(enabled = true, description = "Json rpc api of eth_hashrate") + public void test27JsonRpcApiTestForEthHashRate() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_hashrate", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertEquals("0x0", result); + } + + @Test(enabled = true, description = "Json rpc api of eth_mining") + public void test28JsonRpcApiTestForEthMining() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_mining", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertEquals(result, "true"); + } + + @Test(enabled = true, description = "Json rpc api of eth_protocolVersion") + public void test29JsonRpcApiTestForEthProtocolVersion() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_protocolVersion", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String protocolVersion = responseContent.getString("result").substring(2); + Long protocolVersion1 = Long.parseLong(protocolVersion, 16); + response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + Long protocolVersion2 = + responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("version"); + logger.info(protocolVersion1.toString()); + logger.info(protocolVersion2.toString()); + Assert.assertEquals(protocolVersion1, protocolVersion2); + } + + @Test(enabled = true, description = "Json rpc api of eth_syncing") + public void test30JsonRpcApiTestForEthSyncing() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_syncing", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject temp = responseContent.getJSONObject("result"); + String currentNumFromRpc = temp.getString("currentBlock"); + logger.info(currentNumFromRpc); + logger.info(temp.toString()); + response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + long currentNum = + responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); + logger.info("currentNum:" + currentNum); + logger.info("currentNumFromRpc:" + Long.parseLong(currentNumFromRpc.substring(2), 16)); + Assert.assertEquals(currentNum, Long.parseLong(currentNumFromRpc.substring(2), 16)); + Assert.assertTrue(temp.containsKey("startingBlock")); + Assert.assertTrue(temp.containsKey("currentBlock")); + Assert.assertTrue(temp.containsKey("highestBlock")); + } + + @Test(enabled = true, description = "Json rpc api of net_listening") + public void test31JsonRpcApiTestForNetListening() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("net_listening", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + Boolean temp = responseContent.getBoolean("result"); + logger.info(temp.toString()); + response = HttpMethed.getNodeInfo(httpsolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + boolean expect = false; + int num = responseContent.getInteger("activeConnectCount"); + if (num >= 1) { + expect = true; + } + Assert.assertEquals(temp, expect); + } + + @Test(enabled = true, description = "Json rpc api of net_peerCount") + public void test32JsonRpcApiTestForNetPeerCount() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("net_peerCount", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertNotNull(result); + } + + @Test(enabled = true, description = "Json rpc api of net_version") + public void test33JsonRpcApiTestForEthVersion() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("net_version", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String firstBlockHashFromJsonRpc = responseContent.getString("result").substring(2); + response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, 0); + responseContent = HttpMethed.parseResponseContent(response); + String firstBlockHashFromHttp = responseContent.getString("blockID").substring(56); + logger.info("firstBlockHashFromJsonRpc" + firstBlockHashFromJsonRpc); + logger.info("firstBlockHashFromHttp" + firstBlockHashFromHttp); + Assert.assertEquals(firstBlockHashFromJsonRpc, firstBlockHashFromHttp); + } + + @Test(enabled = true, description = "Json rpc api of web3_clientVersion") + public void test34JsonRpcApiTestForWeb3ClientVersion() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("web3_clientVersion", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + List resultList = new ArrayList<>(); + for (String str : result.split("/")) { + resultList.add(str); + } + Assert.assertEquals(resultList.size(), 5); + Assert.assertEquals(resultList.get(0), "TRON"); + Assert.assertEquals(resultList.get(1).substring(0, 1), "v"); + Assert.assertEquals(resultList.get(2), "Linux"); + Assert.assertEquals(resultList.get(3), "Java1.8"); + Assert.assertEquals(resultList.get(4).substring(0, 11), "GreatVoyage"); + } + + @Test(enabled = true, description = "Json rpc api of web3_sha3") + public void test35JsonRpcApiTestForWeb3Sha3() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x08"); + JsonObject requestBody1 = getJsonRpcBody("web3_sha3", params); + response = getEthHttps(ethHttpsNode, requestBody1); + responseContent = HttpMethed.parseResponseContent(response); + String result1 = responseContent.getString("result"); + JsonObject requestBody2 = getJsonRpcBody("web3_sha3", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody2); + responseContent = HttpMethed.parseResponseContent(response); + String result2 = responseContent.getString("result"); + Assert.assertEquals(result1, result2); + } + + @Test(enabled = true, description = "Json rpc api of eth_compileLLL") + public void test36JsonRpcApiTestForEthCompileLll() throws Exception { + JsonArray params = new JsonArray(); + params.add("(returnlll (suicide (caller)))"); + JsonObject requestBody1 = getJsonRpcBody("eth_compileLLL", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals(errorMessage, "the method eth_compileLLL does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_compileSerpent") + public void test37JsonRpcApiTestForEthCompileSerpent() throws Exception { + JsonArray params = new JsonArray(); + params.add("/* some serpent */"); + JsonObject requestBody = getJsonRpcBody("eth_compileSerpent", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_compileSerpent does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_compileSolidity") + public void test38JsonRpcApiTestForEthCompileSolidity() throws Exception { + JsonArray params = new JsonArray(); + params.add("contract test { function multiply(uint a) returns(uint d) { return a * 7; } }"); + JsonObject requestBody = getJsonRpcBody("eth_compileSolidity", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_compileSolidity does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_getCompilers") + public void test39JsonRpcApiTestForEthCompileSolidity() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_getCompilers", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_getCompilers does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_getTransactionCount") + public void test40JsonRpcApiTestForEthGetTransactionCount() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x407d73d8a49eeb85d32cf465507dd71d507100c1"); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionCount", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_getTransactionCount does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_sendRawTransaction") + public void test41JsonRpcApiTestForEthSendRawTransaction() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x234"); + JsonObject requestBody = getJsonRpcBody("eth_sendRawTransaction", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_sendRawTransaction does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_sendTransaction") + public void test42JsonRpcApiTestForEthSendTransaction() throws Exception { + JsonArray params = new JsonArray(); + JsonObject temp = new JsonObject(); + params.add(temp); + temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); + temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); + temp.addProperty("gas", "0x76c0"); + temp.addProperty("gasPrice", "0x9184e72a000"); + temp.addProperty( + "data", + "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); + temp.addProperty("value", "0x9184e72a"); + + JsonObject requestBody = getJsonRpcBody("eth_sendTransaction", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_sendTransaction does not exist/is not available"); } - Assert.assertEquals(temp, expect); - } - - @Test(enabled = true, description = "Json rpc api of net_peerCount") - public void test32JsonRpcApiTestForNetPeerCount() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_peerCount", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNotNull(result); - } - - @Test(enabled = true, description = "Json rpc api of net_version") - public void test33JsonRpcApiTestForEthVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_version", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String firstBlockHashFromJsonRpc = responseContent.getString("result").substring(2); - response = HttpMethed.getBlockByNumFromSolidity(solidityNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - String firstBlockHashFromHttp = responseContent.getString("blockID").substring(56); - logger.info("firstBlockHashFromJsonRpc" + firstBlockHashFromJsonRpc); - logger.info("firstBlockHashFromHttp" + firstBlockHashFromHttp); - Assert.assertEquals(firstBlockHashFromJsonRpc, firstBlockHashFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of web3_clientVersion") - public void test34JsonRpcApiTestForWeb3ClientVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("web3_clientVersion", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - List resultList = new ArrayList<>(); - for (String str : result.split("/")) { - resultList.add(str); + + @Test(enabled = true, description = "Json rpc api of eth_sign") + public void test43JsonRpcApiTestForEthSign() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); + params.add("0xdeadbeaf"); + JsonObject requestBody = getJsonRpcBody("eth_sign", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals(errorMessage, "the method eth_sign does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_signTransaction") + public void test44JsonRpcApiTestForEthSignTransaction() throws Exception { + JsonArray params = new JsonArray(); + JsonObject temp = new JsonObject(); + params.add(temp); + temp.addProperty( + "data", + "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); + temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); + temp.addProperty("gas", "0x76c0"); + temp.addProperty("gasPrice", "0x9184e72a000"); + temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); + temp.addProperty("value", "0x9184e72a"); + + JsonObject requestBody = getJsonRpcBody("eth_signTransaction", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_signTransaction does not exist/is not available"); } - Assert.assertEquals(resultList.size(), 5); - Assert.assertEquals(resultList.get(0), "TRON"); - Assert.assertEquals(resultList.get(1).substring(0, 1), "v"); - Assert.assertEquals(resultList.get(2), "Linux"); - Assert.assertEquals(resultList.get(3), "Java1.8"); - Assert.assertEquals(resultList.get(4).substring(0, 11), "GreatVoyage"); - } - - @Test(enabled = true, description = "Json rpc api of web3_sha3") - public void test35JsonRpcApiTestForWeb3Sha3() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x08"); - JsonObject requestBody1 = getJsonRpcBody("web3_sha3", params); - response = getEthHttps(ethHttpsNode, requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - String result1 = responseContent.getString("result"); - JsonObject requestBody2 = getJsonRpcBody("web3_sha3", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody2); - responseContent = HttpMethed.parseResponseContent(response); - String result2 = responseContent.getString("result"); - Assert.assertEquals(result1, result2); - } - - @Test(enabled = true, description = "Json rpc api of eth_compileLLL") - public void test36JsonRpcApiTestForEthCompileLll() throws Exception { - JsonArray params = new JsonArray(); - params.add("(returnlll (suicide (caller)))"); - JsonObject requestBody1 = getJsonRpcBody("eth_compileLLL", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_compileLLL does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_compileSerpent") - public void test37JsonRpcApiTestForEthCompileSerpent() throws Exception { - JsonArray params = new JsonArray(); - params.add("/* some serpent */"); - JsonObject requestBody = getJsonRpcBody("eth_compileSerpent", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_compileSerpent does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_compileSolidity") - public void test38JsonRpcApiTestForEthCompileSolidity() throws Exception { - JsonArray params = new JsonArray(); - params.add("contract test { function multiply(uint a) returns(uint d) { return a * 7; } }"); - JsonObject requestBody = getJsonRpcBody("eth_compileSolidity", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_compileSolidity does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getCompilers") - public void test39JsonRpcApiTestForEthCompileSolidity() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_getCompilers", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_getCompilers does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionCount") - public void test40JsonRpcApiTestForEthGetTransactionCount() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x407d73d8a49eeb85d32cf465507dd71d507100c1"); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionCount", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_getTransactionCount does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sendRawTransaction") - public void test41JsonRpcApiTestForEthSendRawTransaction() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x234"); - JsonObject requestBody = getJsonRpcBody("eth_sendRawTransaction", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_sendRawTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sendTransaction") - public void test42JsonRpcApiTestForEthSendTransaction() throws Exception { - JsonArray params = new JsonArray(); - JsonObject temp = new JsonObject(); - params.add(temp); - temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); - temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); - temp.addProperty("gas", "0x76c0"); - temp.addProperty("gasPrice", "0x9184e72a000"); - temp.addProperty( - "data", - "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); - temp.addProperty("value", "0x9184e72a"); - - JsonObject requestBody = getJsonRpcBody("eth_sendTransaction", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_sendTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sign") - public void test43JsonRpcApiTestForEthSign() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); - params.add("0xdeadbeaf"); - JsonObject requestBody = getJsonRpcBody("eth_sign", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_sign does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_signTransaction") - public void test44JsonRpcApiTestForEthSignTransaction() throws Exception { - JsonArray params = new JsonArray(); - JsonObject temp = new JsonObject(); - params.add(temp); - temp.addProperty( - "data", - "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); - temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); - temp.addProperty("gas", "0x76c0"); - temp.addProperty("gasPrice", "0x9184e72a000"); - temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); - temp.addProperty("value", "0x9184e72a"); - - JsonObject requestBody = getJsonRpcBody("eth_signTransaction", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_signTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_submitWork") - public void test45JsonRpcApiTestForEthSubmitWork() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000000001"); - params.add("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"); - params.add("0xD1GE5700000000000000000000000000D1GE5700000000000000000000000000"); - JsonObject requestBody = getJsonRpcBody("eth_submitWork", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_submitWork does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of parity_nextNonce") - public void test46JsonRpcApiTestForParityNextNonce() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); - JsonObject requestBody = getJsonRpcBody("parity_nextNonce", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method parity_nextNonce does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_submitHashrate") - public void test47JsonRpcApiTestForEthSubmitHashrate() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000000000000000000000000000000000000000000000000000500000"); - params.add("0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c"); - JsonObject requestBody = getJsonRpcBody("eth_submitHashrate", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_submitHashrate does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockByHash params is false") - public void test48JsonRpcApiTestForEthGetBlockByHash() throws Exception { - response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("45getBlockByNumFromSolidityFromHttp:" + responseContent); - accountStateRoot = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("accountStateRoot"); - JsonArray params = new JsonArray(); - params.add(blockHash); - params.add(false); - JsonObject requestBody = getJsonRpcBody("eth_getBlockByHash", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject getBlockByHashResult = responseContent.getJSONObject("result"); - - Assert.assertNull(getBlockByHashResult.getString("nonce")); - Assert.assertNull(getBlockByHashResult.getString("sha3Uncles")); - Assert.assertNull(getBlockByHashResult.getString("receiptsRoot")); - Assert.assertNull(getBlockByHashResult.getString("difficulty")); - Assert.assertNull(getBlockByHashResult.getString("totalDifficulty")); - Assert.assertNull(getBlockByHashResult.getString("extraData")); - Assert.assertNull(getBlockByHashResult.getString("baseFeePerGas")); - Assert.assertNull(getBlockByHashResult.getString("mixHash")); - Assert.assertEquals(getBlockByHashResult.getString("uncles"), new ArrayList<>().toString()); - Assert.assertEquals(getBlockByHashResult.getString("stateRoot"), "0x" + accountStateRoot); - - Assert.assertEquals( - getBlockByHashResult.getString("logsBloom"), - "0x00000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000"); - Assert.assertEquals(getBlockByHashResult.getString("number"), blockNumHex); - Assert.assertEquals(getBlockByHashResult.getString("hash"), "0x" + bid); - Assert.assertEquals(getBlockByHashResult.getString("parentHash"), "0x" + parentHash); - Assert.assertEquals(getBlockByHashResult.getString("transactionsRoot"), "0x" + txTrieRoot); - Assert.assertEquals( - getBlockByHashResult.getString("miner"), "0x" + witnessAddress.substring(2)); - Assert.assertEquals(getBlockByHashResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); - Assert.assertEquals( - String.valueOf(Long.parseLong(getBlockByHashResult.getString("gasLimit").substring(2), 16)), - feeLimit); - Assert.assertEquals( - Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16), - blockTimeStamp); - final GrpcAPI.NumberMessage message = - GrpcAPI.NumberMessage.newBuilder().setNum(blockNum).build(); - HttpMethed.waitToProduceOneBlock(httpFullNode); - Block block = blockingStubFull.getBlockByNum(message); - logger.info("sizeFromJrpc:" + block.getSerializedSize()); - logger.info( - "sizeFromJsonRPc:" - + Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16)); - size = block.getSerializedSize(); - Assert.assertEquals( - Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16), - block.getSerializedSize()); - - Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16); - JSONArray transactionId = getBlockByHashResult.getJSONArray("transactions"); - List transactionIdListFromGetBlockByHash = new ArrayList<>(); - if (transactionId.size() > 0) { - for (int i = 0; i < transactionId.size(); i++) { - transactionIdListFromGetBlockByHash.add(transactionId.get(i).toString()); - } + + @Test(enabled = true, description = "Json rpc api of eth_submitWork") + public void test45JsonRpcApiTestForEthSubmitWork() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x0000000000000001"); + params.add("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"); + params.add("0xD1GE5700000000000000000000000000D1GE5700000000000000000000000000"); + JsonObject requestBody = getJsonRpcBody("eth_submitWork", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals(errorMessage, "the method eth_submitWork does not exist/is not available"); } - Assert.assertEquals(transactionIdListFromGetBlockByHash, transactionIdList); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getBlockByNumFromSolidityber params is true") - public void test49JsonRpcApiTestForEthgetBlockByNumFromSolidityber() throws Exception { - - JsonArray params = new JsonArray(); - params.add(blockNumHex); - logger.info("46blockNumHex:" + blockNumHex); - params.add(true); - JsonObject requestBody = getJsonRpcBody("eth_getBlockByNumber", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - JSONObject getBlockByNumFromSolidityberResult = responseContent.getJSONObject("result"); - logger.info("getBlockByHashResult:" + getBlockByNumFromSolidityberResult); - - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("nonce")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("sha3Uncles")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("receiptsRoot")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("difficulty")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("totalDifficulty")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("extraData")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("baseFeePerGas")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("mixHash")); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("uncles"), new ArrayList<>().toString()); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("stateRoot"), "0x" + accountStateRoot); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("logsBloom"), - "0x00000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000"); - Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("number"), blockNumHex); - Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("hash"), "0x" + bid); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("parentHash"), "0x" + parentHash); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("transactionsRoot"), "0x" + txTrieRoot); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("miner"), "0x" + witnessAddress.substring(2)); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); - Assert.assertEquals( - String.valueOf( - Long.parseLong( - getBlockByNumFromSolidityberResult.getString("gasLimit").substring(2), 16)), - feeLimit); - Assert.assertEquals( - Long.parseLong(getBlockByNumFromSolidityberResult.getString("timestamp").substring(2), 16), - blockTimeStamp); - logger.info("size:" + size); - Assert.assertEquals( - Long.parseLong(getBlockByNumFromSolidityberResult.getString("size").substring(2), 16), - size); - - JSONArray transactionsList = getBlockByNumFromSolidityberResult.getJSONArray("transactions"); - logger.info("transactionsList:" + transactionsList); - List transactionInfoListFromGetBlockByHash = new ArrayList<>(); - if (transactionsList.size() > 0) { - for (int i = 0; i < transactionsList.size(); i++) { - transactionInfoListFromGetBlockByHash.add(transactionsList.get(i).toString()); - } + + @Test(enabled = true, description = "Json rpc api of parity_nextNonce") + public void test46JsonRpcApiTestForParityNextNonce() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); + JsonObject requestBody = getJsonRpcBody("parity_nextNonce", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method parity_nextNonce does not exist/is not available"); } - List transactionInfoListFromTransactionByBlockNumberAndIndex = new ArrayList<>(); - for (int i = 0; i < transactionsList.size(); i++) { - JsonArray paramsForEthGetTransactionByBlockNumberAndIndex = new JsonArray(); - paramsForEthGetTransactionByBlockNumberAndIndex.add(blockNumHex); - String index = "0x" + Integer.toHexString(i); - logger.info("index:" + index); - paramsForEthGetTransactionByBlockNumberAndIndex.add(index); - logger.info( - "paramsForEthGetTransactionByBlockNumberAndIndex:" - + paramsForEthGetTransactionByBlockNumberAndIndex); - JsonObject requestBodyForTransactionByBlockNumberAndIndex = - getJsonRpcBody( - "eth_getTransactionByBlockNumberAndIndex", - paramsForEthGetTransactionByBlockNumberAndIndex); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForTransactionByBlockNumberAndIndex); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - result = responseContent.getJSONObject("result"); - logger.info("result:" + result); - transactionInfoListFromTransactionByBlockNumberAndIndex.add(result.toString()); + + @Test(enabled = true, description = "Json rpc api of eth_submitHashrate") + public void test47JsonRpcApiTestForEthSubmitHashrate() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x0000000000000000000000000000000000000000000000000000000000500000"); + params.add("0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c"); + JsonObject requestBody = getJsonRpcBody("eth_submitHashrate", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_submitHashrate does not exist/is not available"); } - Assert.assertEquals( - transactionInfoListFromGetBlockByHash, - transactionInfoListFromTransactionByBlockNumberAndIndex); - } - - /** constructor. */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); + + @Test(enabled = true, description = "Json rpc api of eth_getBlockByHash params is false") + public void test48JsonRpcApiTestForEthGetBlockByHash() throws Exception { + response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNum); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("45getBlockByNumFromSolidityFromHttp:" + responseContent); + accountStateRoot = + responseContent + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getString("accountStateRoot"); + JsonArray params = new JsonArray(); + params.add(blockHash); + params.add(false); + JsonObject requestBody = getJsonRpcBody("eth_getBlockByHash", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject getBlockByHashResult = responseContent.getJSONObject("result"); + + Assert.assertNull(getBlockByHashResult.getString("nonce")); + Assert.assertNull(getBlockByHashResult.getString("sha3Uncles")); + Assert.assertNull(getBlockByHashResult.getString("receiptsRoot")); + Assert.assertNull(getBlockByHashResult.getString("difficulty")); + Assert.assertNull(getBlockByHashResult.getString("totalDifficulty")); + Assert.assertNull(getBlockByHashResult.getString("extraData")); + Assert.assertNull(getBlockByHashResult.getString("baseFeePerGas")); + Assert.assertNull(getBlockByHashResult.getString("mixHash")); + Assert.assertEquals(getBlockByHashResult.getString("uncles"), new ArrayList<>().toString()); + Assert.assertEquals(getBlockByHashResult.getString("stateRoot"), "0x" + accountStateRoot); + + Assert.assertEquals( + getBlockByHashResult.getString("logsBloom"), + "0x00000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000000000000000000000000" + + "000000000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000"); + Assert.assertEquals(getBlockByHashResult.getString("number"), blockNumHex); + Assert.assertEquals(getBlockByHashResult.getString("hash"), "0x" + bid); + Assert.assertEquals(getBlockByHashResult.getString("parentHash"), "0x" + parentHash); + Assert.assertEquals(getBlockByHashResult.getString("transactionsRoot"), "0x" + txTrieRoot); + Assert.assertEquals( + getBlockByHashResult.getString("miner"), "0x" + witnessAddress.substring(2)); + Assert.assertEquals(getBlockByHashResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); + Assert.assertEquals( + String.valueOf(Long.parseLong(getBlockByHashResult.getString("gasLimit").substring(2), 16)), + feeLimit); + Assert.assertEquals( + Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16), + blockTimeStamp); + final GrpcAPI.NumberMessage message = + GrpcAPI.NumberMessage.newBuilder().setNum(blockNum).build(); + HttpMethed.waitToProduceOneBlock(httpFullNode); + Block block = blockingStubFull.getBlockByNum(message); + logger.info("sizeFromJrpc:" + block.getSerializedSize()); + logger.info( + "sizeFromJsonRPc:" + + Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16)); + size = block.getSerializedSize(); + Assert.assertEquals( + Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16), + block.getSerializedSize()); + + Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16); + JSONArray transactionId = getBlockByHashResult.getJSONArray("transactions"); + List transactionIdListFromGetBlockByHash = new ArrayList<>(); + if (transactionId.size() > 0) { + for (int i = 0; i < transactionId.size(); i++) { + transactionIdListFromGetBlockByHash.add(transactionId.get(i).toString()); + } + } + Assert.assertEquals(transactionIdListFromGetBlockByHash, transactionIdList); + } + + @Test( + enabled = true, + description = "Json rpc api of eth_getBlockByNumFromSolidityber params is true") + public void test49JsonRpcApiTestForEthgetBlockByNumFromSolidityber() throws Exception { + + JsonArray params = new JsonArray(); + params.add(blockNumHex); + logger.info("46blockNumHex:" + blockNumHex); + params.add(true); + JsonObject requestBody = getJsonRpcBody("eth_getBlockByNumber", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + JSONObject getBlockByNumFromSolidityberResult = responseContent.getJSONObject("result"); + logger.info("getBlockByHashResult:" + getBlockByNumFromSolidityberResult); + + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("nonce")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("sha3Uncles")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("receiptsRoot")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("difficulty")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("totalDifficulty")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("extraData")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("baseFeePerGas")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("mixHash")); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("uncles"), new ArrayList<>().toString()); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("stateRoot"), "0x" + accountStateRoot); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("logsBloom"), + "0x00000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000000000000000" + + "000000000000000000000000000000000000000000000000000000000000000000000000" + + "000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000"); + Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("number"), blockNumHex); + Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("hash"), "0x" + bid); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("parentHash"), "0x" + parentHash); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("transactionsRoot"), "0x" + txTrieRoot); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("miner"), "0x" + witnessAddress.substring(2)); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); + Assert.assertEquals( + String.valueOf( + Long.parseLong( + getBlockByNumFromSolidityberResult.getString("gasLimit").substring(2), 16)), + feeLimit); + Assert.assertEquals( + Long.parseLong(getBlockByNumFromSolidityberResult.getString("timestamp").substring(2), 16), + blockTimeStamp); + logger.info("size:" + size); + Assert.assertEquals( + Long.parseLong(getBlockByNumFromSolidityberResult.getString("size").substring(2), 16), + size); + + JSONArray transactionsList = getBlockByNumFromSolidityberResult.getJSONArray("transactions"); + logger.info("transactionsList:" + transactionsList); + List transactionInfoListFromGetBlockByHash = new ArrayList<>(); + if (transactionsList.size() > 0) { + for (int i = 0; i < transactionsList.size(); i++) { + transactionInfoListFromGetBlockByHash.add(transactionsList.get(i).toString()); + } + } + List transactionInfoListFromTransactionByBlockNumberAndIndex = new ArrayList<>(); + for (int i = 0; i < transactionsList.size(); i++) { + JsonArray paramsForEthGetTransactionByBlockNumberAndIndex = new JsonArray(); + paramsForEthGetTransactionByBlockNumberAndIndex.add(blockNumHex); + String index = "0x" + Integer.toHexString(i); + logger.info("index:" + index); + paramsForEthGetTransactionByBlockNumberAndIndex.add(index); + logger.info( + "paramsForEthGetTransactionByBlockNumberAndIndex:" + + paramsForEthGetTransactionByBlockNumberAndIndex); + JsonObject requestBodyForTransactionByBlockNumberAndIndex = + getJsonRpcBody( + "eth_getTransactionByBlockNumberAndIndex", + paramsForEthGetTransactionByBlockNumberAndIndex); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForTransactionByBlockNumberAndIndex); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + result = responseContent.getJSONObject("result"); + logger.info("result:" + result); + transactionInfoListFromTransactionByBlockNumberAndIndex.add(result.toString()); + } + Assert.assertEquals( + transactionInfoListFromGetBlockByHash, + transactionInfoListFromTransactionByBlockNumberAndIndex); + } + + /** + * constructor. + */ + @AfterClass + public void shutdown() throws InterruptedException { + if (channelFull != null) { + channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); + } } - } } diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java index 8cfa74de312..ef2487c2cf1 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java @@ -67,7 +67,7 @@ public void test02GetNewFilterContainAddress() { enabled = true, description = "Eth api of eth_newFilter contains topic fromBlock and toBlock.") public void test03GetNewFilterContainTopic() { - response = HttpMethed.getBlockByNumFromSolidity(solidityNode, blockNumForTrc20); + response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNumForTrc20); responseContent = HttpMethed.parseResponseContent(response); logger.info("responseContent:" + responseContent); logger.info("blockHash:" + responseContent.getString("blockID")); @@ -131,7 +131,7 @@ public void test05GetNewFilterOnlyContainTopic() throws InterruptedException { @Test(enabled = true, description = "Eth api of eth_newFilter which only contains blockHash.") public void test06GetNewFilterHasOnlyBlockHash() throws InterruptedException { - response = HttpMethed.getNowBlockFromSolidity(solidityNode); + response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); responseContent = HttpMethed.parseResponseContent(response); String blockHash = responseContent.getString("blockID"); Thread.sleep(30000); @@ -212,7 +212,7 @@ public void test10GetLogsOnlyContainAddress() { paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 20))); JsonArray params = new JsonArray(); params.add(paramBody); - HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode,solidityNode); + HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode,httpsolidityNode); JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); @@ -235,7 +235,7 @@ public void test11GetLogsContainsTopicAndAddress() { paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 10))); JsonArray params = new JsonArray(); params.add(paramBody); - HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode,solidityNode); + HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode,httpsolidityNode); JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); From 1a486e614f57062281cb87bd9d9bd739324ead62 Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Tue, 14 Dec 2021 15:35:56 +0800 Subject: [PATCH 20/24] fix --- .../dailybuild/jsonrpc/Accounts002.java | 3 +- .../dailybuild/jsonrpc/Accounts004.java | 666 +++++++++--------- 2 files changed, 335 insertions(+), 334 deletions(-) diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java index 11cec94ffb3..c7b146a3b31 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java @@ -678,7 +678,8 @@ public void test21JsonRpcApiTestForEthGetTransactionReceipt() throws Exception { resultFromTransactionReceipt.getString("transactionHash")); Assert.assertEquals( logs.getJSONObject(0).getString("address"), resultFromTransactionReceipt.getString("to")); - response = HttpMethed.getTransactionInfoByBlocknumFromSolidity(httpsolidityNode, blockNumForTrc20); + response = + HttpMethed.getTransactionInfoByBlocknumFromSolidity(httpsolidityNode, blockNumForTrc20); List responseContent1 = HttpMethed.parseResponseContentArray(response); logger.info("responseContent1:" + responseContent1); diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java index ef2487c2cf1..e5d5b4c22fa 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java @@ -12,363 +12,363 @@ @Slf4j public class Accounts004 extends JsonRpcBase { - JSONObject responseContent; - HttpResponse response; - String topic0 = null; - String topic1 = null; - String fromBlock = null; - String toBlock = null; - String newFilterResultIdfrom01 = null; - String newFilterResultIdfrom02 = null; - String blockHash = null; + JSONObject responseContent; + HttpResponse response; + String topic0 = null; + String topic1 = null; + String fromBlock = null; + String toBlock = null; + String newFilterResultIdfrom01 = null; + String newFilterResultIdfrom02 = null; + String blockHash = null; - @Test(enabled = true, description = "Eth api of eth_newFilter contains nothing.") - public void test01GetNewFilterContainNothing() { - JsonObject paramBody = new JsonObject(); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test01GetNewFilterContainNothing_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test01GetNewFilterContainNothing_responseContent" + responseContent); - logger.info("result:" + responseContent.getString("result")); - Assert.assertNotNull(responseContent.getString("result")); - } + @Test(enabled = true, description = "Eth api of eth_newFilter contains nothing.") + public void test01GetNewFilterContainNothing() { + JsonObject paramBody = new JsonObject(); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test01GetNewFilterContainNothing_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test01GetNewFilterContainNothing_responseContent" + responseContent); + logger.info("result:" + responseContent.getString("result")); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test( - enabled = true, - description = "Eth api of eth_newFilter contains address,fromBlock and toBlock.") - public void test02GetNewFilterContainAddress() { - if (blockNumForTrc20 - 10 < 0) { - fromBlock = "0"; - } else { - fromBlock = "0x" + Integer.toHexString(blockNumForTrc20 - 10); + @Test( + enabled = true, + description = "Eth api of eth_newFilter contains address,fromBlock and toBlock.") + public void test02GetNewFilterContainAddress() { + if (blockNumForTrc20 - 10 < 0) { + fromBlock = "0"; + } else { + fromBlock = "0x" + Integer.toHexString(blockNumForTrc20 - 10); + } + toBlock = "0x" + Integer.toHexString(blockNumForTrc20 + 10); + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test02GetNewFilterContainAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test02GetNewFilterContainAddress_responseContent" + responseContent); + newFilterResultIdfrom01 = responseContent.getString("result"); + logger.info("test02GetNewFilterContainAddress_id:" + responseContent.getString("result")); } - toBlock = "0x" + Integer.toHexString(blockNumForTrc20 + 10); - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test02GetNewFilterContainAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test02GetNewFilterContainAddress_responseContent" + responseContent); - newFilterResultIdfrom01 = responseContent.getString("result"); - logger.info("test02GetNewFilterContainAddress_id:" + responseContent.getString("result")); - } - @Test( - enabled = true, - description = "Eth api of eth_newFilter contains topic fromBlock and toBlock.") - public void test03GetNewFilterContainTopic() { - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - logger.info("blockHash:" + responseContent.getString("blockID")); - blockHash = responseContent.getString("blockID"); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - JsonObject paramBody = new JsonObject(); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test03GetNewFilterContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test03GetNewFilterContainTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - newFilterResultIdfrom02 = responseContent.getString("result"); - logger.info("test03GetNewFilterContainTopic_id:" + newFilterResultIdfrom02); - } + @Test( + enabled = true, + description = "Eth api of eth_newFilter contains topic fromBlock and toBlock.") + public void test03GetNewFilterContainTopic() { + response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNumForTrc20); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + logger.info("blockHash:" + responseContent.getString("blockID")); + blockHash = responseContent.getString("blockID"); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + JsonObject paramBody = new JsonObject(); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test03GetNewFilterContainTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test03GetNewFilterContainTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + newFilterResultIdfrom02 = responseContent.getString("result"); + logger.info("test03GetNewFilterContainTopic_id:" + newFilterResultIdfrom02); + } - @Test(enabled = true, description = "Eth api of eth_newFilter contains topic and address.") - public void test04GetNewFilterContainsTopicAndAddress() { + @Test(enabled = true, description = "Eth api of eth_newFilter contains topic and address.") + public void test04GetNewFilterContainsTopicAndAddress() { - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test04GetNewFilterContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test04GetNewFilterContainsTopicAndAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test04GetNewFilterContainsTopicAndAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test04GetNewFilterContainsTopicAndAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_newFilter only contain topic and blockHash.") - public void test05GetNewFilterOnlyContainTopic() throws InterruptedException { - JsonObject paramBody = new JsonObject(); - paramBody.addProperty("blockHash", blockHash); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - paramBody.add("topics", topicArray); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test05GetNewFilterOnlyContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test05GetNewFilterOnlyContainTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + @Test(enabled = true, description = "Eth api of eth_newFilter only contain topic and blockHash.") + public void test05GetNewFilterOnlyContainTopic() throws InterruptedException { + JsonObject paramBody = new JsonObject(); + paramBody.addProperty("blockHash", blockHash); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + paramBody.add("topics", topicArray); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test05GetNewFilterOnlyContainTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test05GetNewFilterOnlyContainTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_newFilter which only contains blockHash.") - public void test06GetNewFilterHasOnlyBlockHash() throws InterruptedException { - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - String blockHash = responseContent.getString("blockID"); - Thread.sleep(30000); - JsonObject paramBody = new JsonObject(); - paramBody.addProperty("blockHash", blockHash); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test06GetNewFilterHasOnlyBlockHash_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test06GetNewFilterHasOnlyBlockHash_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + @Test(enabled = true, description = "Eth api of eth_newFilter which only contains blockHash.") + public void test06GetNewFilterHasOnlyBlockHash() throws InterruptedException { + response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + String blockHash = responseContent.getString("blockID"); + Thread.sleep(30000); + JsonObject paramBody = new JsonObject(); + paramBody.addProperty("blockHash", blockHash); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test06GetNewFilterHasOnlyBlockHash_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test06GetNewFilterHasOnlyBlockHash_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_newFilter check new and after block.") - public void test07GetNewFilterCheckNewBlock() { - JsonObject paramBody = new JsonObject(); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - paramBody.add("topics", topicArray); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test07GetNewFilterCheckNewBlock_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test07GetNewFilterCheckNewBlock_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + @Test(enabled = true, description = "Eth api of eth_newFilter check new and after block.") + public void test07GetNewFilterCheckNewBlock() { + JsonObject paramBody = new JsonObject(); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + paramBody.add("topics", topicArray); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test07GetNewFilterCheckNewBlock_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test07GetNewFilterCheckNewBlock_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_newBlockFilter") - public void test08GetEthNewBlockFilter() { + @Test(enabled = true, description = "Eth api of eth_newBlockFilter") + public void test08GetEthNewBlockFilter() { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test08GetEthNewBlockFilter_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test08GetEthNewBlockFilter_responseContent:" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test08GetEthNewBlockFilter_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test08GetEthNewBlockFilter_responseContent:" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_getFilterChanges has less 20 elements.") - public void test09GetFilterChanges() { + @Test(enabled = true, description = "Eth api of eth_getFilterChanges has less 20 elements.") + public void test09GetFilterChanges() { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); - String ethNewBlockFilterResult = responseContent.get("result").toString(); - logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); - String newFilterId = responseContent.getString("result"); - logger.info("newFilterId:" + newFilterId); - params = new JsonArray(); - params.add(newFilterId); - requestBody = getJsonRpcBody("eth_getFilterChanges", params); - logger.info("test09GetFilterChanges_requestBody: " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test09GetFilterChanges_responseContent:" + responseContent); - Assert.assertEquals("[]", responseContent.getString("result")); - } + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); + String ethNewBlockFilterResult = responseContent.get("result").toString(); + logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); + String newFilterId = responseContent.getString("result"); + logger.info("newFilterId:" + newFilterId); + params = new JsonArray(); + params.add(newFilterId); + requestBody = getJsonRpcBody("eth_getFilterChanges", params); + logger.info("test09GetFilterChanges_requestBody: " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test09GetFilterChanges_responseContent:" + responseContent); + Assert.assertEquals("[]", responseContent.getString("result")); + } - @Test( - enabled = true, - description = "Eth api of eth_getLogs contains address ,fromBlock and toBlock.") - public void test10GetLogsOnlyContainAddress() { - JsonArray addressArray = new JsonArray(); - logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); - addressArray.add(contractTrc20AddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - logger.info("blockNumForTrc20:" + blockNumForTrc20); - paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 20))); - paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 20))); - JsonArray params = new JsonArray(); - params.add(paramBody); - HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode,httpsolidityNode); - JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); - logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test10GetLogsOnlyContainAddress_responseContent:" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - String address = - responseContent.getJSONArray("result").getJSONObject(0).getString("address").substring(2); - Assert.assertEquals(address, contractTrc20AddressFrom58.substring(2)); - topic0 = responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); - } + @Test( + enabled = true, + description = "Eth api of eth_getLogs contains address ,fromBlock and toBlock.") + public void test10GetLogsOnlyContainAddress() { + JsonArray addressArray = new JsonArray(); + logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); + addressArray.add(contractTrc20AddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + logger.info("blockNumForTrc20:" + blockNumForTrc20); + paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 20))); + paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 20))); + JsonArray params = new JsonArray(); + params.add(paramBody); + HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode, httpsolidityNode); + JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); + logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test10GetLogsOnlyContainAddress_responseContent:" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + String address = + responseContent.getJSONArray("result").getJSONObject(0).getString("address").substring(2); + Assert.assertEquals(address, contractTrc20AddressFrom58.substring(2)); + topic0 = responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); + } - @Test(enabled = true, description = "Eth api of eth_getLogs both contains topic and address.") - public void test11GetLogsContainsTopicAndAddress() { - JsonArray topicArray = new JsonArray(); - topicArray.add(topic0); - JsonObject paramBody = new JsonObject(); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 10))); - paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 10))); - JsonArray params = new JsonArray(); - params.add(paramBody); - HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode,httpsolidityNode); - JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); - logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test11GetLogsContainsTopicAndAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - String topicFromResult = - responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); - Assert.assertEquals(topicFromResult, topic0); - } + @Test(enabled = true, description = "Eth api of eth_getLogs both contains topic and address.") + public void test11GetLogsContainsTopicAndAddress() { + JsonArray topicArray = new JsonArray(); + topicArray.add(topic0); + JsonObject paramBody = new JsonObject(); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 10))); + paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 10))); + JsonArray params = new JsonArray(); + params.add(paramBody); + HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode, httpsolidityNode); + JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); + logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test11GetLogsContainsTopicAndAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + String topicFromResult = + responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); + Assert.assertEquals(topicFromResult, topic0); + } - @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") - public void test12GetFilterLogsContainsAddress() { + @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") + public void test12GetFilterLogsContainsAddress() { - JsonArray params = new JsonArray(); - params.add(newFilterResultIdfrom01); - JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); - logger.info("test12GetFilterLogsContainsAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test12GetFilterLogsContainsAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + JsonArray params = new JsonArray(); + params.add(newFilterResultIdfrom01); + JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); + logger.info("test12GetFilterLogsContainsAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test12GetFilterLogsContainsAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") - public void test13GetFilterLogsContainsTopic() { + @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") + public void test13GetFilterLogsContainsTopic() { - JsonArray params = new JsonArray(); - params.add(newFilterResultIdfrom02); - JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); - logger.info("test13GetFilterLogsContainsTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test13GetFilterLogsContainsTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + JsonArray params = new JsonArray(); + params.add(newFilterResultIdfrom02); + JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); + logger.info("test13GetFilterLogsContainsTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test13GetFilterLogsContainsTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test( - enabled = true, - description = - "Eth api of eth_uninstallFilter which method is eth_newFilter" - + " and params has one element ") - public void test14EthUninstallFilter() { - // create ID - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.addProperty("fromBlock", "0x1f8b6a7"); - paramBody.addProperty("toBlock", "0x1f8b6a7"); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test14_newfilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_newfilter_responseContentr" + responseContent); - String ethNewFilterResult = responseContent.get("result").toString(); - logger.info("EthNewFilterResult:" + ethNewFilterResult); - Assert.assertNotNull(responseContent.getString("result")); + @Test( + enabled = true, + description = + "Eth api of eth_uninstallFilter which method is eth_newFilter" + + " and params has one element ") + public void test14EthUninstallFilter() { + // create ID + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.addProperty("fromBlock", "0x1f8b6a7"); + paramBody.addProperty("toBlock", "0x1f8b6a7"); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test14_newfilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_newfilter_responseContentr" + responseContent); + String ethNewFilterResult = responseContent.get("result").toString(); + logger.info("EthNewFilterResult:" + ethNewFilterResult); + Assert.assertNotNull(responseContent.getString("result")); - // verify ID invalid + // verify ID invalid - // first time - params = new JsonArray(); - params.add(responseContent.get("result").toString()); - requestBody = getJsonRpcBody("eth_uninstallFilter", params); - logger.info("test14_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_eth_uninstallFilter_responseContentr_first" + responseContent); - Assert.assertEquals(responseContent.get("result"), true); - // second time - logger.info("test14_eth_uninstallFilter_second " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_eth_uninstallFilter_responseContentr_second " + responseContent); - Assert.assertEquals( - responseContent.getJSONObject("error").getString("message"), "filter not found"); + // first time + params = new JsonArray(); + params.add(responseContent.get("result").toString()); + requestBody = getJsonRpcBody("eth_uninstallFilter", params); + logger.info("test14_eth_uninstallFilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_eth_uninstallFilter_responseContentr_first" + responseContent); + Assert.assertEquals(responseContent.get("result"), true); + // second time + logger.info("test14_eth_uninstallFilter_second " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_eth_uninstallFilter_responseContentr_second " + responseContent); + Assert.assertEquals( + responseContent.getJSONObject("error").getString("message"), "filter not found"); - // query getFilterChanges to verify ID has invalid - params = new JsonArray(); - params.add(ethNewFilterResult); - requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14EthUninstallFilter_responseContent" + responseContent); - String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; - Assert.assertEquals(responseContent.get("error").toString(), expectResult); - } + // query getFilterChanges to verify ID has invalid + params = new JsonArray(); + params.add(ethNewFilterResult); + requestBody = getJsonRpcBody("getFilterChanges", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14EthUninstallFilter_responseContent" + responseContent); + String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; + Assert.assertEquals(responseContent.get("error").toString(), expectResult); + } - @Test( - enabled = true, - description = - "Eth api of eth_uninstallFilter which method is eth_newBlockFilter" - + " and params has one element ") - public void test15EthUninstallFilter() { - // create ID + @Test( + enabled = true, + description = + "Eth api of eth_uninstallFilter which method is eth_newBlockFilter" + + " and params has one element ") + public void test15EthUninstallFilter() { + // create ID - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); - String ethNewBlockFilterResult = responseContent.get("result").toString(); - logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); - Assert.assertNotNull(responseContent.getString("result")); + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); + String ethNewBlockFilterResult = responseContent.get("result").toString(); + logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); + Assert.assertNotNull(responseContent.getString("result")); - // verify ID invalid - // first time - params = new JsonArray(); - params.add(responseContent.get("result").toString()); - requestBody = getJsonRpcBody("eth_uninstallFilter", params); - logger.info("test15_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15_eth_uninstallFilter_responseContentr_first" + responseContent); - Assert.assertEquals(responseContent.get("result"), true); - // second time - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15_eth_uninstallFilter_responseContentr_second" + responseContent); - Assert.assertEquals( - responseContent.getJSONObject("error").getString("message"), "filter not found"); - // query getFilterChanges to verify ID has invalid - params = new JsonArray(); - params.add(ethNewBlockFilterResult); - requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_responseContent" + responseContent); - String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; - Assert.assertEquals(responseContent.get("error").toString(), expectResult); - } + // verify ID invalid + // first time + params = new JsonArray(); + params.add(responseContent.get("result").toString()); + requestBody = getJsonRpcBody("eth_uninstallFilter", params); + logger.info("test15_eth_uninstallFilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15_eth_uninstallFilter_responseContentr_first" + responseContent); + Assert.assertEquals(responseContent.get("result"), true); + // second time + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15_eth_uninstallFilter_responseContentr_second" + responseContent); + Assert.assertEquals( + responseContent.getJSONObject("error").getString("message"), "filter not found"); + // query getFilterChanges to verify ID has invalid + params = new JsonArray(); + params.add(ethNewBlockFilterResult); + requestBody = getJsonRpcBody("getFilterChanges", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_responseContent" + responseContent); + String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; + Assert.assertEquals(responseContent.get("error").toString(), expectResult); + } } From b0988ba57c04705fda212b16d6b03de09efaaa2b Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Tue, 14 Dec 2021 16:28:25 +0800 Subject: [PATCH 21/24] fix --- .../common/client/utils/HttpMethed.java | 10331 ++++++------ .../common/client/utils/PublicMethed.java | 13553 ++++++++-------- .../dailybuild/jsonrpc/Accounts002.java | 2394 ++- .../dailybuild/jsonrpc/Accounts004.java | 666 +- 4 files changed, 13481 insertions(+), 13463 deletions(-) diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java index ce84cc011b2..8ef8fecbd8e 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java @@ -37,5313 +37,5056 @@ @Slf4j public class HttpMethed { - static HttpClient httpClient; - static HttpPost httppost; - static HttpResponse response; - static Integer connectionTimeout = Configuration.getByPath("testng.conf") - .getInt("defaultParameter.httpConnectionTimeout"); - static Integer soTimeout = Configuration.getByPath("testng.conf") - .getInt("defaultParameter.httpSoTimeout"); - static String transactionString; - static String transactionSignString; - static JSONObject responseContent; - static JSONObject signResponseContent; - static JSONObject transactionApprovedListContent; - public static volatile Integer witnessNum; - - /** - * constructor. - */ - private static volatile String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list") - .get(1); - - /** - * constructor. - */ - public static Integer getWitnessNum() { - if (null == witnessNum) { - witnessNum = parseResponseContent(listwitnesses(httpnode)).getJSONArray("witnesses").size(); - } - - return witnessNum; - } - - static { - PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(); - pccm.setDefaultMaxPerRoute(80); - pccm.setMaxTotal(100); - - httpClient = new DefaultHttpClient(pccm); - } - - /** - * constructor. - */ - public static HttpResponse updateAccount(String httpNode, byte[] updateAccountAddress, - String accountName, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/updateaccount"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("account_name", str2hex(accountName)); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(updateAccountAddress)); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse setAccountId(String httpNode, byte[] setAccountIdAddress, - String accountId, Boolean visable, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/setaccountid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("account_id", accountId); - userBaseObj2.addProperty("owner_address", - Base58.encode58Check(PublicMethed.getFinalAddress(fromKey))); - userBaseObj2.addProperty("visible", visable); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse updateWitness(String httpNode, byte[] witnessAddress, String updateUrl, - String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/updatewitness"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("update_url", str2hex(updateUrl)); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(witnessAddress)); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse voteWitnessAccount(String httpNode, byte[] ownerAddress, - JsonArray voteArray, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/votewitnessaccount"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.add("votes", voteArray); - logger.info(userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse createAccount(String httpNode, byte[] ownerAddress, - byte[] accountAddress, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createaccount"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("account_address", ByteArray.toHexString(accountAddress)); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse createWitness(String httpNode, byte[] ownerAddress, String url) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createwitness"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("url", str2hex(url)); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - //transactionString = EntityUtils.toString(response.getEntity()); - //transactionSignString = gettransactionsign(httpNode,transactionString,fromKey); - //response = broadcastTransaction(httpNode,transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse withdrawBalance(String httpNode, byte[] witnessAddress) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/withdrawbalance"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(witnessAddress)); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - //transactionString = EntityUtils.toString(response.getEntity()); - //transactionSignString = gettransactionsign(httpNode,transactionString,fromKey); - //response = broadcastTransaction(httpNode,transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse sendCoin(String httpNode, byte[] fromAddress, byte[] toAddress, - Long amount, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(fromAddress)); - userBaseObj2.addProperty("amount", amount); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse sendCoin(String httpNode, byte[] fromAddress, byte[] toAddress, - Long amount, Integer permissionId, String[] managerKeys) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(fromAddress)); - userBaseObj2.addProperty("amount", amount); - userBaseObj2.addProperty("Permission_id", permissionId); - response = createConnect(requestUrl, userBaseObj2); - transactionSignString = EntityUtils.toString(response.getEntity()); - HttpResponse getSignWeightResponse; - HttpResponse getTransactionApprovedListResponse; - - for (String key : managerKeys) { - transactionSignString = gettransactionsign(httpNode, transactionSignString, key); - getSignWeightResponse = getSignWeight(httpNode, transactionSignString); - signResponseContent = parseResponseContent(getSignWeightResponse); - logger.info("-----------sign information-----------------"); - printJsonContent(signResponseContent); - getSignWeightResponse = getTransactionApprovedList(httpNode, transactionSignString); - signResponseContent = parseResponseContent(getSignWeightResponse); - logger.info("-----------get Transaction Approved List-----------------"); - printJsonContent(signResponseContent); - - - } - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static String sendCoin(String httpNode, byte[] fromAddress, byte[] toAddress, Long amount, - String notes, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(fromAddress)); - userBaseObj2.addProperty("amount", amount); - userBaseObj2.addProperty("extra_data", ByteArray.toHexString(notes.getBytes())); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseStringContent(transactionString); - return responseContent.getString("txID"); - } - - /** - * constructor. - */ - public static String sendCoinGetTxid(String httpNode, byte[] fromAddress, byte[] toAddress, - Long amount, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(fromAddress)); - userBaseObj2.addProperty("amount", amount); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseStringContent(transactionString); - logger.info(responseContent.getString("txID")); - return responseContent.getString("txID"); - } - - /** - * constructor. - */ - public static HttpResponse createProposal(String httpNode, byte[] ownerAddress, Long proposalKey, - Long proposalValue, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/proposalcreate"; - JsonObject userBaseObj2 = new JsonObject(); - JsonObject proposalMap = new JsonObject(); - proposalMap.addProperty("key", proposalKey); - proposalMap.addProperty("value", proposalValue); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.add("parameters", proposalMap); - - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse approvalProposal(String httpNode, byte[] ownerAddress, - Integer proposalId, Boolean isAddApproval, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/proposalapprove"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("proposal_id", proposalId); - userBaseObj2.addProperty("is_add_approval", isAddApproval); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse deleteProposal(String httpNode, byte[] ownerAddress, - Integer proposalId, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/proposaldelete"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("proposal_id", proposalId); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getEnergyPric(String httpNode) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getenergyprices"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - - public static HttpResponse getChainParameters(String httpNode) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getchainparameters"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse accountPermissionUpdate(String httpNode, byte[] ownerAddress, - JsonObject ownerObject, JsonObject witnessObject, JsonObject activesObject, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/accountpermissionupdate"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.add("owner", ownerObject); - //userBaseObj2.add("witness", witnessObject); - userBaseObj2.add("actives", activesObject); - logger.info(userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse exchangeCreate(String httpNode, byte[] ownerAddress, - String firstTokenId, Long firstTokenBalance, String secondTokenId, Long secondTokenBalance, - String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/exchangecreate"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("first_token_id", str2hex(firstTokenId)); - userBaseObj2.addProperty("first_token_balance", firstTokenBalance); - userBaseObj2.addProperty("second_token_id", str2hex(secondTokenId)); - userBaseObj2.addProperty("second_token_balance", secondTokenBalance); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse exchangeInject(String httpNode, byte[] ownerAddress, - Integer exchangeId, String tokenId, Long quant, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/exchangeinject"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("exchange_id", exchangeId); - userBaseObj2.addProperty("token_id", str2hex(tokenId)); - userBaseObj2.addProperty("quant", quant); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse exchangeWithdraw(String httpNode, byte[] ownerAddress, - Integer exchangeId, String tokenId, Long quant, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/exchangewithdraw"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("exchange_id", exchangeId); - userBaseObj2.addProperty("token_id", str2hex(tokenId)); - userBaseObj2.addProperty("quant", quant); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse exchangeTransaction(String httpNode, byte[] ownerAddress, - Integer exchangeId, String tokenId, Long quant, Long expected, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/exchangetransaction"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("exchange_id", exchangeId); - userBaseObj2.addProperty("token_id", str2hex(tokenId)); - userBaseObj2.addProperty("quant", quant); - userBaseObj2.addProperty("expected", expected); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse assetIssue(String httpNode, byte[] ownerAddress, String name, - String abbr, Long totalSupply, Integer trxNum, Integer num, Long startTime, Long endTime, - Integer voteScore, Integer precision, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createassetissue"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("name", str2hex(name)); - userBaseObj2.addProperty("abbr", str2hex(abbr)); - userBaseObj2.addProperty("total_supply", totalSupply); - userBaseObj2.addProperty("trx_num", trxNum); - userBaseObj2.addProperty("num", num); - userBaseObj2.addProperty("precision", precision); - userBaseObj2.addProperty("start_time", startTime); - userBaseObj2.addProperty("end_time", endTime); - userBaseObj2.addProperty("vote_score", voteScore); - userBaseObj2.addProperty("description", str2hex(description)); - userBaseObj2.addProperty("url", str2hex(url)); - userBaseObj2.addProperty("free_asset_net_limit", freeAssetNetLimit); - userBaseObj2.addProperty("public_free_asset_net_limit", publicFreeAssetNetLimit); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse transferAsset(String httpNode, byte[] ownerAddress, byte[] toAddress, - String assetIssueById, Long amount, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/transferasset"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("asset_name", str2hex(assetIssueById)); - userBaseObj2.addProperty("amount", amount); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse deployContract(String httpNode, String name, String abi, - String bytecode, Long bandwidthLimit, Long feeLimit, Integer consumeUserResourcePercent, - Long originEnergyLimit, Long callValue, Integer tokenId, Long tokenValue, byte[] ownerAddress, - String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/deploycontract"; - JsonObject userBaseObj2 = new JsonObject(); - //userBaseObj2.addProperty("name", str2hex(name)); - userBaseObj2.addProperty("name", name); - userBaseObj2.addProperty("abi", abi); - userBaseObj2.addProperty("bytecode", bytecode); - userBaseObj2.addProperty("bandwidth_limit", bandwidthLimit); - userBaseObj2.addProperty("fee_limit", feeLimit); - userBaseObj2.addProperty("consume_user_resource_percent", consumeUserResourcePercent); - userBaseObj2.addProperty("origin_energy_limit", originEnergyLimit); - userBaseObj2.addProperty("call_value", callValue); - userBaseObj2.addProperty("token_id", tokenId); - userBaseObj2.addProperty("tokenValue", tokenValue); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static String deployContractGetTxid(String httpNode, String name, String abi, - String bytecode, Long bandwidthLimit, Long feeLimit, Integer consumeUserResourcePercent, - Long originEnergyLimit, Long callValue, Integer tokenId, Long tokenValue, byte[] ownerAddress, - String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/deploycontract"; - JsonObject userBaseObj2 = new JsonObject(); - //userBaseObj2.addProperty("name", str2hex(name)); - userBaseObj2.addProperty("name", name); - userBaseObj2.addProperty("abi", abi); - userBaseObj2.addProperty("bytecode", bytecode); - userBaseObj2.addProperty("bandwidth_limit", bandwidthLimit); - userBaseObj2.addProperty("fee_limit", feeLimit); - userBaseObj2.addProperty("consume_user_resource_percent", consumeUserResourcePercent); - userBaseObj2.addProperty("origin_energy_limit", originEnergyLimit); - userBaseObj2.addProperty("call_value", callValue); - userBaseObj2.addProperty("token_id", tokenId); - userBaseObj2.addProperty("call_token_value", tokenValue); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - - logger.info(userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseStringContent(transactionString); - return responseContent.getString("txID"); - } - - /** - * constructor. - */ - public static HttpResponse deployContractGetTxidWithTooBigLong(String httpNode, String name, - String abi, String bytecode, Long bandwidthLimit, Long feeLimit, - Integer consumeUserResourcePercent, Long originEnergyLimit, Long callValue, Integer tokenId, - Long tokenValue, byte[] ownerAddress, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/deploycontract"; - - String text = "{\"call_token_value\": 10000000e100000000}"; - JSONObject jsonObject = JSONObject.parseObject(text); - logger.info("jsonObject: " + jsonObject.toString()); - jsonObject.put("name", name); - jsonObject.put("abi", abi); - jsonObject.put("bytecode", bytecode); - jsonObject.put("bandwidth_limit", bandwidthLimit); - jsonObject.put("fee_limit", feeLimit); - jsonObject.put("consume_user_resource_percent", consumeUserResourcePercent); - jsonObject.put("origin_energy_limit", originEnergyLimit); - jsonObject.put("call_value", callValue); - jsonObject.put("token_id", tokenId); - jsonObject.put("owner_address", ByteArray.toHexString(ownerAddress)); - - logger.info(jsonObject.toString()); - response = createConnect1(requestUrl, jsonObject); + static HttpClient httpClient; + static HttpPost httppost; + static HttpResponse response; + static Integer connectionTimeout = + Configuration.getByPath("testng.conf").getInt("defaultParameter.httpConnectionTimeout"); + static Integer soTimeout = + Configuration.getByPath("testng.conf").getInt("defaultParameter.httpSoTimeout"); + static String transactionString; + static String transactionSignString; + static JSONObject responseContent; + static JSONObject signResponseContent; + static JSONObject transactionApprovedListContent; + public static volatile Integer witnessNum; + + /** constructor. */ + private static volatile String httpnode = + Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(1); + + /** constructor. */ + public static Integer getWitnessNum() { + if (null == witnessNum) { + witnessNum = parseResponseContent(listwitnesses(httpnode)).getJSONArray("witnesses").size(); + } + + return witnessNum; + } + + static { + PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(); + pccm.setDefaultMaxPerRoute(80); + pccm.setMaxTotal(100); + + httpClient = new DefaultHttpClient(pccm); + } + + /** constructor. */ + public static HttpResponse updateAccount( + String httpNode, byte[] updateAccountAddress, String accountName, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/updateaccount"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("account_name", str2hex(accountName)); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(updateAccountAddress)); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse setAccountId( + String httpNode, + byte[] setAccountIdAddress, + String accountId, + Boolean visable, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/setaccountid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("account_id", accountId); + userBaseObj2.addProperty( + "owner_address", Base58.encode58Check(PublicMethed.getFinalAddress(fromKey))); + userBaseObj2.addProperty("visible", visable); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse updateWitness( + String httpNode, byte[] witnessAddress, String updateUrl, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/updatewitness"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("update_url", str2hex(updateUrl)); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(witnessAddress)); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse voteWitnessAccount( + String httpNode, byte[] ownerAddress, JsonArray voteArray, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/votewitnessaccount"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.add("votes", voteArray); + logger.info(userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse createAccount( + String httpNode, byte[] ownerAddress, byte[] accountAddress, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createaccount"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("account_address", ByteArray.toHexString(accountAddress)); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse createWitness(String httpNode, byte[] ownerAddress, String url) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createwitness"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("url", str2hex(url)); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + response = createConnect(requestUrl, userBaseObj2); + logger.info(userBaseObj2.toString()); + // transactionString = EntityUtils.toString(response.getEntity()); + // transactionSignString = gettransactionsign(httpNode,transactionString,fromKey); + // response = broadcastTransaction(httpNode,transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse withdrawBalance(String httpNode, byte[] witnessAddress) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/withdrawbalance"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(witnessAddress)); + response = createConnect(requestUrl, userBaseObj2); + logger.info(userBaseObj2.toString()); + // transactionString = EntityUtils.toString(response.getEntity()); + // transactionSignString = gettransactionsign(httpNode,transactionString,fromKey); + // response = broadcastTransaction(httpNode,transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse sendCoin( + String httpNode, byte[] fromAddress, byte[] toAddress, Long amount, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(fromAddress)); + userBaseObj2.addProperty("amount", amount); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse sendCoin( + String httpNode, + byte[] fromAddress, + byte[] toAddress, + Long amount, + Integer permissionId, + String[] managerKeys) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(fromAddress)); + userBaseObj2.addProperty("amount", amount); + userBaseObj2.addProperty("Permission_id", permissionId); + response = createConnect(requestUrl, userBaseObj2); + transactionSignString = EntityUtils.toString(response.getEntity()); + HttpResponse getSignWeightResponse; + HttpResponse getTransactionApprovedListResponse; + + for (String key : managerKeys) { + transactionSignString = gettransactionsign(httpNode, transactionSignString, key); + getSignWeightResponse = getSignWeight(httpNode, transactionSignString); + signResponseContent = parseResponseContent(getSignWeightResponse); + logger.info("-----------sign information-----------------"); + printJsonContent(signResponseContent); + getSignWeightResponse = getTransactionApprovedList(httpNode, transactionSignString); + signResponseContent = parseResponseContent(getSignWeightResponse); + logger.info("-----------get Transaction Approved List-----------------"); + printJsonContent(signResponseContent); + } + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static String sendCoin( + String httpNode, + byte[] fromAddress, + byte[] toAddress, + Long amount, + String notes, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(fromAddress)); + userBaseObj2.addProperty("amount", amount); + userBaseObj2.addProperty("extra_data", ByteArray.toHexString(notes.getBytes())); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseStringContent(transactionString); + return responseContent.getString("txID"); + } + + /** constructor. */ + public static String sendCoinGetTxid( + String httpNode, byte[] fromAddress, byte[] toAddress, Long amount, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createtransaction"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(fromAddress)); + userBaseObj2.addProperty("amount", amount); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseStringContent(transactionString); + logger.info(responseContent.getString("txID")); + return responseContent.getString("txID"); + } + + /** constructor. */ + public static HttpResponse createProposal( + String httpNode, byte[] ownerAddress, Long proposalKey, Long proposalValue, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/proposalcreate"; + JsonObject userBaseObj2 = new JsonObject(); + JsonObject proposalMap = new JsonObject(); + proposalMap.addProperty("key", proposalKey); + proposalMap.addProperty("value", proposalValue); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.add("parameters", proposalMap); + + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse approvalProposal( + String httpNode, + byte[] ownerAddress, + Integer proposalId, + Boolean isAddApproval, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/proposalapprove"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("proposal_id", proposalId); + userBaseObj2.addProperty("is_add_approval", isAddApproval); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse deleteProposal( + String httpNode, byte[] ownerAddress, Integer proposalId, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/proposaldelete"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("proposal_id", proposalId); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getEnergyPric(String httpNode) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getenergyprices"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getChainParameters(String httpNode) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getchainparameters"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse accountPermissionUpdate( + String httpNode, + byte[] ownerAddress, + JsonObject ownerObject, + JsonObject witnessObject, + JsonObject activesObject, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/accountpermissionupdate"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.add("owner", ownerObject); + // userBaseObj2.add("witness", witnessObject); + userBaseObj2.add("actives", activesObject); + logger.info(userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse exchangeCreate( + String httpNode, + byte[] ownerAddress, + String firstTokenId, + Long firstTokenBalance, + String secondTokenId, + Long secondTokenBalance, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/exchangecreate"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("first_token_id", str2hex(firstTokenId)); + userBaseObj2.addProperty("first_token_balance", firstTokenBalance); + userBaseObj2.addProperty("second_token_id", str2hex(secondTokenId)); + userBaseObj2.addProperty("second_token_balance", secondTokenBalance); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse exchangeInject( + String httpNode, + byte[] ownerAddress, + Integer exchangeId, + String tokenId, + Long quant, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/exchangeinject"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("exchange_id", exchangeId); + userBaseObj2.addProperty("token_id", str2hex(tokenId)); + userBaseObj2.addProperty("quant", quant); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse exchangeWithdraw( + String httpNode, + byte[] ownerAddress, + Integer exchangeId, + String tokenId, + Long quant, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/exchangewithdraw"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("exchange_id", exchangeId); + userBaseObj2.addProperty("token_id", str2hex(tokenId)); + userBaseObj2.addProperty("quant", quant); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse exchangeTransaction( + String httpNode, + byte[] ownerAddress, + Integer exchangeId, + String tokenId, + Long quant, + Long expected, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/exchangetransaction"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("exchange_id", exchangeId); + userBaseObj2.addProperty("token_id", str2hex(tokenId)); + userBaseObj2.addProperty("quant", quant); + userBaseObj2.addProperty("expected", expected); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse assetIssue( + String httpNode, + byte[] ownerAddress, + String name, + String abbr, + Long totalSupply, + Integer trxNum, + Integer num, + Long startTime, + Long endTime, + Integer voteScore, + Integer precision, + String description, + String url, + Long freeAssetNetLimit, + Long publicFreeAssetNetLimit, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createassetissue"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("name", str2hex(name)); + userBaseObj2.addProperty("abbr", str2hex(abbr)); + userBaseObj2.addProperty("total_supply", totalSupply); + userBaseObj2.addProperty("trx_num", trxNum); + userBaseObj2.addProperty("num", num); + userBaseObj2.addProperty("precision", precision); + userBaseObj2.addProperty("start_time", startTime); + userBaseObj2.addProperty("end_time", endTime); + userBaseObj2.addProperty("vote_score", voteScore); + userBaseObj2.addProperty("description", str2hex(description)); + userBaseObj2.addProperty("url", str2hex(url)); + userBaseObj2.addProperty("free_asset_net_limit", freeAssetNetLimit); + userBaseObj2.addProperty("public_free_asset_net_limit", publicFreeAssetNetLimit); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse transferAsset( + String httpNode, + byte[] ownerAddress, + byte[] toAddress, + String assetIssueById, + Long amount, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/transferasset"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("asset_name", str2hex(assetIssueById)); + userBaseObj2.addProperty("amount", amount); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse deployContract( + String httpNode, + String name, + String abi, + String bytecode, + Long bandwidthLimit, + Long feeLimit, + Integer consumeUserResourcePercent, + Long originEnergyLimit, + Long callValue, + Integer tokenId, + Long tokenValue, + byte[] ownerAddress, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/deploycontract"; + JsonObject userBaseObj2 = new JsonObject(); + // userBaseObj2.addProperty("name", str2hex(name)); + userBaseObj2.addProperty("name", name); + userBaseObj2.addProperty("abi", abi); + userBaseObj2.addProperty("bytecode", bytecode); + userBaseObj2.addProperty("bandwidth_limit", bandwidthLimit); + userBaseObj2.addProperty("fee_limit", feeLimit); + userBaseObj2.addProperty("consume_user_resource_percent", consumeUserResourcePercent); + userBaseObj2.addProperty("origin_energy_limit", originEnergyLimit); + userBaseObj2.addProperty("call_value", callValue); + userBaseObj2.addProperty("token_id", tokenId); + userBaseObj2.addProperty("tokenValue", tokenValue); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static String deployContractGetTxid( + String httpNode, + String name, + String abi, + String bytecode, + Long bandwidthLimit, + Long feeLimit, + Integer consumeUserResourcePercent, + Long originEnergyLimit, + Long callValue, + Integer tokenId, + Long tokenValue, + byte[] ownerAddress, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/deploycontract"; + JsonObject userBaseObj2 = new JsonObject(); + // userBaseObj2.addProperty("name", str2hex(name)); + userBaseObj2.addProperty("name", name); + userBaseObj2.addProperty("abi", abi); + userBaseObj2.addProperty("bytecode", bytecode); + userBaseObj2.addProperty("bandwidth_limit", bandwidthLimit); + userBaseObj2.addProperty("fee_limit", feeLimit); + userBaseObj2.addProperty("consume_user_resource_percent", consumeUserResourcePercent); + userBaseObj2.addProperty("origin_energy_limit", originEnergyLimit); + userBaseObj2.addProperty("call_value", callValue); + userBaseObj2.addProperty("token_id", tokenId); + userBaseObj2.addProperty("call_token_value", tokenValue); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + + logger.info(userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseStringContent(transactionString); + return responseContent.getString("txID"); + } + + /** constructor. */ + public static HttpResponse deployContractGetTxidWithTooBigLong( + String httpNode, + String name, + String abi, + String bytecode, + Long bandwidthLimit, + Long feeLimit, + Integer consumeUserResourcePercent, + Long originEnergyLimit, + Long callValue, + Integer tokenId, + Long tokenValue, + byte[] ownerAddress, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/deploycontract"; + + String text = "{\"call_token_value\": 10000000e100000000}"; + JSONObject jsonObject = JSONObject.parseObject(text); + logger.info("jsonObject: " + jsonObject.toString()); + jsonObject.put("name", name); + jsonObject.put("abi", abi); + jsonObject.put("bytecode", bytecode); + jsonObject.put("bandwidth_limit", bandwidthLimit); + jsonObject.put("fee_limit", feeLimit); + jsonObject.put("consume_user_resource_percent", consumeUserResourcePercent); + jsonObject.put("origin_energy_limit", originEnergyLimit); + jsonObject.put("call_value", callValue); + jsonObject.put("token_id", tokenId); + jsonObject.put("owner_address", ByteArray.toHexString(ownerAddress)); + + logger.info(jsonObject.toString()); + response = createConnect1(requestUrl, jsonObject); /* transactionString = EntityUtils.toString(response.getEntity()); logger.info(transactionString); transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); logger.info(transactionSignString); response = broadcastTransaction(httpNode, transactionSignString);*/ - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static String triggerContractGetTxid(String httpNode, byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter, Long feeLimit, - Long callValue, Integer tokenId, Long tokenValue, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/triggersmartcontract"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("contract_address", contractAddress); - userBaseObj2.addProperty("function_selector", functionSelector); - userBaseObj2.addProperty("parameter", parameter); - userBaseObj2.addProperty("fee_limit", feeLimit); - userBaseObj2.addProperty("call_value", callValue); - userBaseObj2.addProperty("token_id", tokenId); - userBaseObj2.addProperty("call_token_value", tokenValue); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - - transactionSignString = gettransactionsign(httpNode, - parseStringContent(transactionString).getString("transaction"), fromKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseStringContent(transactionSignString); - return responseContent.getString("txID"); - } - - - /** - * constructor. - */ - public static String triggerContractGetTxidWithVisibleTrue(String httpNode, String ownerAddress, - String contractAddress, String functionSelector, String parameter, Long feeLimit, - Long callValue, Integer tokenId, Long tokenValue, String fromKey) { - return triggerContractGetTxidWithVisibleTrue(httpNode, "", ownerAddress, - contractAddress, functionSelector, parameter, feeLimit, callValue, tokenId, tokenValue, - fromKey); - - } - - /** - * constructor. - */ - public static String triggerContractGetTxidWithVisibleTrue(String httpNode, - String anotherHttpNode, - String ownerAddress, - String contractAddress, String functionSelector, String parameter, Long feeLimit, - Long callValue, Integer tokenId, Long tokenValue, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/triggersmartcontract"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ownerAddress); - userBaseObj2.addProperty("contract_address", contractAddress); - userBaseObj2.addProperty("function_selector", functionSelector); - userBaseObj2.addProperty("parameter", parameter); - userBaseObj2.addProperty("fee_limit", feeLimit); - userBaseObj2.addProperty("call_value", callValue); - userBaseObj2.addProperty("token_id", tokenId); - userBaseObj2.addProperty("call_token_value", tokenValue); - userBaseObj2.addProperty("visible", true); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - - transactionSignString = gettransactionsign(httpNode, - parseStringContent(transactionString).getString("transaction"), fromKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - if (!anotherHttpNode.isEmpty()) { - broadcastTransaction(anotherHttpNode, transactionSignString); - } - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseStringContent(transactionSignString); - return responseContent.getString("txID"); - } - - - /** - * constructor. - */ - public static HttpResponse triggerConstantContract(String httpNode, byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter, Long feeLimit, - String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/triggerconstantcontract"; - JsonObject userBaseObj2 = new JsonObject(); - - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("contract_address", contractAddress); - userBaseObj2.addProperty("function_selector", functionSelector); - userBaseObj2.addProperty("parameter", parameter); - userBaseObj2.addProperty("fee_limit", feeLimit); - - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse triggerConstantContract(String httpNode, byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/triggerconstantcontract"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("contract_address", contractAddress); - userBaseObj2.addProperty("function_selector", functionSelector); - userBaseObj2.addProperty("parameter", parameter); - response = createConnect(requestUrl, userBaseObj2); - return response; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static HttpResponse triggerConstantContractFromSolidity(String httSoliditypNode, - byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter) { - try { - final String requestUrl = - "http://" + httSoliditypNode + "/walletsolidity/triggerconstantcontract"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("contract_address", contractAddress); - userBaseObj2.addProperty("function_selector", functionSelector); - userBaseObj2.addProperty("parameter", parameter); - response = createConnect(requestUrl, userBaseObj2); - return response; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static HttpResponse triggerConstantContractFromPbft(String httpPbftNode, - byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter) { - try { - final String requestUrl = "http://" + httpPbftNode + "/walletpbft/triggerconstantcontract"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("contract_address", contractAddress); - userBaseObj2.addProperty("function_selector", functionSelector); - userBaseObj2.addProperty("parameter", parameter); - response = createConnect(requestUrl, userBaseObj2); - return response; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static HttpResponse participateAssetIssue(String httpNode, byte[] toAddress, - byte[] ownerAddress, String assetIssueById, Long amount, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/participateassetissue"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("asset_name", str2hex(assetIssueById)); - userBaseObj2.addProperty("amount", amount); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse updateAssetIssue(String httpNode, byte[] ownerAddress, - String description, String url, Long newLimit, Long newPublicLimit, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/updateasset"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("url", str2hex(url)); - userBaseObj2.addProperty("description", str2hex(description)); - userBaseObj2.addProperty("new_limit", newLimit); - userBaseObj2.addProperty("new_public_limit", newPublicLimit); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static String triggerContractGetTxid( + String httpNode, + byte[] ownerAddress, + String contractAddress, + String functionSelector, + String parameter, + Long feeLimit, + Long callValue, + Integer tokenId, + Long tokenValue, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/triggersmartcontract"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("function_selector", functionSelector); + userBaseObj2.addProperty("parameter", parameter); + userBaseObj2.addProperty("fee_limit", feeLimit); + userBaseObj2.addProperty("call_value", callValue); + userBaseObj2.addProperty("token_id", tokenId); + userBaseObj2.addProperty("call_token_value", tokenValue); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); - /** - * constructor. - */ - public static Boolean verificationResult(HttpResponse response) { - if (response.getStatusLine().getStatusCode() != 200) { - return false; - } - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - //HttpMethed.printJsonContent(responseContent); - return Boolean.valueOf(responseContent.getString("result")).booleanValue(); - } - - /** - * constructor. - */ - public static HttpResponse freezeBalance(String httpNode, byte[] ownerAddress, Long frozenBalance, - Integer frozenDuration, Integer resourceCode, String fromKey) { - return freezeBalance(httpNode, ownerAddress, frozenBalance, frozenDuration, resourceCode, null, - fromKey); - } - - /** - * constructor. - */ - public static HttpResponse freezeBalance(String httpNode, byte[] ownerAddress, Long frozenBalance, - Integer frozenDuration, Integer resourceCode, byte[] receiverAddress, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/freezebalance"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("frozen_balance", frozenBalance); - userBaseObj2.addProperty("frozen_duration", frozenDuration); - if (resourceCode == 0) { - userBaseObj2.addProperty("resource", "BANDWIDTH"); - } - if (resourceCode == 1) { - userBaseObj2.addProperty("resource", "ENERGY"); - } - if (resourceCode == 2) { - userBaseObj2.addProperty("resource", "TRON_POWER"); - } - if (receiverAddress != null) { - userBaseObj2.addProperty("receiver_address", ByteArray.toHexString(receiverAddress)); - } - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse unFreezeBalance(String httpNode, byte[] ownerAddress, - Integer resourceCode, String fromKey) { - return unFreezeBalance(httpNode, ownerAddress, resourceCode, null, fromKey); - } - - /** - * constructor. - */ - public static HttpResponse unFreezeBalance(String httpNode, byte[] ownerAddress, - Integer resourceCode, byte[] receiverAddress, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/unfreezebalance"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - if (resourceCode == 0) { - userBaseObj2.addProperty("resource", "BANDWIDTH"); - } - if (resourceCode == 1) { - userBaseObj2.addProperty("resource", "ENERGY"); - } - if (resourceCode == 2) { - userBaseObj2.addProperty("resource", "TRON_POWER"); - } - if (receiverAddress != null) { - userBaseObj2.addProperty("receiver_address", ByteArray.toHexString(receiverAddress)); - } - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static String gettransactionsign(String httpNode, String transactionString, - String privateKey) { - try { - String requestUrl = "http://" + httpNode + "/wallet/gettransactionsign"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("transaction", transactionString); - userBaseObj2.addProperty("privateKey", privateKey); - response = createConnect(requestUrl, userBaseObj2); - transactionSignString = EntityUtils.toString(response.getEntity()); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return transactionSignString; - } - - /** - * constructor. - */ - public static HttpResponse broadcastTransaction(String httpNode, String transactionSignString) { - try { - String requestUrl = "http://" + httpNode + "/wallet/broadcasttransaction"; - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httppost = new HttpPost(requestUrl); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - if (transactionSignString != null) { - StringEntity entity = new StringEntity(transactionSignString, Charset.forName("UTF-8")); - entity.setContentEncoding("UTF-8"); - entity.setContentType("application/json"); - httppost.setEntity(entity); - } - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } + transactionSignString = + gettransactionsign( + httpNode, parseStringContent(transactionString).getString("transaction"), fromKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseStringContent(transactionSignString); + return responseContent.getString("txID"); + } + + /** constructor. */ + public static String triggerContractGetTxidWithVisibleTrue( + String httpNode, + String ownerAddress, + String contractAddress, + String functionSelector, + String parameter, + Long feeLimit, + Long callValue, + Integer tokenId, + Long tokenValue, + String fromKey) { + return triggerContractGetTxidWithVisibleTrue( + httpNode, + "", + ownerAddress, + contractAddress, + functionSelector, + parameter, + feeLimit, + callValue, + tokenId, + tokenValue, + fromKey); + } + + /** constructor. */ + public static String triggerContractGetTxidWithVisibleTrue( + String httpNode, + String anotherHttpNode, + String ownerAddress, + String contractAddress, + String functionSelector, + String parameter, + Long feeLimit, + Long callValue, + Integer tokenId, + Long tokenValue, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/triggersmartcontract"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ownerAddress); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("function_selector", functionSelector); + userBaseObj2.addProperty("parameter", parameter); + userBaseObj2.addProperty("fee_limit", feeLimit); + userBaseObj2.addProperty("call_value", callValue); + userBaseObj2.addProperty("token_id", tokenId); + userBaseObj2.addProperty("call_token_value", tokenValue); + userBaseObj2.addProperty("visible", true); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); - responseContent = HttpMethed.parseResponseContent(response); - Integer times = 0; - - while (times++ <= 10 && responseContent.getString("code") != null && responseContent - .getString("code").equalsIgnoreCase("SERVER_BUSY")) { - logger.info("retry num are " + times); - try { - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseResponseContent(response); - try { - Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } + transactionSignString = + gettransactionsign( + httpNode, parseStringContent(transactionString).getString("transaction"), fromKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + if (!anotherHttpNode.isEmpty()) { + broadcastTransaction(anotherHttpNode, transactionSignString); + } + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseStringContent(transactionSignString); + return responseContent.getString("txID"); + } + + /** constructor. */ + public static HttpResponse triggerConstantContract( + String httpNode, + byte[] ownerAddress, + String contractAddress, + String functionSelector, + String parameter, + Long feeLimit, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/triggerconstantcontract"; + JsonObject userBaseObj2 = new JsonObject(); + + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("function_selector", functionSelector); + userBaseObj2.addProperty("parameter", parameter); + userBaseObj2.addProperty("fee_limit", feeLimit); + + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse triggerConstantContract( + String httpNode, + byte[] ownerAddress, + String contractAddress, + String functionSelector, + String parameter) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/triggerconstantcontract"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("function_selector", functionSelector); + userBaseObj2.addProperty("parameter", parameter); + response = createConnect(requestUrl, userBaseObj2); + return response; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** constructor. */ + public static HttpResponse triggerConstantContractFromSolidity( + String httSoliditypNode, + byte[] ownerAddress, + String contractAddress, + String functionSelector, + String parameter) { + try { + final String requestUrl = + "http://" + httSoliditypNode + "/walletsolidity/triggerconstantcontract"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("function_selector", functionSelector); + userBaseObj2.addProperty("parameter", parameter); + response = createConnect(requestUrl, userBaseObj2); + return response; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** constructor. */ + public static HttpResponse triggerConstantContractFromPbft( + String httpPbftNode, + byte[] ownerAddress, + String contractAddress, + String functionSelector, + String parameter) { + try { + final String requestUrl = "http://" + httpPbftNode + "/walletpbft/triggerconstantcontract"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("function_selector", functionSelector); + userBaseObj2.addProperty("parameter", parameter); + response = createConnect(requestUrl, userBaseObj2); + return response; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** constructor. */ + public static HttpResponse participateAssetIssue( + String httpNode, + byte[] toAddress, + byte[] ownerAddress, + String assetIssueById, + Long amount, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/participateassetissue"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("to_address", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("asset_name", str2hex(assetIssueById)); + userBaseObj2.addProperty("amount", amount); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse updateAssetIssue( + String httpNode, + byte[] ownerAddress, + String description, + String url, + Long newLimit, + Long newPublicLimit, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/updateasset"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("url", str2hex(url)); + userBaseObj2.addProperty("description", str2hex(description)); + userBaseObj2.addProperty("new_limit", newLimit); + userBaseObj2.addProperty("new_public_limit", newPublicLimit); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static Boolean verificationResult(HttpResponse response) { + if (response.getStatusLine().getStatusCode() != 200) { + return false; + } + Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); + responseContent = HttpMethed.parseResponseContent(response); + // HttpMethed.printJsonContent(responseContent); + return Boolean.valueOf(responseContent.getString("result")).booleanValue(); + } + + /** constructor. */ + public static HttpResponse freezeBalance( + String httpNode, + byte[] ownerAddress, + Long frozenBalance, + Integer frozenDuration, + Integer resourceCode, + String fromKey) { + return freezeBalance( + httpNode, ownerAddress, frozenBalance, frozenDuration, resourceCode, null, fromKey); + } + + /** constructor. */ + public static HttpResponse freezeBalance( + String httpNode, + byte[] ownerAddress, + Long frozenBalance, + Integer frozenDuration, + Integer resourceCode, + byte[] receiverAddress, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/freezebalance"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("frozen_balance", frozenBalance); + userBaseObj2.addProperty("frozen_duration", frozenDuration); + if (resourceCode == 0) { + userBaseObj2.addProperty("resource", "BANDWIDTH"); + } + if (resourceCode == 1) { + userBaseObj2.addProperty("resource", "ENERGY"); + } + if (resourceCode == 2) { + userBaseObj2.addProperty("resource", "TRON_POWER"); + } + if (receiverAddress != null) { + userBaseObj2.addProperty("receiver_address", ByteArray.toHexString(receiverAddress)); + } + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse unFreezeBalance( + String httpNode, byte[] ownerAddress, Integer resourceCode, String fromKey) { + return unFreezeBalance(httpNode, ownerAddress, resourceCode, null, fromKey); + } + + /** constructor. */ + public static HttpResponse unFreezeBalance( + String httpNode, + byte[] ownerAddress, + Integer resourceCode, + byte[] receiverAddress, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/unfreezebalance"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + if (resourceCode == 0) { + userBaseObj2.addProperty("resource", "BANDWIDTH"); + } + if (resourceCode == 1) { + userBaseObj2.addProperty("resource", "ENERGY"); + } + if (resourceCode == 2) { + userBaseObj2.addProperty("resource", "TRON_POWER"); + } + if (receiverAddress != null) { + userBaseObj2.addProperty("receiver_address", ByteArray.toHexString(receiverAddress)); + } + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static String gettransactionsign( + String httpNode, String transactionString, String privateKey) { + try { + String requestUrl = "http://" + httpNode + "/wallet/gettransactionsign"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("transaction", transactionString); + userBaseObj2.addProperty("privateKey", privateKey); + response = createConnect(requestUrl, userBaseObj2); + transactionSignString = EntityUtils.toString(response.getEntity()); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return transactionSignString; + } + + /** constructor. */ + public static HttpResponse broadcastTransaction(String httpNode, String transactionSignString) { + try { + String requestUrl = "http://" + httpNode + "/wallet/broadcasttransaction"; + httpClient + .getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + httppost = new HttpPost(requestUrl); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + if (transactionSignString != null) { + StringEntity entity = new StringEntity(transactionSignString, Charset.forName("UTF-8")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httppost.setEntity(entity); + } + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + + responseContent = HttpMethed.parseResponseContent(response); + Integer times = 0; + + while (times++ <= 10 + && responseContent.getString("code") != null + && responseContent.getString("code").equalsIgnoreCase("SERVER_BUSY")) { + logger.info("retry num are " + times); + try { + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); httppost.releaseConnection(); - return response; - } - - /** - * constructor. - */ - public static HttpResponse broadcasthex(String httpNode, String transactionHex) { - try { - String requestUrl = "http://" + httpNode + "/wallet/broadcasthex"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("transaction", transactionHex); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getAccountById(String httpNode, String accountId, Boolean visable) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getaccountbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("account_id", accountId); - userBaseObj2.addProperty("visible", visable); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAccountByIdFromSolidity(String httpSolidityNode, String accountId, - Boolean visable) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getaccountbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("account_id", accountId); - userBaseObj2.addProperty("visible", visable); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAccountByIdFromPbft(String httpSolidityNode, String accountId, - Boolean visable) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getaccountbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("account_id", accountId); - userBaseObj2.addProperty("visible", visable); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAccount(String httpNode, byte[] queryAddress) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getaccount"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static Long getAccountForResponse(String httpNode, byte[] queryAddress, Integer times) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getaccount"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); - Long duration = createConnectForResponse(requestUrl, userBaseObj2, times); - return duration; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return -1L; - } - } - - - /** - * constructor. - */ - public static HttpResponse getAccountFromSolidity(String httpSolidityNode, byte[] queryAddress) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getaccount"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); - response = createConnect(requestUrl, userBaseObj2); - logger.info(requestUrl); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAccountFromPbft(String httpSolidityNode, byte[] queryAddress) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getaccount"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getContract(String httpNode, String contractAddress) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getcontract"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", contractAddress); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getSignWeight(String httpNode, String transactionSignString) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getsignweight"; - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httppost = new HttpPost(requestUrl); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - if (transactionSignString != null) { - StringEntity entity = new StringEntity(transactionSignString, Charset.forName("UTF-8")); - entity.setContentEncoding("UTF-8"); - entity.setContentType("application/json"); - httppost.setEntity(entity); - } - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - //httppost.releaseConnection(); - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionApprovedList(String httpNode, - String transactionSignString) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getapprovedlist"; - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httppost = new HttpPost(requestUrl); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - if (transactionSignString != null) { - StringEntity entity = new StringEntity(transactionSignString, Charset.forName("UTF-8")); - entity.setContentEncoding("UTF-8"); - entity.setContentType("application/json"); - httppost.setEntity(entity); - } - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - //httppost.releaseConnection(); - return response; - } - - - /** - * constructor. - */ - public static HttpResponse listExchanges(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/listexchanges"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse listExchangesFromSolidity(String httpSolidityNode) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/listexchanges"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse listExchangesFromPbft(String httpSolidityNode) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/listexchanges"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse listNodes(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/listnodes"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getStatsInfo(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/monitor/getstatsinfo"; - response = createConnectForGet(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getNextmaintenanceTime(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnextmaintenancetime"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getChainParameter(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getchainparameters"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getNodeInfo(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnodeinfo"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse listwitnesses(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/listwitnesses"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse listwitnessesFromSolidity(String httpSolidityNode) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/listwitnesses"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse listwitnessesFromPbft(String httpSolidityNode) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/listwitnesses"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse listProposals(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/listproposals"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getExchangeById(String httpNode, Integer exchangeId) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getexchangebyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("id", exchangeId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getExchangeByIdFromSolidity(String httpSolidityNode, - Integer exchangeId) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getexchangebyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("id", exchangeId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getExchangeByIdFromPbft(String httpSolidityNode, Integer exchangeId) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getexchangebyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("id", exchangeId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getProposalById(String httpNode, Integer proposalId) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getproposalbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("id", proposalId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueListByName(String httpNode, String name) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getassetissuelistbyname"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", str2hex(name)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueListByNameFromSolidity(String httpSolidityNode, - String name) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuelistbyname"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", str2hex(name)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueListByNameFromPbft(String httpPbftNode, - String name) { - try { - String requestUrl = "http://" + httpPbftNode + "/walletpbft/getassetissuelistbyname"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", str2hex(name)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueById(String httpNode, String assetIssueId) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getassetissuebyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", assetIssueId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueByIdFromSolidity(String httpSolidityNode, - String assetIssueId) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuebyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", assetIssueId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueByIdFromPbft(String httpSolidityNode, - String assetIssueId) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getassetissuebyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", assetIssueId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getTransactionById(String httpNode, String txid) { - try { - String requestUrl = "http://" + httpNode + "/wallet/gettransactionbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", txid); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static Long getTransactionByIdForResponse(String httpNode, String txid, Integer times) { - try { - String requestUrl = "http://" + httpNode + "/wallet/gettransactionbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", txid); - Long duration = createConnectForResponse(requestUrl, userBaseObj2, times); - return duration; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - - /** - * constructor. - */ - public static HttpResponse getTransactionByIdFromSolidity(String httpSolidityNode, String txid) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/gettransactionbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", txid); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionByIdFromPbft(String httpSolidityNode, String txid) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/gettransactionbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", txid); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getTransactionInfoById(String httpNode, String txid) { - return getTransactionInfoById(httpNode, txid, false); - } - - /** - * constructor. - */ - public static HttpResponse getTransactionInfoById(String httpNode, String txid, Boolean visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/gettransactioninfobyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", txid); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getTransactionInfoByIdFromSolidity(String httpSolidityNode, - String txid) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/gettransactioninfobyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", txid); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionInfoByIdFromPbft(String httpSolidityNode, String txid) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/gettransactioninfobyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", txid); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionInfoByBlocknum(String httpNode, long blocknum) { - try { - String requestUrl = "http://" + httpNode + "/wallet/gettransactioninfobyblocknum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blocknum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionInfoByBlocknumFromSolidity(String httpSolidityNode, - long blocknum) { - try { - String requestUrl = - "http://" + httpSolidityNode + "/walletsolidity/gettransactioninfobyblocknum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blocknum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionCountByBlocknumFromSolidity(String httpSolidityNode, - long blocknum) { - try { - String requestUrl = - "http://" + httpSolidityNode + "/walletsolidity/gettransactioncountbyblocknum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blocknum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionCountByBlocknumFromPbft(String httpSolidityNode, - long blocknum) { - try { - String requestUrl = - "http://" + httpSolidityNode + "/walletpbft/gettransactioncountbyblocknum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blocknum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getTransactionsFromThisFromSolidity(String httpSolidityNode, - byte[] fromAddress, long offset, long limit) { - try { - Map map1 = new HashMap(); - Map map = new HashMap(); - map1.put("address", ByteArray.toHexString(fromAddress)); - map.put("account", map1); - map.put("offset", offset); - map.put("limit", limit); - String requestUrl = "http://" + httpSolidityNode + "/walletextension/gettransactionsfromthis"; - String jsonStr = new Gson().toJson(map); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - response = createConnect(requestUrl, jsonObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionsToThisFromSolidity(String httpSolidityNode, - byte[] toAddress, long offset, long limit) { - try { - Map map1 = new HashMap(); - Map map = new HashMap(); - map1.put("address", ByteArray.toHexString(toAddress)); - map.put("account", map1); - map.put("offset", offset); - map.put("limit", limit); - String requestUrl = "http://" + httpSolidityNode + "/walletextension/gettransactionstothis"; - String jsonStr = new Gson().toJson(map); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - response = createConnect(requestUrl, jsonObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueByName(String httpNode, String name) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getassetissuebyname"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", str2hex(name)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getAssetIssueByNameFromSolidity(String httpSolidityNode, String name) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuebyname"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", str2hex(name)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueByNameFromPbft(String httpSolidityNode, String name) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getassetissuebyname"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", str2hex(name)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static Long getBalance(String httpNode, byte[] queryAddress) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getaccount"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseResponseContent(response); - //HttpMethed.printJsonContent(responseContent); - //httppost.releaseConnection(); - if (!responseContent.containsKey("balance")) { - return 0L; - } - return Long.parseLong(responseContent.get("balance").toString()); - } - - - /** - * constructor. - */ - public static HttpResponse getAccountNet(String httpNode, byte[] queryAddress) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getaccountnet"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAccountReource(String httpNode, byte[] queryAddress) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getaccountresource"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAccountBalance(String httpNode, - byte[] queryAddress, Integer blockNum, String blockHash) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getaccountbalance"; - JsonObject addressObj = new JsonObject(); - addressObj.addProperty("address", Base58.encode58Check(queryAddress)); - JsonObject blockObj = new JsonObject(); - blockObj.addProperty("hash", blockHash); - blockObj.addProperty("number", blockNum); - JsonObject accountBalanceObj = new JsonObject(); - accountBalanceObj.add("account_identifier", addressObj); - accountBalanceObj.add("block_identifier", blockObj); - accountBalanceObj.addProperty("visible", true); - logger.info(accountBalanceObj.toString()); - response = createConnect(requestUrl, accountBalanceObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBlockBalance(String httpNode, Integer blockNum, String blockHash) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getblockbalance"; - JsonObject blockObj = new JsonObject(); - blockObj.addProperty("hash", blockHash); - blockObj.addProperty("number", blockNum); - blockObj.addProperty("visible", true); - response = createConnect(requestUrl, blockObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static Long getBurnTrx(String httpNode) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getburntrx"; - JsonObject blockObj = new JsonObject(); - response = createConnect(requestUrl, blockObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseResponseContent(response); - return responseContent.getLong("burnTrxAmount"); - } - - /** - * constructor. - */ - public static Long getBurnTrxFromSolidity(String httpNode) { - try { - final String requestUrl = "http://" + httpNode + "/walletsolidity/getburntrx"; - JsonObject blockObj = new JsonObject(); - response = createConnect(requestUrl, blockObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseResponseContent(response); - return responseContent.getLong("burnTrxAmount"); - } - - /** - * constructor. - */ - public static Long getBurnTrxFromPbft(String httpNode) { - try { - final String requestUrl = "http://" + httpNode + "/walletpbft/getburntrx"; - JsonObject blockObj = new JsonObject(); - response = createConnect(requestUrl, blockObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseResponseContent(response); - return responseContent.getLong("burnTrxAmount"); - } - - - /** - * constructor. - */ - public static HttpResponse getNowBlock(String httpNode) { - return getNowBlock(httpNode, false); - } - - /** - * constructor. - */ - public static HttpResponse getNowBlock(String httpNode, Boolean visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static Long getNowBlockNum(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return parseResponseContent(response).getJSONObject("block_header").getJSONObject("raw_data") - .getLong("number"); - } - - /** - * constructor. - */ - public static Long getNowBlockNumOnSolidity(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/walletsolidity/getnowblock"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return parseResponseContent(response).getJSONObject("block_header").getJSONObject("raw_data") - .getLong("number"); - } - - - /** - * constructor. - */ - public static HttpResponse getNowBlockFromSolidity(String httpSolidityNode) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getnowblock"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getNowBlockFromPbft(String httpSolidityNode) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getnowblock"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static void waitToProduceOneBlock(String httpNode) { - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - Integer currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); - Integer nextBlockNum = 0; - Integer times = 0; - while (nextBlockNum <= currentBlockNum + 1 && times++ <= 10) { - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - responseContent = HttpMethed - .parseStringContent(responseContent.get("block_header").toString()); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); - try { - Thread.sleep(1200); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - /** - * constructor. - */ - public static void waitToProduceOneBlockFromSolidity(String httpNode, String httpSolidityNode) { - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - Integer currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); - Integer nextBlockNum = 0; - Integer times = 0; - while (nextBlockNum <= currentBlockNum && times++ <= ((getWitnessNum() >= 27) - ? 27 : getWitnessNum() + 1)) { - response = HttpMethed.getNowBlockFromSolidity(httpSolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - responseContent = HttpMethed - .parseStringContent(responseContent.get("block_header").toString()); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); - try { - Thread.sleep(3500); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - logger.info("currentBlockNum2:" + currentBlockNum); - logger.info("nextBlockNum2:" + nextBlockNum); - } - - /** - * constructor. - */ - public static void waitToProduceOneBlockFromPbft(String httpNode, String httpSolidityNode) { - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - Integer currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); - Integer nextBlockNum = 0; - Integer times = 0; - while (nextBlockNum <= currentBlockNum && times++ <= 3) { - response = HttpMethed.getNowBlockFromPbft(httpSolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - responseContent = HttpMethed - .parseStringContent(responseContent.get("block_header").toString()); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); - try { - Thread.sleep(3500); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - - /** - * constructor. - */ - public static HttpResponse getBlockByNum(String httpNode, Integer blockNUm) { - return getBlockByNum(httpNode, blockNUm, false); - } - - /** - * constructor. - */ - public static HttpResponse getBlockByNum(String httpNode, Integer blockNUm, Boolean visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getblockbynum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blockNUm); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static Long getBlockByNumForResponse(String httpNode, Integer blockNUm, Integer times) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getblockbynum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blockNUm); - Long duration = createConnectForResponse(requestUrl, userBaseObj2, times); - return duration; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return -1L; - } - } - - - /** - * constructor. - */ - public static HttpResponse getBlockByNumFromSolidity(String httpSolidityNode, Integer blockNum) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getblockbynum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blockNum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBlockByNumFromPbft(String httpSolidityNode, Integer blockNum) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getblockbynum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blockNum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getBlockByLimitNext(String httpNode, Integer startNum, - Integer endNum) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getblockbylimitnext"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("startNum", startNum); - userBaseObj2.addProperty("endNum", endNum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBlockByLimitNextFromSolidity(String httpNode, Integer startNum, - Integer endNum) { - try { - String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbylimitnext"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("startNum", startNum); - userBaseObj2.addProperty("endNum", endNum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBlockByLimitNextFromPbft(String httpNode, Integer startNum, - Integer endNum) { - try { - String requestUrl = "http://" + httpNode + "/walletpbft/getblockbylimitnext"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("startNum", startNum); - userBaseObj2.addProperty("endNum", endNum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getBlockByLastNum(String httpNode, Integer num) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getblockbylatestnum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", num); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBlockByLastNum2(String httpNode, Integer num) { - try { - String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbylatestnum2"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", num); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getBlockByLastNumFromSolidity(String httpNode, Integer num) { - try { - String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbylatestnum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", num); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBlockByLastNumFromPbft(String httpNode, Integer num) { - try { - String requestUrl = "http://" + httpNode + "/walletpbft/getblockbylatestnum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", num); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getBlockById(String httpNode, String blockId) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getblockbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", blockId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBlockByIdFromSolidity(String httpNode, String blockId) { - try { - String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", blockId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBlockByIdFromPbft(String httpNode, String blockId) { - try { - String requestUrl = "http://" + httpNode + "/walletpbft/getblockbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", blockId); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getDelegatedResource(String httpNode, byte[] fromAddress, - byte[] toAddress) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getdelegatedresource"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("fromAddress", ByteArray.toHexString(fromAddress)); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getDelegatedResourceFromSolidity(String httpSolidityNode, - byte[] fromAddress, byte[] toAddress) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getdelegatedresource"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("fromAddress", ByteArray.toHexString(fromAddress)); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getDelegatedResourceFromPbft(String httpSolidityNode, - byte[] fromAddress, byte[] toAddress) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getdelegatedresource"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("fromAddress", ByteArray.toHexString(fromAddress)); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getDelegatedResourceAccountIndex(String httpNode, - byte[] queryAddress) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getdelegatedresourceaccountindex"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", ByteArray.toHexString(queryAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getDelegatedResourceAccountIndexFromSolidity(String httpSolidityNode, - byte[] queryAddress) { - try { - String requestUrl = - "http://" + httpSolidityNode + "/walletsolidity/getdelegatedresourceaccountindex"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", ByteArray.toHexString(queryAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getDelegatedResourceAccountIndexFromPbft(String httpSolidityNode, - byte[] queryAddress) { - try { - String requestUrl = - "http://" + httpSolidityNode + "/walletpbft/getdelegatedresourceaccountindex"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", ByteArray.toHexString(queryAddress)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse createConnect(String url) { - return createConnect(url, null); - } - - /** - * constructor. - */ - public static HttpResponse createConnect(String url, JsonObject requestBody) { - try { - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httppost = new HttpPost(url); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - if (requestBody != null) { - StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); - entity.setContentEncoding("UTF-8"); - entity.setContentType("application/json"); - httppost.setEntity(entity); - } - - logger.info(httppost.toString()); - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse createConnectForGet(String url) { - try { - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - HttpGet httppost; - httppost = new HttpGet(url); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - - logger.info(httppost.toString()); - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse createConnectForShieldTrc20(String url, JSONObject requestBody) { - try { - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httppost = new HttpPost(url); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - if (requestBody != null) { - StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); - entity.setContentEncoding("UTF-8"); - entity.setContentType("application/json"); - httppost.setEntity(entity); - } - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static Long createConnectForResponse(String url, JsonObject requestBody, Integer times) { - try { - - Long start = 0L; - Long end = 0L; - Long duration = 0L; - while (times-- > 0) { - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httppost = new HttpPost(url); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - if (requestBody != null) { - StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); - entity.setContentEncoding("UTF-8"); - entity.setContentType("application/json"); - httppost.setEntity(entity); - } - - start = System.currentTimeMillis(); - response = httpClient.execute(httppost); + return null; + } + responseContent = HttpMethed.parseResponseContent(response); + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + httppost.releaseConnection(); + return response; + } + + /** constructor. */ + public static HttpResponse broadcasthex(String httpNode, String transactionHex) { + try { + String requestUrl = "http://" + httpNode + "/wallet/broadcasthex"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("transaction", transactionHex); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAccountById(String httpNode, String accountId, Boolean visable) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getaccountbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("account_id", accountId); + userBaseObj2.addProperty("visible", visable); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAccountByIdFromSolidity( + String httpSolidityNode, String accountId, Boolean visable) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getaccountbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("account_id", accountId); + userBaseObj2.addProperty("visible", visable); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAccountByIdFromPbft( + String httpSolidityNode, String accountId, Boolean visable) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getaccountbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("account_id", accountId); + userBaseObj2.addProperty("visible", visable); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAccount(String httpNode, byte[] queryAddress) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getaccount"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static Long getAccountForResponse(String httpNode, byte[] queryAddress, Integer times) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getaccount"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); + Long duration = createConnectForResponse(requestUrl, userBaseObj2, times); + return duration; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return -1L; + } + } + + /** constructor. */ + public static HttpResponse getAccountFromSolidity(String httpSolidityNode, byte[] queryAddress) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getaccount"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); + response = createConnect(requestUrl, userBaseObj2); + logger.info(requestUrl); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAccountFromPbft(String httpSolidityNode, byte[] queryAddress) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getaccount"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getContract(String httpNode, String contractAddress) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getcontract"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", contractAddress); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getSignWeight(String httpNode, String transactionSignString) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getsignweight"; + httpClient + .getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + httppost = new HttpPost(requestUrl); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + if (transactionSignString != null) { + StringEntity entity = new StringEntity(transactionSignString, Charset.forName("UTF-8")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httppost.setEntity(entity); + } + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + // httppost.releaseConnection(); + return response; + } + + /** constructor. */ + public static HttpResponse getTransactionApprovedList( + String httpNode, String transactionSignString) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getapprovedlist"; + httpClient + .getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + httppost = new HttpPost(requestUrl); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + if (transactionSignString != null) { + StringEntity entity = new StringEntity(transactionSignString, Charset.forName("UTF-8")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httppost.setEntity(entity); + } + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + // httppost.releaseConnection(); + return response; + } + + /** constructor. */ + public static HttpResponse listExchanges(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/listexchanges"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse listExchangesFromSolidity(String httpSolidityNode) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/listexchanges"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse listExchangesFromPbft(String httpSolidityNode) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/listexchanges"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse listNodes(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/listnodes"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getStatsInfo(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/monitor/getstatsinfo"; + response = createConnectForGet(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getNextmaintenanceTime(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getnextmaintenancetime"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getChainParameter(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getchainparameters"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getNodeInfo(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getnodeinfo"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse listwitnesses(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/listwitnesses"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse listwitnessesFromSolidity(String httpSolidityNode) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/listwitnesses"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse listwitnessesFromPbft(String httpSolidityNode) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/listwitnesses"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse listProposals(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/listproposals"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getExchangeById(String httpNode, Integer exchangeId) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getexchangebyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("id", exchangeId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getExchangeByIdFromSolidity( + String httpSolidityNode, Integer exchangeId) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getexchangebyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("id", exchangeId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getExchangeByIdFromPbft(String httpSolidityNode, Integer exchangeId) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getexchangebyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("id", exchangeId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getProposalById(String httpNode, Integer proposalId) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getproposalbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("id", proposalId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAssetIssueListByName(String httpNode, String name) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getassetissuelistbyname"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", str2hex(name)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAssetIssueListByNameFromSolidity( + String httpSolidityNode, String name) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuelistbyname"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", str2hex(name)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAssetIssueListByNameFromPbft(String httpPbftNode, String name) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getassetissuelistbyname"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", str2hex(name)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAssetIssueById(String httpNode, String assetIssueId) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getassetissuebyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", assetIssueId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAssetIssueByIdFromSolidity( + String httpSolidityNode, String assetIssueId) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuebyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", assetIssueId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAssetIssueByIdFromPbft( + String httpSolidityNode, String assetIssueId) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getassetissuebyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", assetIssueId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getTransactionById(String httpNode, String txid) { + try { + String requestUrl = "http://" + httpNode + "/wallet/gettransactionbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", txid); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static Long getTransactionByIdForResponse(String httpNode, String txid, Integer times) { + try { + String requestUrl = "http://" + httpNode + "/wallet/gettransactionbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", txid); + Long duration = createConnectForResponse(requestUrl, userBaseObj2, times); + return duration; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** constructor. */ + public static HttpResponse getTransactionByIdFromSolidity(String httpSolidityNode, String txid) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/gettransactionbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", txid); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getTransactionByIdFromPbft(String httpSolidityNode, String txid) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/gettransactionbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", txid); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getTransactionInfoById(String httpNode, String txid) { + return getTransactionInfoById(httpNode, txid, false); + } + + /** constructor. */ + public static HttpResponse getTransactionInfoById(String httpNode, String txid, Boolean visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/gettransactioninfobyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", txid); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getTransactionInfoByIdFromSolidity( + String httpSolidityNode, String txid) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/gettransactioninfobyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", txid); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getTransactionInfoByIdFromPbft(String httpSolidityNode, String txid) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/gettransactioninfobyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", txid); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getTransactionInfoByBlocknum(String httpNode, long blocknum) { + try { + String requestUrl = "http://" + httpNode + "/wallet/gettransactioninfobyblocknum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blocknum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getTransactionInfoByBlocknumFromSolidity( + String httpSolidityNode, long blocknum) { + try { + String requestUrl = + "http://" + httpSolidityNode + "/walletsolidity/gettransactioninfobyblocknum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blocknum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getTransactionCountByBlocknumFromSolidity( + String httpSolidityNode, long blocknum) { + try { + String requestUrl = + "http://" + httpSolidityNode + "/walletsolidity/gettransactioncountbyblocknum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blocknum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getTransactionCountByBlocknumFromPbft( + String httpSolidityNode, long blocknum) { + try { + String requestUrl = + "http://" + httpSolidityNode + "/walletpbft/gettransactioncountbyblocknum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blocknum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getTransactionsFromThisFromSolidity( + String httpSolidityNode, byte[] fromAddress, long offset, long limit) { + try { + Map map1 = new HashMap(); + Map map = new HashMap(); + map1.put("address", ByteArray.toHexString(fromAddress)); + map.put("account", map1); + map.put("offset", offset); + map.put("limit", limit); + String requestUrl = "http://" + httpSolidityNode + "/walletextension/gettransactionsfromthis"; + String jsonStr = new Gson().toJson(map); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + response = createConnect(requestUrl, jsonObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getTransactionsToThisFromSolidity( + String httpSolidityNode, byte[] toAddress, long offset, long limit) { + try { + Map map1 = new HashMap(); + Map map = new HashMap(); + map1.put("address", ByteArray.toHexString(toAddress)); + map.put("account", map1); + map.put("offset", offset); + map.put("limit", limit); + String requestUrl = "http://" + httpSolidityNode + "/walletextension/gettransactionstothis"; + String jsonStr = new Gson().toJson(map); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + response = createConnect(requestUrl, jsonObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAssetIssueByName(String httpNode, String name) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getassetissuebyname"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", str2hex(name)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAssetIssueByNameFromSolidity(String httpSolidityNode, String name) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuebyname"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", str2hex(name)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAssetIssueByNameFromPbft(String httpSolidityNode, String name) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getassetissuebyname"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", str2hex(name)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static Long getBalance(String httpNode, byte[] queryAddress) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getaccount"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseResponseContent(response); + // HttpMethed.printJsonContent(responseContent); + // httppost.releaseConnection(); + if (!responseContent.containsKey("balance")) { + return 0L; + } + return Long.parseLong(responseContent.get("balance").toString()); + } + + /** constructor. */ + public static HttpResponse getAccountNet(String httpNode, byte[] queryAddress) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getaccountnet"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAccountReource(String httpNode, byte[] queryAddress) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getaccountresource"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(queryAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAccountBalance( + String httpNode, byte[] queryAddress, Integer blockNum, String blockHash) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getaccountbalance"; + JsonObject addressObj = new JsonObject(); + addressObj.addProperty("address", Base58.encode58Check(queryAddress)); + JsonObject blockObj = new JsonObject(); + blockObj.addProperty("hash", blockHash); + blockObj.addProperty("number", blockNum); + JsonObject accountBalanceObj = new JsonObject(); + accountBalanceObj.add("account_identifier", addressObj); + accountBalanceObj.add("block_identifier", blockObj); + accountBalanceObj.addProperty("visible", true); + logger.info(accountBalanceObj.toString()); + response = createConnect(requestUrl, accountBalanceObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getBlockBalance(String httpNode, Integer blockNum, String blockHash) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getblockbalance"; + JsonObject blockObj = new JsonObject(); + blockObj.addProperty("hash", blockHash); + blockObj.addProperty("number", blockNum); + blockObj.addProperty("visible", true); + response = createConnect(requestUrl, blockObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static Long getBurnTrx(String httpNode) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getburntrx"; + JsonObject blockObj = new JsonObject(); + response = createConnect(requestUrl, blockObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseResponseContent(response); + return responseContent.getLong("burnTrxAmount"); + } + + /** constructor. */ + public static Long getBurnTrxFromSolidity(String httpNode) { + try { + final String requestUrl = "http://" + httpNode + "/walletsolidity/getburntrx"; + JsonObject blockObj = new JsonObject(); + response = createConnect(requestUrl, blockObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseResponseContent(response); + return responseContent.getLong("burnTrxAmount"); + } + + /** constructor. */ + public static Long getBurnTrxFromPbft(String httpNode) { + try { + final String requestUrl = "http://" + httpNode + "/walletpbft/getburntrx"; + JsonObject blockObj = new JsonObject(); + response = createConnect(requestUrl, blockObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseResponseContent(response); + return responseContent.getLong("burnTrxAmount"); + } + + /** constructor. */ + public static HttpResponse getNowBlock(String httpNode) { + return getNowBlock(httpNode, false); + } + + /** constructor. */ + public static HttpResponse getNowBlock(String httpNode, Boolean visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static Long getNowBlockNum(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return parseResponseContent(response) + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getLong("number"); + } + + /** constructor. */ + public static Long getNowBlockNumOnSolidity(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/walletsolidity/getnowblock"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return parseResponseContent(response) + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getLong("number"); + } + + /** constructor. */ + public static HttpResponse getNowBlockFromSolidity(String httpSolidityNode) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getnowblock"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getNowBlockFromPbft(String httpSolidityNode) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getnowblock"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static void waitToProduceOneBlock(String httpNode) { + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); + responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); + Integer currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); + Integer nextBlockNum = 0; + Integer times = 0; + while (nextBlockNum <= currentBlockNum + 1 && times++ <= 10) { + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + responseContent = + HttpMethed.parseStringContent(responseContent.get("block_header").toString()); + responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); + nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); + try { + Thread.sleep(1200); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + /** constructor. */ + public static void waitToProduceOneBlockFromSolidity(String httpNode, String httpSolidityNode) { + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); + responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); + Integer currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); + Integer nextBlockNum = 0; + Integer times = 0; + while (nextBlockNum <= currentBlockNum + && times++ <= ((getWitnessNum() >= 27) ? 27 : getWitnessNum() + 1)) { + response = HttpMethed.getNowBlockFromSolidity(httpSolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + responseContent = + HttpMethed.parseStringContent(responseContent.get("block_header").toString()); + responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); + nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); + try { + Thread.sleep(3500); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + logger.info("currentBlockNum2:" + currentBlockNum); + logger.info("nextBlockNum2:" + nextBlockNum); + } + + /** constructor. */ + public static void waitToProduceOneBlockFromPbft(String httpNode, String httpSolidityNode) { + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); + responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); + Integer currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); + Integer nextBlockNum = 0; + Integer times = 0; + while (nextBlockNum <= currentBlockNum && times++ <= 3) { + response = HttpMethed.getNowBlockFromPbft(httpSolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + responseContent = + HttpMethed.parseStringContent(responseContent.get("block_header").toString()); + responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); + nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); + try { + Thread.sleep(3500); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + /** constructor. */ + public static HttpResponse getBlockByNum(String httpNode, Integer blockNUm) { + return getBlockByNum(httpNode, blockNUm, false); + } + + /** constructor. */ + public static HttpResponse getBlockByNum(String httpNode, Integer blockNUm, Boolean visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getblockbynum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blockNUm); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static Long getBlockByNumForResponse(String httpNode, Integer blockNUm, Integer times) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getblockbynum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blockNUm); + Long duration = createConnectForResponse(requestUrl, userBaseObj2, times); + return duration; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return -1L; + } + } + + /** constructor. */ + public static HttpResponse getBlockByNumFromSolidity(String httpSolidityNode, Integer blockNum) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getblockbynum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blockNum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getBlockByNumFromPbft(String httpSolidityNode, Integer blockNum) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getblockbynum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blockNum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getBlockByLimitNext( + String httpNode, Integer startNum, Integer endNum) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getblockbylimitnext"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("startNum", startNum); + userBaseObj2.addProperty("endNum", endNum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getBlockByLimitNextFromSolidity( + String httpNode, Integer startNum, Integer endNum) { + try { + String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbylimitnext"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("startNum", startNum); + userBaseObj2.addProperty("endNum", endNum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getBlockByLimitNextFromPbft( + String httpNode, Integer startNum, Integer endNum) { + try { + String requestUrl = "http://" + httpNode + "/walletpbft/getblockbylimitnext"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("startNum", startNum); + userBaseObj2.addProperty("endNum", endNum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getBlockByLastNum(String httpNode, Integer num) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getblockbylatestnum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", num); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getBlockByLastNum2(String httpNode, Integer num) { + try { + String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbylatestnum2"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", num); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getBlockByLastNumFromSolidity(String httpNode, Integer num) { + try { + String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbylatestnum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", num); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getBlockByLastNumFromPbft(String httpNode, Integer num) { + try { + String requestUrl = "http://" + httpNode + "/walletpbft/getblockbylatestnum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", num); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + } + return response; + } + + /** constructor. */ + public static HttpResponse getBlockById(String httpNode, String blockId) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getblockbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", blockId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getBlockByIdFromSolidity(String httpNode, String blockId) { + try { + String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", blockId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getBlockByIdFromPbft(String httpNode, String blockId) { + try { + String requestUrl = "http://" + httpNode + "/walletpbft/getblockbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", blockId); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getDelegatedResource( + String httpNode, byte[] fromAddress, byte[] toAddress) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getdelegatedresource"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("fromAddress", ByteArray.toHexString(fromAddress)); + userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getDelegatedResourceFromSolidity( + String httpSolidityNode, byte[] fromAddress, byte[] toAddress) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getdelegatedresource"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("fromAddress", ByteArray.toHexString(fromAddress)); + userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getDelegatedResourceFromPbft( + String httpSolidityNode, byte[] fromAddress, byte[] toAddress) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getdelegatedresource"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("fromAddress", ByteArray.toHexString(fromAddress)); + userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getDelegatedResourceAccountIndex( + String httpNode, byte[] queryAddress) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getdelegatedresourceaccountindex"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", ByteArray.toHexString(queryAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getDelegatedResourceAccountIndexFromSolidity( + String httpSolidityNode, byte[] queryAddress) { + try { + String requestUrl = + "http://" + httpSolidityNode + "/walletsolidity/getdelegatedresourceaccountindex"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", ByteArray.toHexString(queryAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getDelegatedResourceAccountIndexFromPbft( + String httpSolidityNode, byte[] queryAddress) { + try { + String requestUrl = + "http://" + httpSolidityNode + "/walletpbft/getdelegatedresourceaccountindex"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", ByteArray.toHexString(queryAddress)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse createConnect(String url) { + return createConnect(url, null); + } + + /** constructor. */ + public static HttpResponse createConnect(String url, JsonObject requestBody) { + try { + httpClient + .getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + httppost = new HttpPost(url); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + if (requestBody != null) { + StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httppost.setEntity(entity); + } + + logger.info(httppost.toString()); + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse createConnectForGet(String url) { + try { + httpClient + .getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + HttpGet httppost; + httppost = new HttpGet(url); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + + logger.info(httppost.toString()); + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse createConnectForShieldTrc20(String url, JSONObject requestBody) { + try { + httpClient + .getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + httppost = new HttpPost(url); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + if (requestBody != null) { + StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httppost.setEntity(entity); + } + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static Long createConnectForResponse(String url, JsonObject requestBody, Integer times) { + try { + + Long start = 0L; + Long end = 0L; + Long duration = 0L; + while (times-- > 0) { + httpClient + .getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + httppost = new HttpPost(url); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + if (requestBody != null) { + StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httppost.setEntity(entity); + } + + start = System.currentTimeMillis(); + response = httpClient.execute(httppost); /* responseContent = HttpMethed.parseResponseContent(response); logger.info(responseContent.toString());*/ - end = System.currentTimeMillis(); - duration = duration + end - start; - httppost.releaseConnection(); - } - return duration; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return -1L; - } - } - - - /** - * constructor. - */ - public static HttpResponse createConnect1(String url, JSONObject requestBody) { - try { - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout * 10000); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout * 10000); - httppost = new HttpPost(url); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - if (requestBody != null) { - StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); - entity.setContentEncoding("UTF-8"); - entity.setContentType("application/json"); - httppost.setEntity(entity); - } - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getAssetissueList(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getassetissuelist"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static Long getAssetIssueValue(String httpNode, byte[] accountAddress, - String assetIssueId) { - response = HttpMethed.getAccount(httpNode, accountAddress); - responseContent = HttpMethed.parseResponseContent(response); - JSONArray assetV2 = responseContent.getJSONArray("assetV2"); - if (assetV2 != null && assetV2.size() > 0) { - for (int i = 0; i < assetV2.size(); i++) { - String assetString = assetV2.get(i).toString(); - logger.info("assetString:" + assetString); - String assetKey = HttpMethed.parseStringContent(assetString).getString("key"); - if (assetKey.equals(assetIssueId)) { - return HttpMethed.parseStringContent(assetString).getLong("value"); - } - } - } - return 0L; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueListFromSolidity(String httpSolidityNode) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuelist"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAssetIssueListFromPbft(String httpSolidityNode) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getassetissuelist"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getPaginatedAssetissueList(String httpNode, Integer offset, - Integer limit) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getpaginatedassetissuelist"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("offset", offset); - userBaseObj2.addProperty("limit", limit); - userBaseObj2.addProperty("visible", "true"); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getPaginatedAssetissueListFromSolidity(String httpSolidityNode, - Integer offset, Integer limit) { - try { - String requestUrl = - "http://" + httpSolidityNode + "/walletsolidity/getpaginatedassetissuelist"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("offset", offset); - userBaseObj2.addProperty("limit", limit); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getPaginatedAssetissueListFromPbft(String httpSolidityNode, - Integer offset, Integer limit) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getpaginatedassetissuelist"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("offset", offset); - userBaseObj2.addProperty("limit", limit); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getPaginatedProposalList(String httpNode, Integer offset, - Integer limit) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getpaginatedproposallist"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("offset", offset); - userBaseObj2.addProperty("limit", limit); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getPaginatedExchangeList(String httpNode, Integer offset, - Integer limit) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getpaginatedexchangelist"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("offset", offset); - userBaseObj2.addProperty("limit", limit); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse updateSetting(String httpNode, byte[] ownerAddress, - String contractAddress, Integer consumeUserResourcePercent, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/updatesetting"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("contract_address", contractAddress); - userBaseObj2.addProperty("consume_user_resource_percent", consumeUserResourcePercent); - logger.info(userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse updateEnergyLimit(String httpNode, byte[] ownerAddress, - String contractAddress, Integer originEnergyLimit, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/updateenergylimit"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("contract_address", contractAddress); - userBaseObj2.addProperty("origin_energy_limit", originEnergyLimit); - logger.info(userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse createAddress(String httpNode, String value) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createaddress"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", str2hex(value)); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse generateAddress(String httpNode) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/generateaddress"; - JsonObject userBaseObj2 = new JsonObject(); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTransactionCountByBlocknum(String httpNode, long blocknum) { - try { - String requestUrl = - "http://" + httpNode + "/wallet/gettransactioncountbyblocknum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blocknum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse validateAddress(String httpNode, String address) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/validateaddress"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", address); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse easyTransfer(String httpNode, String value, byte[] toAddress, - Long amount) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/easytransfer"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("passPhrase", str2hex(value)); - userBaseObj2.addProperty("amount", amount); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse easyTransferByPrivate(String httpNode, String privateKey, - byte[] toAddress, Long amount) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/easytransferbyprivate"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("privateKey", privateKey); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("amount", amount); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse easyTransferAsset(String httpNode, String value, byte[] toAddress, - Long amount, String assetId) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/easytransferasset"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("passPhrase", str2hex(value)); - userBaseObj2.addProperty("amount", amount); - userBaseObj2.addProperty("assetId", assetId); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse easyTransferAssetByPrivate(String httpNode, String privateKey, - byte[] toAddress, Long amount, String assetId) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/easytransferassetbyprivate"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("privateKey", privateKey); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("amount", amount); - userBaseObj2.addProperty("assetId", assetId); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getContractInfo(String httpNode, String contractAddress) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getcontractinfo"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", contractAddress); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static void disConnect() { + end = System.currentTimeMillis(); + duration = duration + end - start; httppost.releaseConnection(); - } - - /** - * constructor. - */ - public static JSONObject parseResponseContent(HttpResponse response) { - try { - String result = EntityUtils.toString(response.getEntity()); - StringEntity entity = new StringEntity(result, Charset.forName("UTF-8")); - response.setEntity(entity); - JSONObject obj = JSONObject.parseObject(result); - return obj; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /** - * constructor. - */ - public static List parseResponseContentArray(HttpResponse response) { - try { - String result = EntityUtils.toString(response.getEntity()); - StringEntity entity = new StringEntity(result, Charset.forName("UTF-8")); - response.setEntity(entity); - List list = new ArrayList(); - JSONArray objects = JSONArray.parseArray(result); - for (int i = 0; i < objects.size(); i++) { - list.add(objects.getJSONObject(i)); - } - return list; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /** - * constructor. - */ - public static JSONObject parseStringContent(String content) { - try { - JSONObject obj = JSONObject.parseObject(content); - return obj; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /** - * constructor. - */ - public static void printJsonContent(JSONObject responseContent) { - logger.info("----------------------------Print JSON Start---------------------------"); - for (String str : responseContent.keySet()) { - logger.info(str + ":" + responseContent.get(str)); - } - logger.info("JSON content size are: " + responseContent.size()); - logger.info("----------------------------Print JSON End-----------------------------"); - } - - /** - * constructor. - */ - public static String str2hex(String str) { - char[] chars = "0123456789ABCDEF".toCharArray(); - StringBuilder sb = new StringBuilder(); - byte[] bs = str.getBytes(); - int bit; - for (int i = 0; i < bs.length; i++) { - bit = (bs[i] & 0x0f0) >> 4; - sb.append(chars[bit]); - bit = bs[i] & 0x0f; - sb.append(chars[bit]); - // sb.append(' '); - } - return sb.toString().trim(); - } - - - /** - * constructor. - */ - public static HttpResponse clearABiGetTxid(String httpNode, byte[] ownerAddress, - String contractAddress, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/clearabi"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("contract_address", contractAddress); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - - - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static Optional generateShieldAddress(String httpnode) { - ShieldAddressInfo addressInfo = new ShieldAddressInfo(); - String sk; - String d; - String ask; - String nsk; - String ovk; - String ak; - String nk; - String ivk; - String pkD; - try { - response = HttpMethed.getSpendingKey(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - sk = responseContent.getString("value"); - - response = HttpMethed.getDiversifier(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - d = responseContent.getString("d"); - - response = HttpMethed.getExpandedSpendingKey(httpnode, sk); - responseContent = HttpMethed.parseResponseContent(response); - ask = responseContent.getString("ask"); - nsk = responseContent.getString("nsk"); - ovk = responseContent.getString("ovk"); - - response = HttpMethed.getAkFromAsk(httpnode, ask); - responseContent = HttpMethed.parseResponseContent(response); - ak = responseContent.getString("value"); - - response = HttpMethed.getNkFromNsk(httpnode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - nk = responseContent.getString("value"); - - response = HttpMethed.getIncomingViewingKey(httpnode, ak, nk); - responseContent = HttpMethed.parseResponseContent(response); - ivk = responseContent.getString("ivk"); - - response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d); - responseContent = HttpMethed.parseResponseContent(response); - pkD = responseContent.getString("pkD"); - - addressInfo.setSk(ByteArray.fromHexString(sk)); - addressInfo.setD(new DiversifierT(ByteArray.fromHexString(d))); - addressInfo.setIvk(ByteArray.fromHexString(ivk)); - addressInfo.setOvk(ByteArray.fromHexString(ovk)); - addressInfo.setPkD(ByteArray.fromHexString(pkD)); - logger.info("sk:" + sk); - - if (addressInfo.validateCheck()) { - return Optional.of(addressInfo); - } - } catch (Exception e) { - e.printStackTrace(); - } - - return Optional.empty(); - } - - /** - * constructor. - */ - public static List addShieldOutputList(String httpNode, - List shieldOutList, String shieldToAddress, String toAmountString, - String menoString) { - String shieldAddress = shieldToAddress; - String amountString = toAmountString; - if (menoString.equals("null")) { - menoString = ""; - } - long shieldAmount = 0; - if (!StringUtil.isNullOrEmpty(amountString)) { - shieldAmount = Long.valueOf(amountString); - } + } + return duration; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return -1L; + } + } + + /** constructor. */ + public static HttpResponse createConnect1(String url, JSONObject requestBody) { + try { + httpClient + .getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + httpClient + .getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout * 10000); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout * 10000); + httppost = new HttpPost(url); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + if (requestBody != null) { + StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httppost.setEntity(entity); + } + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAssetissueList(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getassetissuelist"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static Long getAssetIssueValue( + String httpNode, byte[] accountAddress, String assetIssueId) { + response = HttpMethed.getAccount(httpNode, accountAddress); + responseContent = HttpMethed.parseResponseContent(response); + JSONArray assetV2 = responseContent.getJSONArray("assetV2"); + if (assetV2 != null && assetV2.size() > 0) { + for (int i = 0; i < assetV2.size(); i++) { + String assetString = assetV2.get(i).toString(); + logger.info("assetString:" + assetString); + String assetKey = HttpMethed.parseStringContent(assetString).getString("key"); + if (assetKey.equals(assetIssueId)) { + return HttpMethed.parseStringContent(assetString).getLong("value"); + } + } + } + return 0L; + } + + /** constructor. */ + public static HttpResponse getAssetIssueListFromSolidity(String httpSolidityNode) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuelist"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAssetIssueListFromPbft(String httpSolidityNode) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getassetissuelist"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getPaginatedAssetissueList( + String httpNode, Integer offset, Integer limit) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getpaginatedassetissuelist"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("offset", offset); + userBaseObj2.addProperty("limit", limit); + userBaseObj2.addProperty("visible", "true"); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getPaginatedAssetissueListFromSolidity( + String httpSolidityNode, Integer offset, Integer limit) { + try { + String requestUrl = + "http://" + httpSolidityNode + "/walletsolidity/getpaginatedassetissuelist"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("offset", offset); + userBaseObj2.addProperty("limit", limit); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getPaginatedAssetissueListFromPbft( + String httpSolidityNode, Integer offset, Integer limit) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getpaginatedassetissuelist"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("offset", offset); + userBaseObj2.addProperty("limit", limit); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getPaginatedProposalList( + String httpNode, Integer offset, Integer limit) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getpaginatedproposallist"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("offset", offset); + userBaseObj2.addProperty("limit", limit); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getPaginatedExchangeList( + String httpNode, Integer offset, Integer limit) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getpaginatedexchangelist"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("offset", offset); + userBaseObj2.addProperty("limit", limit); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse updateSetting( + String httpNode, + byte[] ownerAddress, + String contractAddress, + Integer consumeUserResourcePercent, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/updatesetting"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("consume_user_resource_percent", consumeUserResourcePercent); + logger.info(userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse updateEnergyLimit( + String httpNode, + byte[] ownerAddress, + String contractAddress, + Integer originEnergyLimit, + String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/updateenergylimit"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + userBaseObj2.addProperty("origin_energy_limit", originEnergyLimit); + logger.info(userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + logger.info(transactionString); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse createAddress(String httpNode, String value) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createaddress"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", str2hex(value)); + response = createConnect(requestUrl, userBaseObj2); + logger.info(userBaseObj2.toString()); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse generateAddress(String httpNode) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/generateaddress"; + JsonObject userBaseObj2 = new JsonObject(); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getTransactionCountByBlocknum(String httpNode, long blocknum) { + try { + String requestUrl = "http://" + httpNode + "/wallet/gettransactioncountbyblocknum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blocknum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse validateAddress(String httpNode, String address) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/validateaddress"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", address); + response = createConnect(requestUrl, userBaseObj2); + logger.info(userBaseObj2.toString()); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse easyTransfer( + String httpNode, String value, byte[] toAddress, Long amount) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/easytransfer"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("passPhrase", str2hex(value)); + userBaseObj2.addProperty("amount", amount); + response = createConnect(requestUrl, userBaseObj2); + logger.info(userBaseObj2.toString()); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse easyTransferByPrivate( + String httpNode, String privateKey, byte[] toAddress, Long amount) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/easytransferbyprivate"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("privateKey", privateKey); + userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("amount", amount); + response = createConnect(requestUrl, userBaseObj2); + logger.info(userBaseObj2.toString()); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse easyTransferAsset( + String httpNode, String value, byte[] toAddress, Long amount, String assetId) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/easytransferasset"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("passPhrase", str2hex(value)); + userBaseObj2.addProperty("amount", amount); + userBaseObj2.addProperty("assetId", assetId); + response = createConnect(requestUrl, userBaseObj2); + logger.info(userBaseObj2.toString()); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse easyTransferAssetByPrivate( + String httpNode, String privateKey, byte[] toAddress, Long amount, String assetId) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/easytransferassetbyprivate"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("privateKey", privateKey); + userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); + userBaseObj2.addProperty("amount", amount); + userBaseObj2.addProperty("assetId", assetId); + response = createConnect(requestUrl, userBaseObj2); + logger.info(userBaseObj2.toString()); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getContractInfo(String httpNode, String contractAddress) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getcontractinfo"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", contractAddress); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static void disConnect() { + httppost.releaseConnection(); + } + + /** constructor. */ + public static JSONObject parseResponseContent(HttpResponse response) { + try { + String result = EntityUtils.toString(response.getEntity()); + StringEntity entity = new StringEntity(result, Charset.forName("UTF-8")); + response.setEntity(entity); + JSONObject obj = JSONObject.parseObject(result); + return obj; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** constructor. */ + public static List parseResponseContentArray(HttpResponse response) { + try { + String result = EntityUtils.toString(response.getEntity()); + StringEntity entity = new StringEntity(result, Charset.forName("UTF-8")); + response.setEntity(entity); + List list = new ArrayList(); + JSONArray objects = JSONArray.parseArray(result); + for (int i = 0; i < objects.size(); i++) { + list.add(objects.getJSONObject(i)); + } + return list; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** constructor. */ + public static JSONObject parseStringContent(String content) { + try { + JSONObject obj = JSONObject.parseObject(content); + return obj; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** constructor. */ + public static void printJsonContent(JSONObject responseContent) { + logger.info("----------------------------Print JSON Start---------------------------"); + for (String str : responseContent.keySet()) { + logger.info(str + ":" + responseContent.get(str)); + } + logger.info("JSON content size are: " + responseContent.size()); + logger.info("----------------------------Print JSON End-----------------------------"); + } + + /** constructor. */ + public static String str2hex(String str) { + char[] chars = "0123456789ABCDEF".toCharArray(); + StringBuilder sb = new StringBuilder(); + byte[] bs = str.getBytes(); + int bit; + for (int i = 0; i < bs.length; i++) { + bit = (bs[i] & 0x0f0) >> 4; + sb.append(chars[bit]); + bit = bs[i] & 0x0f; + sb.append(chars[bit]); + // sb.append(' '); + } + return sb.toString().trim(); + } + + /** constructor. */ + public static HttpResponse clearABiGetTxid( + String httpNode, byte[] ownerAddress, String contractAddress, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/clearabi"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("contract_address", contractAddress); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); - GrpcAPI.Note.Builder noteBuild = GrpcAPI.Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setValue(shieldAmount); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = HttpMethed.getRcm(httpNode); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static Optional generateShieldAddress(String httpnode) { + ShieldAddressInfo addressInfo = new ShieldAddressInfo(); + String sk; + String d; + String ask; + String nsk; + String ovk; + String ak; + String nk; + String ivk; + String pkD; + try { + response = HttpMethed.getSpendingKey(httpnode); + responseContent = HttpMethed.parseResponseContent(response); + sk = responseContent.getString("value"); + + response = HttpMethed.getDiversifier(httpnode); + responseContent = HttpMethed.parseResponseContent(response); + d = responseContent.getString("d"); + + response = HttpMethed.getExpandedSpendingKey(httpnode, sk); + responseContent = HttpMethed.parseResponseContent(response); + ask = responseContent.getString("ask"); + nsk = responseContent.getString("nsk"); + ovk = responseContent.getString("ovk"); + + response = HttpMethed.getAkFromAsk(httpnode, ask); + responseContent = HttpMethed.parseResponseContent(response); + ak = responseContent.getString("value"); + + response = HttpMethed.getNkFromNsk(httpnode, nsk); + responseContent = HttpMethed.parseResponseContent(response); + nk = responseContent.getString("value"); + + response = HttpMethed.getIncomingViewingKey(httpnode, ak, nk); + responseContent = HttpMethed.parseResponseContent(response); + ivk = responseContent.getString("ivk"); + + response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d); + responseContent = HttpMethed.parseResponseContent(response); + pkD = responseContent.getString("pkD"); + + addressInfo.setSk(ByteArray.fromHexString(sk)); + addressInfo.setD(new DiversifierT(ByteArray.fromHexString(d))); + addressInfo.setIvk(ByteArray.fromHexString(ivk)); + addressInfo.setOvk(ByteArray.fromHexString(ovk)); + addressInfo.setPkD(ByteArray.fromHexString(pkD)); + logger.info("sk:" + sk); + + if (addressInfo.validateCheck()) { + return Optional.of(addressInfo); + } + } catch (Exception e) { + e.printStackTrace(); + } + + return Optional.empty(); + } + + /** constructor. */ + public static List addShieldOutputList( + String httpNode, + List shieldOutList, + String shieldToAddress, + String toAmountString, + String menoString) { + String shieldAddress = shieldToAddress; + String amountString = toAmountString; + if (menoString.equals("null")) { + menoString = ""; + } + long shieldAmount = 0; + if (!StringUtil.isNullOrEmpty(amountString)) { + shieldAmount = Long.valueOf(amountString); + } + + GrpcAPI.Note.Builder noteBuild = GrpcAPI.Note.newBuilder(); + noteBuild.setPaymentAddress(shieldAddress); + noteBuild.setPaymentAddress(shieldAddress); + noteBuild.setValue(shieldAmount); + + response = HttpMethed.getRcm(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + String rcm = responseContent.getString("value"); + + noteBuild.setRcm(ByteString.copyFrom(rcm.getBytes())); + noteBuild.setMemo(ByteString.copyFrom(menoString.getBytes())); + shieldOutList.add(noteBuild.build()); + return shieldOutList; + } + + /** constructor. */ + public static HttpResponse getSpendingKey(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getspendingkey"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getDiversifier(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getdiversifier"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getRcm(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getrcm"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getExpandedSpendingKey(String httpNode, String spendingKey) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getexpandedspendingkey"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", spendingKey); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getAkFromAsk(String httpNode, String ask) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getakfromask"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", ask); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getNkFromNsk(String httpNode, String nsk) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getnkfromnsk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", nsk); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getIncomingViewingKey(String httpNode, String ak, String nk) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getincomingviewingkey"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("ak", ak); + userBaseObj2.addProperty("nk", nk); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getNewShieldedAddress(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getnewshieldedaddress"; + response = createConnect(requestUrl); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getZenPaymentAddress(String httpNode, String ivk, String d) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getzenpaymentaddress"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("ivk", ivk); + userBaseObj2.addProperty("d", d); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getMerkleTreeVoucherInfo( + String httpNode, String hash, Integer index, int blockNum) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getmerkletreevoucherinfo"; + JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); + jsonObjectWarp + .put( + "out_points", + Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) + .put("block_num", blockNum); + String jsonStr = jsonObjectWarp.toJSONString(); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + logger.info("jsonObj:" + jsonObj.toString()); + response = createConnect(requestUrl, jsonObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getMerkleTreeVoucherInfoFromSolidity( + String httpSolidityNode, String hash, Integer index, int blockNum) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmerkletreevoucherinfo"; + JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); + jsonObjectWarp + .put( + "out_points", + Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) + .put("block_num", blockNum); + String jsonStr = jsonObjectWarp.toJSONString(); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + logger.info("jsonObj:" + jsonObj.toString()); + response = createConnect(requestUrl, jsonObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getMerkleTreeVoucherInfoFromPbft( + String httpSolidityNode, String hash, Integer index, int blockNum) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getmerkletreevoucherinfo"; + JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); + jsonObjectWarp + .put( + "out_points", + Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) + .put("block_num", blockNum); + String jsonStr = jsonObjectWarp.toJSONString(); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + logger.info("jsonObj:" + jsonObj.toString()); + response = createConnect(requestUrl, jsonObj); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse sendShieldCoin( + String httpNode, + byte[] publicZenTokenOwnerAddress, + long fromAmount, + ShieldAddressInfo shieldAddressInfo, + ShieldNoteInfo noteTx, + List shieldOutputList, + byte[] publicZenTokenToAddress, + long toAmount, + String zenTokenOwnerKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/createshieldedtransaction"; + + Map map = new HashMap(); + if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { + map.put("transparent_from_address", ByteArray.toHexString(publicZenTokenOwnerAddress)); + map.put("from_amount", fromAmount); + } + if (shieldAddressInfo != null) { + HttpResponse expandedSpendingKey = + HttpMethed.getExpandedSpendingKey( + httpNode, ByteArray.toHexString(shieldAddressInfo.getSk())); + responseContent = HttpMethed.parseResponseContent(expandedSpendingKey); + HttpMethed.printJsonContent(responseContent); + String ovk = responseContent.getString("ovk"); + map.put("ask", responseContent.getString("ask")); + map.put("nsk", responseContent.getString("nsk")); + map.put("ovk", ovk); + + response = + HttpMethed.getMerkleTreeVoucherInfo(httpNode, noteTx.getTrxId(), noteTx.getIndex(), 1); responseContent = HttpMethed.parseResponseContent(response); - String rcm = responseContent.getString("value"); - - noteBuild.setRcm(ByteString.copyFrom(rcm.getBytes())); - noteBuild.setMemo(ByteString.copyFrom(menoString.getBytes())); - shieldOutList.add(noteBuild.build()); - return shieldOutList; - } - - /** - * constructor. - */ - public static HttpResponse getSpendingKey(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getspendingkey"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getDiversifier(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getdiversifier"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getRcm(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getrcm"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getExpandedSpendingKey(String httpNode, String spendingKey) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getexpandedspendingkey"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", spendingKey); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getAkFromAsk(String httpNode, String ask) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getakfromask"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", ask); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getNkFromNsk(String httpNode, String nsk) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnkfromnsk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", nsk); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getIncomingViewingKey(String httpNode, String ak, String nk) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getincomingviewingkey"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("ak", ak); - userBaseObj2.addProperty("nk", nk); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getNewShieldedAddress(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnewshieldedaddress"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getZenPaymentAddress(String httpNode, String ivk, String d) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getzenpaymentaddress"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("ivk", ivk); - userBaseObj2.addProperty("d", d); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMerkleTreeVoucherInfo(String httpNode, String hash, Integer index, - int blockNum) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getmerkletreevoucherinfo"; - JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); - jsonObjectWarp.put("out_points", - Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) - .put("block_num", blockNum); - String jsonStr = jsonObjectWarp.toJSONString(); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - logger.info("jsonObj:" + jsonObj.toString()); - response = createConnect(requestUrl, jsonObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMerkleTreeVoucherInfoFromSolidity(String httpSolidityNode, - String hash, Integer index, int blockNum) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmerkletreevoucherinfo"; - JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); - jsonObjectWarp.put("out_points", - Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) - .put("block_num", blockNum); - String jsonStr = jsonObjectWarp.toJSONString(); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - logger.info("jsonObj:" + jsonObj.toString()); - response = createConnect(requestUrl, jsonObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMerkleTreeVoucherInfoFromPbft(String httpSolidityNode, String hash, - Integer index, int blockNum) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getmerkletreevoucherinfo"; - JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); - jsonObjectWarp.put("out_points", - Lists.newArrayList(new JSONObjectWarp().put("hash", hash).put("index", index))) - .put("block_num", blockNum); - String jsonStr = jsonObjectWarp.toJSONString(); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - logger.info("jsonObj:" + jsonObj.toString()); - response = createConnect(requestUrl, jsonObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse sendShieldCoin(String httpNode, byte[] publicZenTokenOwnerAddress, - long fromAmount, ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx, - List shieldOutputList, byte[] publicZenTokenToAddress, long toAmount, - String zenTokenOwnerKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createshieldedtransaction"; - - Map map = new HashMap(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - map.put("transparent_from_address", ByteArray.toHexString(publicZenTokenOwnerAddress)); - map.put("from_amount", fromAmount); - } - if (shieldAddressInfo != null) { - HttpResponse expandedSpendingKey = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.getSk())); - responseContent = HttpMethed.parseResponseContent(expandedSpendingKey); - HttpMethed.printJsonContent(responseContent); - String ovk = responseContent.getString("ovk"); - map.put("ask", responseContent.getString("ask")); - map.put("nsk", responseContent.getString("nsk")); - map.put("ovk", ovk); - - response = HttpMethed - .getMerkleTreeVoucherInfo(httpNode, noteTx.getTrxId(), noteTx.getIndex(), 1); - responseContent = HttpMethed.parseResponseContent(response); - JSONArray vouchers = responseContent.getJSONArray("vouchers"); - JSONArray paths = responseContent.getJSONArray("paths"); - - List shieldedSpends = Lists.newArrayList(new JSONObjectWarp().put("note", - new JSONObjectWarp().put("value", noteTx.getValue()) - .put("payment_address", noteTx.getPaymentAddress()) - .put("rcm", ByteArray.toHexString(noteTx.getR())) - .put("memo", ByteArray.toHexString(noteTx.getMemo()))) - .put("alpha", ByteArray.toHexString(org.tron.core.zen.note.Note.generateR())) - .put("voucher", Lists.newArrayList(vouchers)).put("path", Lists.newArrayList(paths))); - - map.put("shielded_spends", shieldedSpends); - } else { - map.put("ovk", "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - } - - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - map.put("transparent_to_address", ByteArray.toHexString(publicZenTokenToAddress)); - map.put("to_amount", toAmount); - } - - if (shieldOutputList.size() > 0) { - ArrayList noteList = new ArrayList<>(); - for (int i = 0; i < shieldOutputList.size(); ++i) { - - Map noteInfo = new HashMap(); - noteInfo.put("value", shieldOutputList.get(i).getValue()); - noteInfo.put("payment_address", shieldOutputList.get(i).getPaymentAddress()); - noteInfo.put("rcm", shieldOutputList.get(i).getRcm().toStringUtf8()); - noteInfo.put("memo", - ByteArray.toHexString(shieldOutputList.get(i).getMemo().toStringUtf8().getBytes())); - final Map note = new HashMap(); - note.put("note", noteInfo); - noteList.add(note); - } - map.put("shielded_receives", noteList); - } - - String jsonStr = new Gson().toJson(map); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - logger.info("jsonObj:" + jsonObj.toString()); - response = createConnect(requestUrl, jsonObj); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - transactionSignString = gettransactionsign(httpNode, transactionString, zenTokenOwnerKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } else { - response = broadcastTransaction(httpNode, transactionString); - } - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static Boolean getSpendResult(String httpNode, ShieldAddressInfo shieldAddressInfo, - ShieldNoteInfo noteTx) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/isspend"; - - response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); - responseContent = HttpMethed.parseResponseContent(response); - String ask = responseContent.getString("ask"); - response = HttpMethed.getAkFromAsk(httpNode, ask); - responseContent = HttpMethed.parseResponseContent(response); - JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); - jsonObjectWarp.put("ak", responseContent.getString("value")); - - String nsk = responseContent.getString("nsk"); - response = HttpMethed.getNkFromNsk(httpNode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - jsonObjectWarp.put("nk", responseContent.getString("value")); - - jsonObjectWarp.put("note", new JSONObjectWarp().put("value", noteTx.getValue()) - .put("payment_address", noteTx.getPaymentAddress()) - .put("rcm", ByteArray.toHexString(noteTx.getR())) - .put("memo", ByteArray.toHexString(noteTx.getMemo()))).put("txid", noteTx.getTrxId()); - - String jsonStr = jsonObjectWarp.toJSONString(); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - logger.info("jsonObj:" + jsonObj.toString()); - HttpMethed.response = createConnect(requestUrl, jsonObj); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String jsonString = responseContent.toJSONString(); - if (jsonString.contains("result") && (responseContent.getString("result").equals("true") - && responseContent.getString("message").equals("Input note has been spent"))) { - return Boolean.TRUE; - } else { - return Boolean.FALSE; - } - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static Boolean getSpendResultFromSolidity(String httpNode, String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx) { - try { - final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/isspend"; - - response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); - responseContent = HttpMethed.parseResponseContent(response); - String ask = responseContent.getString("ask"); - response = HttpMethed.getAkFromAsk(httpNode, ask); - responseContent = HttpMethed.parseResponseContent(response); - JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); - jsonObjectWarp.put("ak", responseContent.getString("value")); - - String nsk = responseContent.getString("nsk"); - response = HttpMethed.getNkFromNsk(httpNode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - jsonObjectWarp.put("nk", responseContent.getString("value")); - - jsonObjectWarp.put("note", new JSONObjectWarp().put("value", noteTx.getValue()) - .put("payment_address", noteTx.getPaymentAddress()) - .put("rcm", ByteArray.toHexString(noteTx.getR())) - .put("memo", ByteArray.toHexString(noteTx.getMemo()))).put("txid", noteTx.getTrxId()); - - String jsonStr = jsonObjectWarp.toJSONString(); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - logger.info("jsonObj:" + jsonObj.toString()); - HttpMethed.response = createConnect(requestUrl, jsonObj); - responseContent = HttpMethed.parseResponseContent(response); - - HttpMethed.printJsonContent(responseContent); - String jsonString = responseContent.toJSONString(); - if (jsonString.contains("result") && (responseContent.getString("result").equals("true") - && responseContent.getString("message").equals("Input note has been spent"))) { - return Boolean.TRUE; - } else { - return Boolean.FALSE; - } - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static Boolean getSpendResultFromPbft(String httpNode, String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx) { - try { - final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/isspend"; - final JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); - - response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); - responseContent = HttpMethed.parseResponseContent(response); - String ask = responseContent.getString("ask"); - final String nsk = responseContent.getString("nsk"); - response = HttpMethed.getAkFromAsk(httpNode, ask); - responseContent = HttpMethed.parseResponseContent(response); - jsonObjectWarp.put("ak", responseContent.getString("value")); - response = HttpMethed.getNkFromNsk(httpNode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - jsonObjectWarp.put("nk", responseContent.getString("value")); - jsonObjectWarp.put("note", new JSONObjectWarp().put("value", noteTx.getValue()) - .put("payment_address", noteTx.getPaymentAddress()) - .put("rcm", ByteArray.toHexString(noteTx.getR())) - .put("memo", ByteArray.toHexString(noteTx.getMemo()))).put("txid", noteTx.getTrxId()); - String jsonStr = jsonObjectWarp.toJSONString(); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - logger.info("jsonObj:" + jsonObj.toString()); - HttpMethed.response = createConnect(requestUrl, jsonObj); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String jsonString = responseContent.toJSONString(); - if (jsonString.contains("result") && (responseContent.getString("result").equals("true") - && responseContent.getString("message").equals("Input note has been spent"))) { - return Boolean.TRUE; - } else { - return Boolean.FALSE; - } - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static List scanNoteByOvkFromPbft(String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed.getNowBlockFromPbft(httpSolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - - final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/scannotebyovk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ovk", ByteArray.toHexString(shieldAddressInfo.getOvk())); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(0).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - - /** - * constructor. - */ - public static List scanNoteByIvk(String httpNode, - ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - - final String requestUrl = "http://" + httpNode + "/wallet/scannotebyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - if (jsonArray != null) { - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(i).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static List scanNoteByIvkFromSolidity(String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed.getNowBlockFromSolidity(httpSolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - - final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/scannotebyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(i).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static List scanNoteByIvkFromPbft(String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed.getNowBlockFromPbft(httpSolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - - final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/scannotebyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(i).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - - /** - * constructor. - */ - public static List scanAndMarkNoteByIvk(String httpNode, - ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); - responseContent = HttpMethed.parseResponseContent(response); - String ask = responseContent.getString("ask"); - String nsk = responseContent.getString("nsk"); - response = HttpMethed.getAkFromAsk(httpNode, ask); - responseContent = HttpMethed.parseResponseContent(response); - final String ak = responseContent.getString("value"); - - response = HttpMethed.getNkFromNsk(httpNode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - final String nk = responseContent.getString("value"); - - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - - final String requestUrl = "http://" + httpNode + "/wallet/scanandmarknotebyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); - userBaseObj2.addProperty("ak", ak); - userBaseObj2.addProperty("nk", nk); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - logger.info("jsonArray:" + jsonArray.toJSONString()); - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(i).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIsSpend(HttpMethed.parseStringContent(noteTxs).getBoolean("is_spend")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static List scanAndMarkNoteByIvkFromSolidity(String httpNode, - String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); - responseContent = HttpMethed.parseResponseContent(response); - String ask = responseContent.getString("ask"); - String nsk = responseContent.getString("nsk"); - response = HttpMethed.getAkFromAsk(httpNode, ask); - responseContent = HttpMethed.parseResponseContent(response); - final String ak = responseContent.getString("value"); - - response = HttpMethed.getNkFromNsk(httpNode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - final String nk = responseContent.getString("value"); - - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - - final String requestUrl = - "http://" + httpSolidityNode + "/walletsolidity/scanandmarknotebyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); - userBaseObj2.addProperty("ak", ak); - userBaseObj2.addProperty("nk", nk); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - logger.info("jsonArray:" + jsonArray.toJSONString()); - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(i).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIsSpend(HttpMethed.parseStringContent(noteTxs).getBoolean("is_spend")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static List scanAndMarkNoteByIvkFromPbft(String httpNode, - String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); - responseContent = HttpMethed.parseResponseContent(response); - String ask = responseContent.getString("ask"); - String nsk = responseContent.getString("nsk"); - response = HttpMethed.getAkFromAsk(httpNode, ask); - responseContent = HttpMethed.parseResponseContent(response); - final String ak = responseContent.getString("value"); - - response = HttpMethed.getNkFromNsk(httpNode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - final String nk = responseContent.getString("value"); - - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/scanandmarknotebyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); - userBaseObj2.addProperty("ak", ak); - userBaseObj2.addProperty("nk", nk); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - logger.info("jsonArray:" + jsonArray.toJSONString()); - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(i).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIsSpend(HttpMethed.parseStringContent(noteTxs).getBoolean("is_spend")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - - /** - * constructor. - */ - public static List scanNoteByOvk(String httpNode, - ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed.getNowBlock(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - - final String requestUrl = "http://" + httpNode + "/wallet/scannotebyovk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ovk", ByteArray.toHexString(shieldAddressInfo.getOvk())); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(i).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static List scanNoteByOvkFromSolidity(String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo) { - try { - response = HttpMethed.getNowBlockFromSolidity(httpSolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); - Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); - Integer startBlockNum = 0; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - - final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/scannotebyovk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startBlockNum); - userBaseObj2.addProperty("end_block_index", currentBlockNum); - userBaseObj2.addProperty("ovk", ByteArray.toHexString(shieldAddressInfo.getOvk())); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - List shieldNoteInfoList = new ArrayList<>(); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - for (int i = 0; i < jsonArray.size(); i++) { - ShieldNoteInfo noteTx = new ShieldNoteInfo(); - String noteTxs = jsonArray.get(0).toString(); - String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); - noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); - noteTx.setPaymentAddress( - HttpMethed.parseStringContent(noteString).getString("payment_address")); - noteTx.setR( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); - noteTx.setMemo( - ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); - noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); - noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); - shieldNoteInfoList.add(noteTx); - } - return shieldNoteInfoList; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String httpSolidityNode, - String httpPbftNode, byte[] publicZenTokenOwnerAddress, long fromAmount, - ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx, - List shieldOutputList, byte[] publicZenTokenToAddress, long toAmount, - String zenTokenOwnerKey) { - try { - final String requestUrl = - "http://" + httpNode + "/wallet/createshieldedtransactionwithoutspendauthsig"; - - Map map = new HashMap(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - map.put("transparent_from_address", ByteArray.toHexString(publicZenTokenOwnerAddress)); - map.put("from_amount", fromAmount); - } - String ask = ""; - byte[] alpha = null; - if (shieldAddressInfo != null) { - HttpResponse expandedSpendingKey = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.getSk())); - responseContent = HttpMethed.parseResponseContent(expandedSpendingKey); - HttpMethed.printJsonContent(responseContent); - map.put("nsk", responseContent.getString("nsk")); - map.put("ovk", responseContent.getString("ovk")); - ask = responseContent.getString("ask"); - response = HttpMethed.getAkFromAsk(httpNode, ask); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - map.put("ak", responseContent.getString("value")); - - logger.info("noteTx.getTrxId():" + noteTx.getTrxId()); - HttpMethed.response = HttpMethed - .getMerkleTreeVoucherInfoFromSolidity(httpSolidityNode, noteTx.getTrxId(), - noteTx.getIndex(), 1); - HttpMethed.responseContent = HttpMethed.parseResponseContent(HttpMethed.response); - HttpMethed.printJsonContent(responseContent); - final JSONArray vouchers = HttpMethed.responseContent.getJSONArray("vouchers"); - final JSONArray paths = HttpMethed.responseContent.getJSONArray("paths"); - - HttpMethed.response = HttpMethed - .getMerkleTreeVoucherInfoFromPbft(httpPbftNode, noteTx.getTrxId(), noteTx.getIndex(), - 1); - HttpMethed.responseContent = HttpMethed.parseResponseContent(HttpMethed.response); - HttpMethed.printJsonContent(responseContent); - JSONArray vouchersPbft = HttpMethed.responseContent.getJSONArray("vouchers"); - JSONArray pathsPbft = HttpMethed.responseContent.getJSONArray("paths"); - Assert.assertTrue(pathsPbft.equals(paths)); - alpha = org.tron.core.zen.note.Note.generateR(); - - List shieldedSpends = Lists.newArrayList(new JSONObjectWarp().put("note", - new JSONObjectWarp().put("value", noteTx.getValue()) - .put("payment_address", noteTx.getPaymentAddress()) - .put("rcm", ByteArray.toHexString(noteTx.getR())) - .put("memo", ByteArray.toHexString(noteTx.getMemo()))) - .put("alpha", ByteArray.toHexString(alpha)).put("voucher", Lists.newArrayList(vouchers)) - .put("path", Lists.newArrayList(paths))); - - map.put("shielded_spends", shieldedSpends); - } else { - map.put("ovk", "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - } - - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - map.put("transparent_to_address", ByteArray.toHexString(publicZenTokenToAddress)); - map.put("to_amount", toAmount); - } - - if (shieldOutputList.size() > 0) { - ArrayList noteList = new ArrayList<>(); - for (int i = 0; i < shieldOutputList.size(); ++i) { - Map noteInfo = new HashMap(); - noteInfo.put("value", shieldOutputList.get(i).getValue()); - noteInfo.put("payment_address", shieldOutputList.get(i).getPaymentAddress()); - noteInfo.put("rcm", shieldOutputList.get(i).getRcm().toStringUtf8()); - noteInfo.put("memo", - ByteArray.toHexString(shieldOutputList.get(i).getMemo().toStringUtf8().getBytes())); - final Map note = new HashMap(); - note.put("note", noteInfo); - noteList.add(note); - } - map.put("shielded_receives", noteList); - } - - String jsonStr = new Gson().toJson(map); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - logger.info("jsonObj:" + jsonObj.toString()); - response = createConnect(requestUrl, jsonObj); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info("transactionString1:" + transactionString); - - if (shieldAddressInfo != null) { - String getHashUrl = "http://" + httpNode + "/wallet/getshieldtransactionhash"; - JsonObject gethashObject = new JsonParser().parse(transactionString).getAsJsonObject(); - logger.info("gethashObject:" + gethashObject); - response = createConnect(getHashUrl, gethashObject); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String hash = responseContent.getString("value"); - - String spendauthsigUrl = "http://" + httpNode + "/wallet/createspendauthsig"; - JSONObjectWarp spendauthsigJson = new JSONObjectWarp().put("ask", ask) - .put("alpha", ByteArray.toHexString(alpha)).put("tx_hash", hash); - String spendauthsigStr = spendauthsigJson.toJSONString(); - JsonObject spendauthsigObj = new JsonParser().parse(spendauthsigStr).getAsJsonObject(); - logger.info("spendauthsigObj:" + spendauthsigObj.toString()); - response = createConnect(spendauthsigUrl, spendauthsigObj); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String spendauthsig = responseContent.getString("value"); - - JSONObject jsonObject = HttpMethed.parseStringContent(transactionString); - jsonObject.getJSONObject("raw_data").getJSONArray("contract").getJSONObject(0) - .getJSONObject("parameter").getJSONObject("value").getJSONArray("spend_description") - .getJSONObject(0).put("spend_authority_signature", spendauthsig); - transactionString = jsonObject.toString(); - logger.info("transactionString2:" + transactionString); - } - - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - transactionSignString = gettransactionsign(httpNode, transactionString, zenTokenOwnerKey); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } else { - response = broadcastTransaction(httpNode, transactionString); - } - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static void freedResource(String httpNode, byte[] fromAddress, byte[] toAddress, - String fromKey) { - long balance = HttpMethed.getBalance(httpNode, fromAddress); - //System.out.println("剩余资源:" + balance); - sendCoin(httpNode, fromAddress, toAddress, balance - 50000, fromKey); - balance = HttpMethed.getBalance(httpNode, fromAddress); - //System.out.println("之后资源:" + balance); - } - - /** - * constructor. - */ - public static HttpResponse updateBrokerage(String httpNode, byte[] ownerAddress, Long brokerage, - String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/updateBrokerage"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("brokerage", brokerage); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse updateBrokerageOnVisible(String httpNode, byte[] ownerAddress, - Long brokerage, String fromKey, String visible) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/updateBrokerage"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("brokerage", brokerage); - if (visible.equals("true")) { - userBaseObj2.addProperty("owner_address", Base58.encode58Check(ownerAddress)); - } else if (visible.equals("false")) { - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - logger.info("userBaseObj2:" + userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getReward(String httpNode, byte[] address) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getReward"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getRewardFromSolidity(String httpSolidityNode, byte[] address) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getReward"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getRewardFromPbft(String httpSolidityNode, byte[] address) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getReward"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getBrokerage(String httpNode, byte[] address) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getBrokerage"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBrokerageFromSolidity(String httpSolidityNode, byte[] address) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getBrokerage"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getRewardOnVisible(String httpNode, byte[] address, String visible) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getReward"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("address", Base58.encode58Check(address)); - } else if (visible.equals("false")) { - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - } - userBaseObj2.addProperty("visible", visible); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getRewardFromSolidityOnVisible(String httpSolidityNode, byte[] address, - String visible) { - try { - final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getReward"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("address", Base58.encode58Check(address)); - } else if (visible.equals("false")) { - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - } - userBaseObj2.addProperty("visible", visible); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBrokerageOnVisible(String httpNode, byte[] address, - String visible) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getBrokerage"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("address", Base58.encode58Check(address)); - } else if (visible.equals("false")) { - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - } - userBaseObj2.addProperty("visible", visible); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBrokerageFromSolidityOnVisible(String httpSolidityNode, - byte[] address, String visible) { - try { - final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getBrokerage"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("address", Base58.encode58Check(address)); - } else if (visible.equals("false")) { - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - } - userBaseObj2.addProperty("visible", visible); - logger.info("userBaseObj2:" + userBaseObj2); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getBrokerageFromPbft(String httpSolidityNode, byte[] address) { - try { - final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getBrokerage"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", ByteArray.toHexString(address)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static String marketSellAssetGetTxId(String httpNode, byte[] ownerAddress, - String sellTokenId, - Long sellTokenQuantity, String buyTokenId, Long buyTokenQuantity, String fromKey, - String visible) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/marketsellasset"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("owner_address", Base58.encode58Check(ownerAddress)); - userBaseObj2.addProperty("sell_token_id", sellTokenId); - userBaseObj2.addProperty("buy_token_id", buyTokenId); - } else { - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); - userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); - } - userBaseObj2.addProperty("sell_token_quantity", sellTokenQuantity); - userBaseObj2.addProperty("buy_token_quantity", buyTokenQuantity); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - System.out.println("userBaseObj2: " + userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - System.out.println("transactionString: " + transactionString); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseStringContent(transactionSignString); - return responseContent.getString("txID"); - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderById(String httpNode, String orderId, String visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getmarketorderbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", orderId); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderByIdFromSolidity(String httpSolidityNode, String orderId, - String visible) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", orderId); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderByIdFromPbft(String httpPbftNode, String orderId, - String visible) { - try { - String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderbyid"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", orderId); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static String marketCancelOrder(String httpNode, byte[] ownerAddress, String orderId, - String fromKey, String visible) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/marketcancelorder"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("owner_address", Base58.encode58Check(ownerAddress)); - } else { - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - } - userBaseObj2.addProperty("order_id", orderId); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - System.out.println("userBaseObj2: " + userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - System.out.println("transactionString: " + transactionString); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseStringContent(transactionSignString); - return responseContent.getString("txID"); - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderByAccount(String httpNode, byte[] ownerAddress, - String visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getmarketorderbyaccount"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("value", Base58.encode58Check(ownerAddress)); - } else { - userBaseObj2.addProperty("value", ByteArray.toHexString(ownerAddress)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderByAccountFromSolidity(String httpSolidityNode, - byte[] ownerAddress, String visible) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderbyaccount"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("value", Base58.encode58Check(ownerAddress)); - } else { - userBaseObj2.addProperty("value", ByteArray.toHexString(ownerAddress)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderByAccountFromPbft(String httpPbftNode, - byte[] ownerAddress, String visible) { - try { - String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderbyaccount"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("value", Base58.encode58Check(ownerAddress)); - } else { - userBaseObj2.addProperty("value", ByteArray.toHexString(ownerAddress)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketPairList(String httpNode, String visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getmarketpairlist"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketPairListFromSolidity(String httpSolidityNode, - String visible) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketpairlist"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketPairListFromPbft(String httpPbftNode, String visible) { - try { - String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketpairlist"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderListByPair(String httpNode, String sellTokenId, - String buyTokenId, String visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getmarketorderlistbypair"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("sell_token_id", sellTokenId); - userBaseObj2.addProperty("buy_token_id", buyTokenId); - } else { - userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); - userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderListByPairFromSolidity(String httpSolidityNode, - String sellTokenId, - String buyTokenId, String visible) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderlistbypair"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("sell_token_id", sellTokenId); - userBaseObj2.addProperty("buy_token_id", buyTokenId); - } else { - userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); - userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketOrderListByPairFromPbft(String httpPbftNode, - String sellTokenId, String buyTokenId, String visible) { - try { - String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderlistbypair"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("sell_token_id", sellTokenId); - userBaseObj2.addProperty("buy_token_id", buyTokenId); - } else { - userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); - userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketPriceByPair(String httpNode, String sellTokenId, - String buyTokenId, String visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getmarketpricebypair"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("sell_token_id", sellTokenId); - userBaseObj2.addProperty("buy_token_id", buyTokenId); - } else { - userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); - userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketPriceByPairFromSolidity(String httpSolidityNode, - String sellTokenId, - String buyTokenId, String visible) { - try { - String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketpricebypair"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("sell_token_id", sellTokenId); - userBaseObj2.addProperty("buy_token_id", buyTokenId); - } else { - userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); - userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getMarketPriceByPairFromPbft(String httpPbftNode, - String sellTokenId, String buyTokenId, String visible) { - try { - String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketpricebypair"; - JsonObject userBaseObj2 = new JsonObject(); - if (visible.equals("true")) { - userBaseObj2.addProperty("sell_token_id", sellTokenId); - userBaseObj2.addProperty("buy_token_id", buyTokenId); - } else { - userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); - userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); - } - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static int getTransactionPendingSize(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getpendingsize"; - JsonObject userBaseObj2 = new JsonObject(); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return 0; - } + JSONArray vouchers = responseContent.getJSONArray("vouchers"); + JSONArray paths = responseContent.getJSONArray("paths"); + + List shieldedSpends = + Lists.newArrayList( + new JSONObjectWarp() + .put( + "note", + new JSONObjectWarp() + .put("value", noteTx.getValue()) + .put("payment_address", noteTx.getPaymentAddress()) + .put("rcm", ByteArray.toHexString(noteTx.getR())) + .put("memo", ByteArray.toHexString(noteTx.getMemo()))) + .put("alpha", ByteArray.toHexString(org.tron.core.zen.note.Note.generateR())) + .put("voucher", Lists.newArrayList(vouchers)) + .put("path", Lists.newArrayList(paths))); + + map.put("shielded_spends", shieldedSpends); + } else { + map.put("ovk", "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); + } + + if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { + map.put("transparent_to_address", ByteArray.toHexString(publicZenTokenToAddress)); + map.put("to_amount", toAmount); + } + + if (shieldOutputList.size() > 0) { + ArrayList noteList = new ArrayList<>(); + for (int i = 0; i < shieldOutputList.size(); ++i) { + + Map noteInfo = new HashMap(); + noteInfo.put("value", shieldOutputList.get(i).getValue()); + noteInfo.put("payment_address", shieldOutputList.get(i).getPaymentAddress()); + noteInfo.put("rcm", shieldOutputList.get(i).getRcm().toStringUtf8()); + noteInfo.put( + "memo", + ByteArray.toHexString(shieldOutputList.get(i).getMemo().toStringUtf8().getBytes())); + final Map note = new HashMap(); + note.put("note", noteInfo); + noteList.add(note); + } + map.put("shielded_receives", noteList); + } + + String jsonStr = new Gson().toJson(map); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + logger.info("jsonObj:" + jsonObj.toString()); + response = createConnect(requestUrl, jsonObj); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info(transactionString); + if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { + transactionSignString = gettransactionsign(httpNode, transactionString, zenTokenOwnerKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } else { + response = broadcastTransaction(httpNode, transactionString); + } + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static Boolean getSpendResult( + String httpNode, ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/isspend"; + + response = + HttpMethed.getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + responseContent = HttpMethed.parseResponseContent(response); + String ask = responseContent.getString("ask"); + response = HttpMethed.getAkFromAsk(httpNode, ask); + responseContent = HttpMethed.parseResponseContent(response); + JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); + jsonObjectWarp.put("ak", responseContent.getString("value")); + + String nsk = responseContent.getString("nsk"); + response = HttpMethed.getNkFromNsk(httpNode, nsk); + responseContent = HttpMethed.parseResponseContent(response); + jsonObjectWarp.put("nk", responseContent.getString("value")); + + jsonObjectWarp + .put( + "note", + new JSONObjectWarp() + .put("value", noteTx.getValue()) + .put("payment_address", noteTx.getPaymentAddress()) + .put("rcm", ByteArray.toHexString(noteTx.getR())) + .put("memo", ByteArray.toHexString(noteTx.getMemo()))) + .put("txid", noteTx.getTrxId()); + + String jsonStr = jsonObjectWarp.toJSONString(); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + logger.info("jsonObj:" + jsonObj.toString()); + HttpMethed.response = createConnect(requestUrl, jsonObj); + + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String jsonString = responseContent.toJSONString(); + if (jsonString.contains("result") + && (responseContent.getString("result").equals("true") + && responseContent.getString("message").equals("Input note has been spent"))) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** constructor. */ + public static Boolean getSpendResultFromSolidity( + String httpNode, + String httpSolidityNode, + ShieldAddressInfo shieldAddressInfo, + ShieldNoteInfo noteTx) { + try { + final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/isspend"; + + response = + HttpMethed.getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + responseContent = HttpMethed.parseResponseContent(response); + String ask = responseContent.getString("ask"); + response = HttpMethed.getAkFromAsk(httpNode, ask); + responseContent = HttpMethed.parseResponseContent(response); + JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); + jsonObjectWarp.put("ak", responseContent.getString("value")); + + String nsk = responseContent.getString("nsk"); + response = HttpMethed.getNkFromNsk(httpNode, nsk); + responseContent = HttpMethed.parseResponseContent(response); + jsonObjectWarp.put("nk", responseContent.getString("value")); + + jsonObjectWarp + .put( + "note", + new JSONObjectWarp() + .put("value", noteTx.getValue()) + .put("payment_address", noteTx.getPaymentAddress()) + .put("rcm", ByteArray.toHexString(noteTx.getR())) + .put("memo", ByteArray.toHexString(noteTx.getMemo()))) + .put("txid", noteTx.getTrxId()); + + String jsonStr = jsonObjectWarp.toJSONString(); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + logger.info("jsonObj:" + jsonObj.toString()); + HttpMethed.response = createConnect(requestUrl, jsonObj); + responseContent = HttpMethed.parseResponseContent(response); + + HttpMethed.printJsonContent(responseContent); + String jsonString = responseContent.toJSONString(); + if (jsonString.contains("result") + && (responseContent.getString("result").equals("true") + && responseContent.getString("message").equals("Input note has been spent"))) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** constructor. */ + public static Boolean getSpendResultFromPbft( + String httpNode, + String httpSolidityNode, + ShieldAddressInfo shieldAddressInfo, + ShieldNoteInfo noteTx) { + try { + final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/isspend"; + final JSONObjectWarp jsonObjectWarp = new JSONObjectWarp(); + + response = + HttpMethed.getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + responseContent = HttpMethed.parseResponseContent(response); + String ask = responseContent.getString("ask"); + final String nsk = responseContent.getString("nsk"); + response = HttpMethed.getAkFromAsk(httpNode, ask); + responseContent = HttpMethed.parseResponseContent(response); + jsonObjectWarp.put("ak", responseContent.getString("value")); + response = HttpMethed.getNkFromNsk(httpNode, nsk); + responseContent = HttpMethed.parseResponseContent(response); + jsonObjectWarp.put("nk", responseContent.getString("value")); + jsonObjectWarp + .put( + "note", + new JSONObjectWarp() + .put("value", noteTx.getValue()) + .put("payment_address", noteTx.getPaymentAddress()) + .put("rcm", ByteArray.toHexString(noteTx.getR())) + .put("memo", ByteArray.toHexString(noteTx.getMemo()))) + .put("txid", noteTx.getTrxId()); + String jsonStr = jsonObjectWarp.toJSONString(); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + logger.info("jsonObj:" + jsonObj.toString()); + HttpMethed.response = createConnect(requestUrl, jsonObj); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String jsonString = responseContent.toJSONString(); + if (jsonString.contains("result") + && (responseContent.getString("result").equals("true") + && responseContent.getString("message").equals("Input note has been spent"))) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** constructor. */ + public static List scanNoteByOvkFromPbft( + String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { + try { + response = HttpMethed.getNowBlockFromPbft(httpSolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + + final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/scannotebyovk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ovk", ByteArray.toHexString(shieldAddressInfo.getOvk())); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(0).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** constructor. */ + public static List scanNoteByIvk( + String httpNode, ShieldAddressInfo shieldAddressInfo) { + try { + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + + final String requestUrl = "http://" + httpNode + "/wallet/scannotebyivk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + if (jsonArray != null) { + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(i).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** constructor. */ + public static List scanNoteByIvkFromSolidity( + String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { + try { + response = HttpMethed.getNowBlockFromSolidity(httpSolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + + final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/scannotebyivk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(i).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** constructor. */ + public static List scanNoteByIvkFromPbft( + String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { + try { + response = HttpMethed.getNowBlockFromPbft(httpSolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + + final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/scannotebyivk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(i).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** constructor. */ + public static List scanAndMarkNoteByIvk( + String httpNode, ShieldAddressInfo shieldAddressInfo) { + try { + response = + HttpMethed.getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + responseContent = HttpMethed.parseResponseContent(response); + String ask = responseContent.getString("ask"); + String nsk = responseContent.getString("nsk"); + response = HttpMethed.getAkFromAsk(httpNode, ask); + responseContent = HttpMethed.parseResponseContent(response); + final String ak = responseContent.getString("value"); + + response = HttpMethed.getNkFromNsk(httpNode, nsk); + responseContent = HttpMethed.parseResponseContent(response); + final String nk = responseContent.getString("value"); + + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + + final String requestUrl = "http://" + httpNode + "/wallet/scanandmarknotebyivk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); + userBaseObj2.addProperty("ak", ak); + userBaseObj2.addProperty("nk", nk); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + logger.info("jsonArray:" + jsonArray.toJSONString()); + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(i).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIsSpend(HttpMethed.parseStringContent(noteTxs).getBoolean("is_spend")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** constructor. */ + public static List scanAndMarkNoteByIvkFromSolidity( + String httpNode, String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { + try { + response = + HttpMethed.getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + responseContent = HttpMethed.parseResponseContent(response); + String ask = responseContent.getString("ask"); + String nsk = responseContent.getString("nsk"); + response = HttpMethed.getAkFromAsk(httpNode, ask); + responseContent = HttpMethed.parseResponseContent(response); + final String ak = responseContent.getString("value"); + + response = HttpMethed.getNkFromNsk(httpNode, nsk); + responseContent = HttpMethed.parseResponseContent(response); + final String nk = responseContent.getString("value"); + + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + + final String requestUrl = + "http://" + httpSolidityNode + "/walletsolidity/scanandmarknotebyivk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); + userBaseObj2.addProperty("ak", ak); + userBaseObj2.addProperty("nk", nk); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + logger.info("jsonArray:" + jsonArray.toJSONString()); + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(i).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIsSpend(HttpMethed.parseStringContent(noteTxs).getBoolean("is_spend")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** constructor. */ + public static List scanAndMarkNoteByIvkFromPbft( + String httpNode, String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { + try { + response = + HttpMethed.getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + responseContent = HttpMethed.parseResponseContent(response); + String ask = responseContent.getString("ask"); + String nsk = responseContent.getString("nsk"); + response = HttpMethed.getAkFromAsk(httpNode, ask); + responseContent = HttpMethed.parseResponseContent(response); + final String ak = responseContent.getString("value"); + + response = HttpMethed.getNkFromNsk(httpNode, nsk); + responseContent = HttpMethed.parseResponseContent(response); + final String nk = responseContent.getString("value"); + + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/scanandmarknotebyivk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ivk", ByteArray.toHexString(shieldAddressInfo.ivk)); + userBaseObj2.addProperty("ak", ak); + userBaseObj2.addProperty("nk", nk); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + logger.info("jsonArray:" + jsonArray.toJSONString()); + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(i).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIsSpend(HttpMethed.parseStringContent(noteTxs).getBoolean("is_spend")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** constructor. */ + public static List scanNoteByOvk( + String httpNode, ShieldAddressInfo shieldAddressInfo) { + try { + response = HttpMethed.getNowBlock(httpNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + + final String requestUrl = "http://" + httpNode + "/wallet/scannotebyovk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ovk", ByteArray.toHexString(shieldAddressInfo.getOvk())); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(i).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** constructor. */ + public static List scanNoteByOvkFromSolidity( + String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { + try { + response = HttpMethed.getNowBlockFromSolidity(httpSolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String blockHeaderString = responseContent.getString("block_header"); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); + Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); + Integer startBlockNum = 0; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + + final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/scannotebyovk"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("start_block_index", startBlockNum); + userBaseObj2.addProperty("end_block_index", currentBlockNum); + userBaseObj2.addProperty("ovk", ByteArray.toHexString(shieldAddressInfo.getOvk())); + logger.info("userBaseObj2:" + userBaseObj2.toString()); + response = createConnect(requestUrl, userBaseObj2); + + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + List shieldNoteInfoList = new ArrayList<>(); + JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); + for (int i = 0; i < jsonArray.size(); i++) { + ShieldNoteInfo noteTx = new ShieldNoteInfo(); + String noteTxs = jsonArray.get(0).toString(); + String noteString = HttpMethed.parseStringContent(noteTxs).getString("note"); + noteTx.setValue(HttpMethed.parseStringContent(noteString).getLong("value")); + noteTx.setPaymentAddress( + HttpMethed.parseStringContent(noteString).getString("payment_address")); + noteTx.setR( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("rcm"))); + noteTx.setMemo( + ByteArray.fromHexString(HttpMethed.parseStringContent(noteString).getString("memo"))); + noteTx.setTrxId(HttpMethed.parseStringContent(noteTxs).getString("txid")); + noteTx.setIndex(HttpMethed.parseStringContent(noteTxs).getIntValue("index")); + shieldNoteInfoList.add(noteTx); + } + return shieldNoteInfoList; + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + } + + /** constructor. */ + public static HttpResponse sendShieldCoinWithoutAsk( + String httpNode, + String httpSolidityNode, + String httpPbftNode, + byte[] publicZenTokenOwnerAddress, + long fromAmount, + ShieldAddressInfo shieldAddressInfo, + ShieldNoteInfo noteTx, + List shieldOutputList, + byte[] publicZenTokenToAddress, + long toAmount, + String zenTokenOwnerKey) { + try { + final String requestUrl = + "http://" + httpNode + "/wallet/createshieldedtransactionwithoutspendauthsig"; + + Map map = new HashMap(); + if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { + map.put("transparent_from_address", ByteArray.toHexString(publicZenTokenOwnerAddress)); + map.put("from_amount", fromAmount); + } + String ask = ""; + byte[] alpha = null; + if (shieldAddressInfo != null) { + HttpResponse expandedSpendingKey = + HttpMethed.getExpandedSpendingKey( + httpNode, ByteArray.toHexString(shieldAddressInfo.getSk())); + responseContent = HttpMethed.parseResponseContent(expandedSpendingKey); + HttpMethed.printJsonContent(responseContent); + map.put("nsk", responseContent.getString("nsk")); + map.put("ovk", responseContent.getString("ovk")); + ask = responseContent.getString("ask"); + response = HttpMethed.getAkFromAsk(httpNode, ask); responseContent = HttpMethed.parseResponseContent(response); - return responseContent.getInteger("pendingSize"); - } - - /** - * constructor. - */ - public static HttpResponse getTransactionListFromPending(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/gettransactionlistfrompending"; - JsonObject userBaseObj2 = new JsonObject(); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getTransactionFromPending(String httpNode, String txid) { - try { - String requestUrl = "http://" + httpNode + "/wallet/gettransactionfrompending"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", txid); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - + HttpMethed.printJsonContent(responseContent); + map.put("ak", responseContent.getString("value")); + + logger.info("noteTx.getTrxId():" + noteTx.getTrxId()); + HttpMethed.response = + HttpMethed.getMerkleTreeVoucherInfoFromSolidity( + httpSolidityNode, noteTx.getTrxId(), noteTx.getIndex(), 1); + HttpMethed.responseContent = HttpMethed.parseResponseContent(HttpMethed.response); + HttpMethed.printJsonContent(responseContent); + final JSONArray vouchers = HttpMethed.responseContent.getJSONArray("vouchers"); + final JSONArray paths = HttpMethed.responseContent.getJSONArray("paths"); + + HttpMethed.response = + HttpMethed.getMerkleTreeVoucherInfoFromPbft( + httpPbftNode, noteTx.getTrxId(), noteTx.getIndex(), 1); + HttpMethed.responseContent = HttpMethed.parseResponseContent(HttpMethed.response); + HttpMethed.printJsonContent(responseContent); + JSONArray vouchersPbft = HttpMethed.responseContent.getJSONArray("vouchers"); + JSONArray pathsPbft = HttpMethed.responseContent.getJSONArray("paths"); + Assert.assertTrue(pathsPbft.equals(paths)); + alpha = org.tron.core.zen.note.Note.generateR(); + + List shieldedSpends = + Lists.newArrayList( + new JSONObjectWarp() + .put( + "note", + new JSONObjectWarp() + .put("value", noteTx.getValue()) + .put("payment_address", noteTx.getPaymentAddress()) + .put("rcm", ByteArray.toHexString(noteTx.getR())) + .put("memo", ByteArray.toHexString(noteTx.getMemo()))) + .put("alpha", ByteArray.toHexString(alpha)) + .put("voucher", Lists.newArrayList(vouchers)) + .put("path", Lists.newArrayList(paths))); + + map.put("shielded_spends", shieldedSpends); + } else { + map.put("ovk", "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); + } + + if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { + map.put("transparent_to_address", ByteArray.toHexString(publicZenTokenToAddress)); + map.put("to_amount", toAmount); + } + + if (shieldOutputList.size() > 0) { + ArrayList noteList = new ArrayList<>(); + for (int i = 0; i < shieldOutputList.size(); ++i) { + Map noteInfo = new HashMap(); + noteInfo.put("value", shieldOutputList.get(i).getValue()); + noteInfo.put("payment_address", shieldOutputList.get(i).getPaymentAddress()); + noteInfo.put("rcm", shieldOutputList.get(i).getRcm().toStringUtf8()); + noteInfo.put( + "memo", + ByteArray.toHexString(shieldOutputList.get(i).getMemo().toStringUtf8().getBytes())); + final Map note = new HashMap(); + note.put("note", noteInfo); + noteList.add(note); + } + map.put("shielded_receives", noteList); + } + + String jsonStr = new Gson().toJson(map); + JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); + logger.info("jsonObj:" + jsonObj.toString()); + response = createConnect(requestUrl, jsonObj); + transactionString = EntityUtils.toString(response.getEntity()); + logger.info("transactionString1:" + transactionString); + + if (shieldAddressInfo != null) { + String getHashUrl = "http://" + httpNode + "/wallet/getshieldtransactionhash"; + JsonObject gethashObject = new JsonParser().parse(transactionString).getAsJsonObject(); + logger.info("gethashObject:" + gethashObject); + response = createConnect(getHashUrl, gethashObject); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String hash = responseContent.getString("value"); + + String spendauthsigUrl = "http://" + httpNode + "/wallet/createspendauthsig"; + JSONObjectWarp spendauthsigJson = + new JSONObjectWarp() + .put("ask", ask) + .put("alpha", ByteArray.toHexString(alpha)) + .put("tx_hash", hash); + String spendauthsigStr = spendauthsigJson.toJSONString(); + JsonObject spendauthsigObj = new JsonParser().parse(spendauthsigStr).getAsJsonObject(); + logger.info("spendauthsigObj:" + spendauthsigObj.toString()); + response = createConnect(spendauthsigUrl, spendauthsigObj); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + String spendauthsig = responseContent.getString("value"); + + JSONObject jsonObject = HttpMethed.parseStringContent(transactionString); + jsonObject + .getJSONObject("raw_data") + .getJSONArray("contract") + .getJSONObject(0) + .getJSONObject("parameter") + .getJSONObject("value") + .getJSONArray("spend_description") + .getJSONObject(0) + .put("spend_authority_signature", spendauthsig); + transactionString = jsonObject.toString(); + logger.info("transactionString2:" + transactionString); + } + + if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { + transactionSignString = gettransactionsign(httpNode, transactionString, zenTokenOwnerKey); + logger.info(transactionSignString); + response = broadcastTransaction(httpNode, transactionSignString); + } else { + response = broadcastTransaction(httpNode, transactionString); + } + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static void freedResource( + String httpNode, byte[] fromAddress, byte[] toAddress, String fromKey) { + long balance = HttpMethed.getBalance(httpNode, fromAddress); + // System.out.println("剩余资源:" + balance); + sendCoin(httpNode, fromAddress, toAddress, balance - 50000, fromKey); + balance = HttpMethed.getBalance(httpNode, fromAddress); + // System.out.println("之后资源:" + balance); + } + + /** constructor. */ + public static HttpResponse updateBrokerage( + String httpNode, byte[] ownerAddress, Long brokerage, String fromKey) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/updateBrokerage"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("brokerage", brokerage); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse updateBrokerageOnVisible( + String httpNode, byte[] ownerAddress, Long brokerage, String fromKey, String visible) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/updateBrokerage"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("brokerage", brokerage); + if (visible.equals("true")) { + userBaseObj2.addProperty("owner_address", Base58.encode58Check(ownerAddress)); + } else if (visible.equals("false")) { + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + logger.info("userBaseObj2:" + userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getReward(String httpNode, byte[] address) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getReward"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getRewardFromSolidity(String httpSolidityNode, byte[] address) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getReward"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getRewardFromPbft(String httpSolidityNode, byte[] address) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getReward"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getBrokerage(String httpNode, byte[] address) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getBrokerage"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getBrokerageFromSolidity(String httpSolidityNode, byte[] address) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getBrokerage"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getRewardOnVisible(String httpNode, byte[] address, String visible) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getReward"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("address", Base58.encode58Check(address)); + } else if (visible.equals("false")) { + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + } + userBaseObj2.addProperty("visible", visible); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getRewardFromSolidityOnVisible( + String httpSolidityNode, byte[] address, String visible) { + try { + final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getReward"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("address", Base58.encode58Check(address)); + } else if (visible.equals("false")) { + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + } + userBaseObj2.addProperty("visible", visible); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getBrokerageOnVisible( + String httpNode, byte[] address, String visible) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/getBrokerage"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("address", Base58.encode58Check(address)); + } else if (visible.equals("false")) { + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + } + userBaseObj2.addProperty("visible", visible); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getBrokerageFromSolidityOnVisible( + String httpSolidityNode, byte[] address, String visible) { + try { + final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getBrokerage"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("address", Base58.encode58Check(address)); + } else if (visible.equals("false")) { + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + } + userBaseObj2.addProperty("visible", visible); + logger.info("userBaseObj2:" + userBaseObj2); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getBrokerageFromPbft(String httpSolidityNode, byte[] address) { + try { + final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getBrokerage"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("address", ByteArray.toHexString(address)); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static String marketSellAssetGetTxId( + String httpNode, + byte[] ownerAddress, + String sellTokenId, + Long sellTokenQuantity, + String buyTokenId, + Long buyTokenQuantity, + String fromKey, + String visible) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/marketsellasset"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("owner_address", Base58.encode58Check(ownerAddress)); + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("sell_token_quantity", sellTokenQuantity); + userBaseObj2.addProperty("buy_token_quantity", buyTokenQuantity); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + System.out.println("userBaseObj2: " + userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + System.out.println("transactionString: " + transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseStringContent(transactionSignString); + return responseContent.getString("txID"); + } + + /** constructor. */ + public static HttpResponse getMarketOrderById(String httpNode, String orderId, String visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getmarketorderbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", orderId); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getMarketOrderByIdFromSolidity( + String httpSolidityNode, String orderId, String visible) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", orderId); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getMarketOrderByIdFromPbft( + String httpPbftNode, String orderId, String visible) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderbyid"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", orderId); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static String marketCancelOrder( + String httpNode, byte[] ownerAddress, String orderId, String fromKey, String visible) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/marketcancelorder"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("owner_address", Base58.encode58Check(ownerAddress)); + } else { + userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); + } + userBaseObj2.addProperty("order_id", orderId); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + System.out.println("userBaseObj2: " + userBaseObj2); + transactionString = EntityUtils.toString(response.getEntity()); + System.out.println("transactionString: " + transactionString); + transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); + response = broadcastTransaction(httpNode, transactionSignString); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + responseContent = HttpMethed.parseStringContent(transactionSignString); + return responseContent.getString("txID"); + } + + /** constructor. */ + public static HttpResponse getMarketOrderByAccount( + String httpNode, byte[] ownerAddress, String visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getmarketorderbyaccount"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("value", Base58.encode58Check(ownerAddress)); + } else { + userBaseObj2.addProperty("value", ByteArray.toHexString(ownerAddress)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getMarketOrderByAccountFromSolidity( + String httpSolidityNode, byte[] ownerAddress, String visible) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderbyaccount"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("value", Base58.encode58Check(ownerAddress)); + } else { + userBaseObj2.addProperty("value", ByteArray.toHexString(ownerAddress)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getMarketOrderByAccountFromPbft( + String httpPbftNode, byte[] ownerAddress, String visible) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderbyaccount"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("value", Base58.encode58Check(ownerAddress)); + } else { + userBaseObj2.addProperty("value", ByteArray.toHexString(ownerAddress)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getMarketPairList(String httpNode, String visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getmarketpairlist"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getMarketPairListFromSolidity( + String httpSolidityNode, String visible) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketpairlist"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getMarketPairListFromPbft(String httpPbftNode, String visible) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketpairlist"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getMarketOrderListByPair( + String httpNode, String sellTokenId, String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getmarketorderlistbypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getMarketOrderListByPairFromSolidity( + String httpSolidityNode, String sellTokenId, String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderlistbypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getMarketOrderListByPairFromPbft( + String httpPbftNode, String sellTokenId, String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderlistbypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getMarketPriceByPair( + String httpNode, String sellTokenId, String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getmarketpricebypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getMarketPriceByPairFromSolidity( + String httpSolidityNode, String sellTokenId, String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketpricebypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getMarketPriceByPairFromPbft( + String httpPbftNode, String sellTokenId, String buyTokenId, String visible) { + try { + String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketpricebypair"; + JsonObject userBaseObj2 = new JsonObject(); + if (visible.equals("true")) { + userBaseObj2.addProperty("sell_token_id", sellTokenId); + userBaseObj2.addProperty("buy_token_id", buyTokenId); + } else { + userBaseObj2.addProperty("sell_token_id", str2hex(sellTokenId)); + userBaseObj2.addProperty("buy_token_id", str2hex(buyTokenId)); + } + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static int getTransactionPendingSize(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getpendingsize"; + JsonObject userBaseObj2 = new JsonObject(); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return 0; + } + responseContent = HttpMethed.parseResponseContent(response); + return responseContent.getInteger("pendingSize"); + } + + /** constructor. */ + public static HttpResponse getTransactionListFromPending(String httpNode) { + try { + String requestUrl = "http://" + httpNode + "/wallet/gettransactionlistfrompending"; + JsonObject userBaseObj2 = new JsonObject(); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getTransactionFromPending(String httpNode, String txid) { + try { + String requestUrl = "http://" + httpNode + "/wallet/gettransactionfrompending"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("value", txid); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + } } diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java index 396cd730ea7..04ee5b487de 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java @@ -141,649 +141,670 @@ public class PublicMethed { - //Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - private static final String FilePath = "Wallet"; - private static final Logger logger = LoggerFactory.getLogger("TestLogger"); - //private WalletGrpc.WalletBlockingStub blockingStubFull = null; - //private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - public static Map utxoMapNote = new ConcurrentHashMap(); - public static List spendUtxoList = new ArrayList<>(); - private static List walletFile = new ArrayList<>(); - private static ShieldWrapper shieldWrapper = new ShieldWrapper(); - Wallet wallet = new Wallet(); - public static volatile Integer witnessNum; - - /** - * constructor. - */ - - - public static Integer getWitnessNum(WalletGrpc.WalletBlockingStub blockingStubFull) { - if (null == witnessNum) { - witnessNum = PublicMethed.listWitnesses(blockingStubFull) - .get().getWitnessesList().size(); - } - - return witnessNum; - } + // Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + private static final String FilePath = "Wallet"; + private static final Logger logger = LoggerFactory.getLogger("TestLogger"); + // private WalletGrpc.WalletBlockingStub blockingStubFull = null; + // private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; + public static Map utxoMapNote = new ConcurrentHashMap(); + public static List spendUtxoList = new ArrayList<>(); + private static List walletFile = new ArrayList<>(); + private static ShieldWrapper shieldWrapper = new ShieldWrapper(); + Wallet wallet = new Wallet(); + public static volatile Integer witnessNum; + + /** constructor. */ + public static Integer getWitnessNum(WalletGrpc.WalletBlockingStub blockingStubFull) { + if (null == witnessNum) { + witnessNum = PublicMethed.listWitnesses(blockingStubFull).get().getWitnessesList().size(); + } + + return witnessNum; + } - public static String createAssetIssueGetTxid(byte[] address, String name, String abbreviation, - Long totalSupply, Integer trxNum, Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setAbbr(ByteString.copyFrom(abbreviation.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return null; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } catch (Exception ex) { - ex.printStackTrace(); - return null; - } - } + /** constructor. */ + public static String createAssetIssueGetTxid( + byte[] address, + String name, + String abbreviation, + Long totalSupply, + Integer trxNum, + Integer icoNum, + Long startTime, + Long endTime, + Integer voteScore, + String description, + String url, + Long freeAssetNetLimit, + Long publicFreeAssetNetLimit, + Long fronzenAmount, + Long frozenDay, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; + try { + AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(address)); + builder.setName(ByteString.copyFrom(name.getBytes())); + builder.setAbbr(ByteString.copyFrom(abbreviation.getBytes())); + builder.setTotalSupply(totalSupply); + builder.setTrxNum(trxNum); + builder.setNum(icoNum); + builder.setStartTime(startTime); + builder.setEndTime(endTime); + builder.setVoteScore(voteScore); + builder.setDescription(ByteString.copyFrom(description.getBytes())); + builder.setUrl(ByteString.copyFrom(url.getBytes())); + builder.setFreeAssetNetLimit(freeAssetNetLimit); + builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); + AssetIssueContract.FrozenSupply.Builder frozenBuilder = + AssetIssueContract.FrozenSupply.newBuilder(); + frozenBuilder.setFrozenAmount(fronzenAmount); + frozenBuilder.setFrozenDays(frozenDay); + builder.addFrozenSupply(0, frozenBuilder); + + Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); + return null; + } + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - /** - * constructor. - */ - public static Boolean createAssetIssue(byte[] address, String name, Long totalSupply, - Integer trxNum, Integer icoNum, Long startTime, Long endTime, Integer voteScore, - String description, String url, Long freeAssetNetLimit, Long publicFreeAssetNetLimit, - Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } catch (Exception ex) { + ex.printStackTrace(); + return null; } + } - /** - * constructor. - */ - - public static Boolean createAssetIssue(byte[] address, String name, String abbreviation, - Long totalSupply, Integer trxNum, Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setAbbr(ByteString.copyFrom(abbreviation.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } + /** constructor. */ + public static Boolean createAssetIssue( + byte[] address, + String name, + Long totalSupply, + Integer trxNum, + Integer icoNum, + Long startTime, + Long endTime, + Integer voteScore, + String description, + String url, + Long freeAssetNetLimit, + Long publicFreeAssetNetLimit, + Long fronzenAmount, + Long frozenDay, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; + try { + AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(address)); + builder.setName(ByteString.copyFrom(name.getBytes())); + builder.setTotalSupply(totalSupply); + builder.setTrxNum(trxNum); + builder.setNum(icoNum); + builder.setStartTime(startTime); + builder.setEndTime(endTime); + builder.setVoteScore(voteScore); + builder.setDescription(ByteString.copyFrom(description.getBytes())); + builder.setUrl(ByteString.copyFrom(url.getBytes())); + builder.setFreeAssetNetLimit(freeAssetNetLimit); + builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); + AssetIssueContract.FrozenSupply.Builder frozenBuilder = + AssetIssueContract.FrozenSupply.newBuilder(); + frozenBuilder.setFrozenAmount(fronzenAmount); + frozenBuilder.setFrozenDays(frozenDay); + builder.addFrozenSupply(0, frozenBuilder); + + Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); + return false; + } + transaction = signTransaction(ecKey, transaction); - /** - * constructor. - */ + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - public static Boolean createAssetIssue(byte[] address, String name, Long totalSupply, - Integer trxNum, Integer icoNum, int precision, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setPrecision(precision); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } + return response.getResult(); + } catch (Exception ex) { + ex.printStackTrace(); + return false; } + } - /** - * constructor. - */ - - public static Return createAssetIssue2(byte[] address, String name, Long totalSupply, - Integer trxNum, Integer icoNum, Long startTime, Long endTime, Integer voteScore, - String description, String url, Long freeAssetNetLimit, Long publicFreeAssetNetLimit, - Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(ecKey, blockingStubFull); - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - //builder.setPublicFreeAssetNetUsage(); - //builder.setPublicLatestFreeNetTime(); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - TransactionExtention transactionExtention = blockingStubFull - .createAssetIssue2(builder.build()); - - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return response; - } else { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - return ret; - } catch (Exception ex) { - ex.printStackTrace(); - //return false; - return Return.getDefaultInstance(); - } - } + /** constructor. */ + public static Boolean createAssetIssue( + byte[] address, + String name, + String abbreviation, + Long totalSupply, + Integer trxNum, + Integer icoNum, + Long startTime, + Long endTime, + Integer voteScore, + String description, + String url, + Long freeAssetNetLimit, + Long publicFreeAssetNetLimit, + Long fronzenAmount, + Long frozenDay, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; + try { + AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(address)); + builder.setName(ByteString.copyFrom(name.getBytes())); + builder.setAbbr(ByteString.copyFrom(abbreviation.getBytes())); + builder.setTotalSupply(totalSupply); + builder.setTrxNum(trxNum); + builder.setNum(icoNum); + builder.setStartTime(startTime); + builder.setEndTime(endTime); + builder.setVoteScore(voteScore); + builder.setDescription(ByteString.copyFrom(description.getBytes())); + builder.setUrl(ByteString.copyFrom(url.getBytes())); + builder.setFreeAssetNetLimit(freeAssetNetLimit); + builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); + AssetIssueContract.FrozenSupply.Builder frozenBuilder = + AssetIssueContract.FrozenSupply.newBuilder(); + frozenBuilder.setFrozenAmount(fronzenAmount); + frozenBuilder.setFrozenDays(frozenDay); + builder.addFrozenSupply(0, frozenBuilder); + + Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); + return false; + } + transaction = signTransaction(ecKey, transaction); - /** - * constructor. - */ + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - public static Account queryAccountByAddress(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); + return response.getResult(); + } catch (Exception ex) { + ex.printStackTrace(); + return false; } + } - /** - * constructor. - */ + /** constructor. */ + public static Boolean createAssetIssue( + byte[] address, + String name, + Long totalSupply, + Integer trxNum, + Integer icoNum, + int precision, + Long startTime, + Long endTime, + Integer voteScore, + String description, + String url, + Long freeAssetNetLimit, + Long publicFreeAssetNetLimit, + Long fronzenAmount, + Long frozenDay, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; + try { + AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(address)); + builder.setName(ByteString.copyFrom(name.getBytes())); + builder.setTotalSupply(totalSupply); + builder.setTrxNum(trxNum); + builder.setNum(icoNum); + builder.setStartTime(startTime); + builder.setEndTime(endTime); + builder.setVoteScore(voteScore); + builder.setPrecision(precision); + builder.setDescription(ByteString.copyFrom(description.getBytes())); + builder.setUrl(ByteString.copyFrom(url.getBytes())); + builder.setFreeAssetNetLimit(freeAssetNetLimit); + builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); + AssetIssueContract.FrozenSupply.Builder frozenBuilder = + AssetIssueContract.FrozenSupply.newBuilder(); + frozenBuilder.setFrozenAmount(fronzenAmount); + frozenBuilder.setFrozenDays(frozenDay); + builder.addFrozenSupply(0, frozenBuilder); + + Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); + return false; + } + transaction = signTransaction(ecKey, transaction); - public static Account queryAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } catch (Exception ex) { + ex.printStackTrace(); + return false; + } + } - /** - * constructor. - */ + /** constructor. */ + public static Return createAssetIssue2( + byte[] address, + String name, + Long totalSupply, + Integer trxNum, + Integer icoNum, + Long startTime, + Long endTime, + Integer voteScore, + String description, + String url, + Long freeAssetNetLimit, + Long publicFreeAssetNetLimit, + Long fronzenAmount, + Long frozenDay, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; + // Protocol.Account search = queryAccount(ecKey, blockingStubFull); + try { + AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(address)); + builder.setName(ByteString.copyFrom(name.getBytes())); + builder.setTotalSupply(totalSupply); + builder.setTrxNum(trxNum); + builder.setNum(icoNum); + builder.setStartTime(startTime); + builder.setEndTime(endTime); + builder.setVoteScore(voteScore); + builder.setDescription(ByteString.copyFrom(description.getBytes())); + builder.setUrl(ByteString.copyFrom(url.getBytes())); + builder.setFreeAssetNetLimit(freeAssetNetLimit); + builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); + // builder.setPublicFreeAssetNetUsage(); + // builder.setPublicLatestFreeNetTime(); + AssetIssueContract.FrozenSupply.Builder frozenBuilder = + AssetIssueContract.FrozenSupply.newBuilder(); + frozenBuilder.setFrozenAmount(fronzenAmount); + frozenBuilder.setFrozenDays(frozenDay); + builder.addFrozenSupply(0, frozenBuilder); + + TransactionExtention transactionExtention = + blockingStubFull.createAssetIssue2(builder.build()); + + if (transactionExtention == null) { + return transactionExtention.getResult(); + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return ret; + } else { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return transactionExtention.getResult(); + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); - public static Protocol.Account queryAccount(String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address; - ECKey temKey = null; + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return response; + } else { try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); + Thread.sleep(3000); + } catch (InterruptedException e) { + e.printStackTrace(); } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); + } + return ret; + } catch (Exception ex) { + ex.printStackTrace(); + // return false; + return Return.getDefaultInstance(); } + } - /** - * constructor. - */ - public static Account queryAccount(byte[] address, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } + /** constructor. */ + public static Account queryAccountByAddress( + byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString addressBs = ByteString.copyFrom(address); + Account request = Account.newBuilder().setAddress(addressBs).build(); + return blockingStubFull.getAccount(request); + } - /** - * constructor. - */ + /** constructor. */ + public static Account queryAccount( + byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString addressBs = ByteString.copyFrom(address); + Account request = Account.newBuilder().setAddress(addressBs).build(); + return blockingStubFull.getAccount(request); + } - public static Account getAccountById(String accountId, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString bsAccountId = ByteString.copyFromUtf8(accountId); - Account request = Account.newBuilder().setAccountId(bsAccountId).build(); - return blockingStubFull.getAccountById(request); + /** constructor. */ + public static Protocol.Account queryAccount( + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + byte[] address; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; + if (ecKey == null) { + String pubKey = loadPubKey(); // 04 PubKey[128] + if (StringUtils.isEmpty(pubKey)) { + logger.warn("Warning: QueryAccount failed, no wallet address !!"); + return null; + } + byte[] pubKeyAsc = pubKey.getBytes(); + byte[] pubKeyHex = Hex.decode(pubKeyAsc); + ecKey = ECKey.fromPublicOnly(pubKeyHex); } + return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); + } - /** - * constructor. - */ - - public static Account getAccountByIdFromSolidity(String accountId, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString bsAccountId = ByteString.copyFromUtf8(accountId); - Account request = Account.newBuilder().setAccountId(bsAccountId).build(); - return blockingStubFull.getAccountById(request); - } + /** constructor. */ + public static Account queryAccount( + byte[] address, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString addressBs = ByteString.copyFrom(address); + Account request = Account.newBuilder().setAddress(addressBs).build(); + return blockingStubFull.getAccount(request); + } - /** - * constructor. - */ - public static String loadPubKey() { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } + /** constructor. */ + public static Account getAccountById( + String accountId, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString bsAccountId = ByteString.copyFromUtf8(accountId); + Account request = Account.newBuilder().setAccountId(bsAccountId).build(); + return blockingStubFull.getAccountById(request); + } - /** - * constructor. - */ + /** constructor. */ + public static Account getAccountByIdFromSolidity( + String accountId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString bsAccountId = ByteString.copyFromUtf8(accountId); + Account request = Account.newBuilder().setAccountId(bsAccountId).build(); + return blockingStubFull.getAccountById(request); + } - public static byte[] getAddress(ECKey ecKey) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + /** constructor. */ + public static String loadPubKey() { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + char[] buf = new char[0x100]; + return String.valueOf(buf, 32, 130); + } - return ecKey.getAddress(); - } + /** constructor. */ + public static byte[] getAddress(ECKey ecKey) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - /** - * constructor. - */ + return ecKey.getAddress(); + } - public static Protocol.Account grpcQueryAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Protocol.Account request = Protocol.Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } + /** constructor. */ + public static Protocol.Account grpcQueryAccount( + byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString addressBs = ByteString.copyFrom(address); + Protocol.Account request = Protocol.Account.newBuilder().setAddress(addressBs).build(); + return blockingStubFull.getAccount(request); + } - /** - * constructor. - */ + /** constructor. */ + public static Protocol.Block getBlock( + long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); + builder.setNum(blockNum); + return blockingStubFull.getBlockByNum(builder.build()); + } - public static Protocol.Block getBlock(long blockNum, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } + /** constructor. */ + public static BlockExtention getBlock2(long blockNum, WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); + builder.setNum(blockNum); + return blockingStubFull.getBlockByNum2(builder.build()); + } - /** - * constructor. - */ + /** constructor. */ + public static Protocol.Transaction signTransaction( + ECKey ecKey, Protocol.Transaction transaction) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + if (ecKey == null || ecKey.getPrivKey() == null) { + // logger.warn("Warning: Can't sign,there is no private key !!"); + return null; + } + transaction = TransactionUtils.setTimestamp(transaction); + logger.info( + "Txid in sign is " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + return TransactionUtils.sign(transaction, ecKey); + } - public static BlockExtention getBlock2(long blockNum, - WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum2(builder.build()); - } + /** constructor. */ + public static Protocol.Transaction signTransactionForShield( + ECKey ecKey, Protocol.Transaction transaction) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + if (ecKey == null || ecKey.getPrivKey() == null) { + // logger.warn("Warning: Can't sign,there is no private key !!"); + return null; + } + logger.info( + "Txid in sign is " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + return TransactionUtils.sign(transaction, ecKey); + } - /** - * constructor. - */ + /** constructor. */ + public static boolean participateAssetIssue( + byte[] to, + byte[] assertName, + long amount, + byte[] from, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsName = ByteString.copyFrom(assertName); + ByteString bsOwner = ByteString.copyFrom(from); + builder.setToAddress(bsTo); + builder.setAssetName(bsName); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + ParticipateAssetIssueContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - public static Protocol.Transaction signTransaction(ECKey ecKey, - Protocol.Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - //logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - logger.info("Txid in sign is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - return TransactionUtils.sign(transaction, ecKey); + /** constructor. */ + public static Return participateAssetIssue2( + byte[] to, + byte[] assertName, + long amount, + byte[] from, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsName = ByteString.copyFrom(assertName); + ByteString bsOwner = ByteString.copyFrom(from); + builder.setToAddress(bsTo); + builder.setAssetName(bsName); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + ParticipateAssetIssueContract contract = builder.build(); + + TransactionExtention transactionExtention = blockingStubFull.participateAssetIssue2(contract); + if (transactionExtention == null) { + return transactionExtention.getResult(); } - - /** - * constructor. - */ - - public static Protocol.Transaction signTransactionForShield(ECKey ecKey, - Protocol.Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - //logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - logger.info("Txid in sign is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - return TransactionUtils.sign(transaction, ecKey); + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return ret; } - - - /** - * constructor. - */ - - public static boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, - byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - - public static Return participateAssetIssue2(byte[] to, byte[] assertName, long amount, - byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.participateAssetIssue2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - //Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return response; - } else { - return ret; - } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return transactionExtention.getResult(); } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - /** - * constructor. - */ - - public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Protocol.Block currentBlock = blockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Protocol.Account beforeFronzen = queryAccount(priKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); + // Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return response; + } else { + return ret; + } + } - FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); + /** constructor. */ + public static Boolean freezeBalance( + byte[] addRess, + long freezeBalance, + long freezeDuration, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + byte[] address = addRess; + long frozenBalance = freezeBalance; + long frozenDuration = freezeDuration; + // String priKey = testKey002; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + Protocol.Block currentBlock = + blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Protocol.Account beforeFronzen = queryAccount(priKey, blockingStubFull); + Long beforeFrozenBalance = 0L; + // Long beforeBandwidth = beforeFronzen.getBandwidth(); + if (beforeFronzen.getFrozenCount() != 0) { + beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); + // beforeBandwidth = beforeFronzen.getBandwidth(); + // logger.info(Long.toString(beforeFronzen.getBandwidth())); + logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); + } + + FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); + ByteString byteAddreess = ByteString.copyFrom(address); + + builder + .setOwnerAddress(byteAddreess) + .setFrozenBalance(frozenBalance) + .setFrozenDuration(frozenDuration); + + FreezeBalanceContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction = null"); + return false; + } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + transaction = TransactionUtils.setTimestamp(transaction); + transaction = TransactionUtils.sign(transaction, ecKey); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); + return response.getResult(); /* Long afterBlockNum = 0L; while (afterBlockNum < beforeBlockNum) { @@ -798,219 +819,224 @@ public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long fre logger.info("beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" + afterFrozenBalance.toString()); Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance);*/ - } - - /** - * constructor. - */ - - public static Return freezeBalance2(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Protocol.Block currentBlock = blockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Protocol.Account beforeFronzen = queryAccount(priKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.freezeBalance2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - if (response.getResult() == false) { - return response; - } - - Long afterBlockNum = 0L; - - while (afterBlockNum < beforeBlockNum) { - Protocol.Block currentBlock1 = blockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - } + } - Protocol.Account afterFronzen = queryAccount(priKey, blockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - logger.info( - "beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" + afterFrozenBalance - .toString()); - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - return ret; + /** constructor. */ + public static Return freezeBalance2( + byte[] addRess, + long freezeBalance, + long freezeDuration, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + byte[] address = addRess; + long frozenBalance = freezeBalance; + long frozenDuration = freezeDuration; + // String priKey = testKey002; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + Protocol.Block currentBlock = + blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Protocol.Account beforeFronzen = queryAccount(priKey, blockingStubFull); + Long beforeFrozenBalance = 0L; + // Long beforeBandwidth = beforeFronzen.getBandwidth(); + if (beforeFronzen.getFrozenCount() != 0) { + beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); + // beforeBandwidth = beforeFronzen.getBandwidth(); + // logger.info(Long.toString(beforeFronzen.getBandwidth())); + logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); + } + + FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); + ByteString byteAddreess = ByteString.copyFrom(address); + + builder + .setOwnerAddress(byteAddreess) + .setFrozenBalance(frozenBalance) + .setFrozenDuration(frozenDuration); + + FreezeBalanceContract contract = builder.build(); + + GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.freezeBalance2(contract); + if (transactionExtention == null) { + return transactionExtention.getResult(); } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return ret; + } else { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return transactionExtention.getResult(); + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - /** - * constructor. - */ - - public static Boolean unFreezeBalance(byte[] address, String priKey, int resourceCode, - byte[] receiverAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess).setResourceValue(resourceCode); - if (receiverAddress != null) { - ByteString receiverAddressBytes = ByteString.copyFrom(receiverAddress); - builder.setReceiverAddress(receiverAddressBytes); - } - - UnfreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + transaction = TransactionUtils.setTimestamp(transaction); + transaction = TransactionUtils.sign(transaction, ecKey); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); + if (response.getResult() == false) { + return response; } - /** - * constructor. - */ + Long afterBlockNum = 0L; - public static Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - Integer times = 0; - while (times++ <= 2) { - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - continue; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - return false; + while (afterBlockNum < beforeBlockNum) { + Protocol.Block currentBlock1 = + blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); } - /** - * constructor. - */ + Protocol.Account afterFronzen = queryAccount(priKey, blockingStubFull); + Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); + logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); + logger.info( + "beforefronen" + + beforeFrozenBalance.toString() + + " afterfronzen" + + afterFrozenBalance.toString()); + Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); + return ret; + } - public static String sendcoinGetTransactionHex(byte[] to, long amount, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - Integer times = 0; - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; + /** constructor. */ + public static Boolean unFreezeBalance( + byte[] address, + String priKey, + int resourceCode, + byte[] receiverAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract.newBuilder(); + ByteString byteAddreess = ByteString.copyFrom(address); + builder.setOwnerAddress(byteAddreess).setResourceValue(resourceCode); + if (receiverAddress != null) { + ByteString receiverAddressBytes = ByteString.copyFrom(receiverAddress); + builder.setReceiverAddress(receiverAddressBytes); + } + + UnfreezeBalanceContract contract = builder.build(); + Transaction transaction = blockingStubFull.unfreezeBalance(contract); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - } - transaction = signTransaction(ecKey, transaction); - logger.info("HEX transaction is : " + "transaction hex string is " + ByteArray - .toHexString(transaction.toByteArray())); - return ByteArray.toHexString(transaction.toByteArray()); - } + return response.getResult(); + } + /** constructor. */ + public static Boolean sendcoin( + byte[] to, + long amount, + byte[] owner, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + // String priKey = testKey002; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + Integer times = 0; + while (times++ <= 2) { + + TransferContract.Builder builder = TransferContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsOwner = ByteString.copyFrom(owner); + builder.setToAddress(bsTo); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction ==null"); + continue; + } + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } + return false; + } - /** - * constructor. - */ + /** constructor. */ + public static String sendcoinGetTransactionHex( + byte[] to, + long amount, + byte[] owner, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + Integer times = 0; + TransferContract.Builder builder = TransferContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsOwner = ByteString.copyFrom(owner); + builder.setToAddress(bsTo); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction ==null"); + return null; + } + transaction = signTransaction(ecKey, transaction); + logger.info( + "HEX transaction is : " + + "transaction hex string is " + + ByteArray.toHexString(transaction.toByteArray())); + return ByteArray.toHexString(transaction.toByteArray()); + } - public static Boolean cancelDeferredTransactionById(String txid, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + /** constructor. */ + public static Boolean cancelDeferredTransactionById( + String txid, byte[] owner, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; /*Contract.CancelDeferredTransactionContract.Builder builder = Contract .CancelDeferredTransactionContract.newBuilder(); builder.setTransactionId(ByteString.copyFrom(ByteArray.fromHexString(txid))); @@ -1044,550 +1070,584 @@ public static Boolean cancelDeferredTransactionById(String txid, byte[] owner, S .getTxid().toByteArray())); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response.getResult();*/ - return null; - } + return null; + } - /** - * constructor. - */ + /** constructor. */ + public static String cancelDeferredTransactionByIdGetTxid( + String txid, byte[] owner, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + return null; + } - public static String cancelDeferredTransactionByIdGetTxid(String txid, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - return null; + /** constructor. */ + public static Boolean sendcoinDelayed( + byte[] to, + long amount, + long delaySeconds, + byte[] owner, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); } + final ECKey ecKey = temKey; + TransferContract.Builder builder = TransferContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsOwner = ByteString.copyFrom(owner); + builder.setToAddress(bsTo); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); - /** - * constructor. - */ - - public static Boolean sendcoinDelayed(byte[] to, long amount, long delaySeconds, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + TransferContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); + // transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction ==null"); + return false; + } + transaction = signTransaction(ecKey, transaction); + logger.info( + "Txid is " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + /** constructor. */ + public static boolean transferAssetDelay( + byte[] to, + byte[] assertName, + long amount, + long delaySeconds, + byte[] address, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsName = ByteString.copyFrom(assertName); + ByteString bsOwner = ByteString.copyFrom(address); + builder.setToAddress(bsTo); + builder.setAssetName(bsName); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferAssetContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); + // transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + if (transaction == null) { + logger.info("transaction == null"); + } else { + logger.info("transaction.getRawData().getContractCount() == 0"); + } + return false; } + transaction = signTransaction(ecKey, transaction); + logger.info( + "Txid is " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - /** - * constructor. - */ - - public static boolean transferAssetDelay(byte[] to, byte[] assertName, long amount, - long delaySeconds, byte[] address, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - logger.info("transaction == null"); - } else { - logger.info("transaction.getRawData().getContractCount() == 0"); - } - return false; - } - transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); + /** constructor. */ + public static String createAccountDelayGetTxid( + byte[] ownerAddress, + byte[] newAddress, + Long delaySeconds, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setAccountAddress(ByteString.copyFrom(newAddress)); + AccountCreateContract contract = builder.build(); + Transaction transaction = blockingStubFull.createAccount(contract); + // transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); } + transaction = signTransaction(ecKey, transaction); + logger.info( + "Txid is " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } - /** - * constructor. - */ + /** constructor. */ + public static String updateAccountDelayGetTxid( + byte[] addressBytes, + byte[] accountNameBytes, + Long delaySeconds, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); + ByteString basAddreess = ByteString.copyFrom(addressBytes); + ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); + + builder.setAccountName(bsAccountName); + builder.setOwnerAddress(basAddreess); + + AccountUpdateContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.updateAccount(contract); + // transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("Please check!!! transaction == null"); + return null; + } + transaction = signTransaction(ecKey, transaction); + logger.info( + "Txid is " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } - public static String createAccountDelayGetTxid(byte[] ownerAddress, byte[] newAddress, - Long delaySeconds, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - Transaction transaction = blockingStubFull.createAccount(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + /** constructor. */ + public static String unfreezeAssetDelayGetTxid( + byte[] address, + Long delaySeconds, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + UnfreezeAssetContract.Builder builder = UnfreezeAssetContract.newBuilder(); + ByteString byteAddreess = ByteString.copyFrom(address); + builder.setOwnerAddress(byteAddreess); + + UnfreezeAssetContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.unfreezeAsset(contract); + // transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("Please check!!! transaction == null"); + return null; } + transaction = signTransaction(ecKey, transaction); + logger.info( + "Txid is " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } - /** - * constructor. - */ + /** constructor. */ + public static String transferAssetDelayGetTxid( + byte[] to, + byte[] assertName, + long amount, + long delaySeconds, + byte[] address, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsName = ByteString.copyFrom(assertName); + ByteString bsOwner = ByteString.copyFrom(address); + builder.setToAddress(bsTo); + builder.setAssetName(bsName); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferAssetContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); + // transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - public static String updateAccountDelayGetTxid(byte[] addressBytes, byte[] accountNameBytes, - Long delaySeconds, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(addressBytes); - ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); - - builder.setAccountName(bsAccountName); - builder.setOwnerAddress(basAddreess); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + if (transaction == null) { + logger.info("transaction == null"); + } else { + logger.info("transaction.getRawData().getContractCount() == 0"); + } + return null; + } + transaction = signTransaction(ecKey, transaction); + logger.info( + "Txid is " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } - AccountUpdateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateAccount(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return null; - } - transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + /** constructor. */ + public static String sendcoinDelayedGetTxid( + byte[] to, + long amount, + long delaySeconds, + byte[] owner, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); } + final ECKey ecKey = temKey; - /** - * constructor. - */ + TransferContract.Builder builder = TransferContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsOwner = ByteString.copyFrom(owner); + builder.setToAddress(bsTo); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); - public static String unfreezeAssetDelayGetTxid(byte[] address, Long delaySeconds, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + TransferContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess); + // transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - UnfreezeAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.unfreezeAsset(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return null; - } - transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction ==null"); + return null; } + transaction = signTransaction(ecKey, transaction); + logger.info( + "Txid is " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } + /** constructor. */ + public static String setAccountIdDelayGetTxid( + byte[] accountIdBytes, + long delaySeconds, + byte[] ownerAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + SetAccountIdContract.Builder builder = SetAccountIdContract.newBuilder(); + ByteString bsAddress = ByteString.copyFrom(owner); + ByteString bsAccountId = ByteString.copyFrom(accountIdBytes); + builder.setAccountId(bsAccountId); + builder.setOwnerAddress(bsAddress); + SetAccountIdContract contract = builder.build(); + Transaction transaction = blockingStubFull.setAccountId(contract); + // transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - /** - * constructor. - */ - - public static String transferAssetDelayGetTxid(byte[] to, byte[] assertName, long amount, - long delaySeconds, byte[] address, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - logger.info("transaction == null"); - } else { - logger.info("transaction.getRawData().getContractCount() == 0"); - } - return null; - } - transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); } + transaction = signTransaction(ecKey, transaction); + logger.info( + "Txid is " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } - /** - * constructor. - */ - - public static String sendcoinDelayedGetTxid(byte[] to, long amount, long delaySeconds, - byte[] owner, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + /** constructor. */ + public static String updateAssetDelay( + byte[] address, + byte[] description, + byte[] url, + long newLimit, + long newPublicLimit, + long delaySeconds, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); + ByteString basAddreess = ByteString.copyFrom(address); + builder.setDescription(ByteString.copyFrom(description)); + builder.setUrl(ByteString.copyFrom(url)); + builder.setNewLimit(newLimit); + builder.setNewPublicLimit(newPublicLimit); + builder.setOwnerAddress(basAddreess); + + UpdateAssetContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.updateAsset(contract); + // transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + return null; } - /** - * constructor. - */ - - public static String setAccountIdDelayGetTxid(byte[] accountIdBytes, long delaySeconds, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SetAccountIdContract.Builder builder = SetAccountIdContract.newBuilder(); - ByteString bsAddress = ByteString.copyFrom(owner); - ByteString bsAccountId = ByteString.copyFrom(accountIdBytes); - builder.setAccountId(bsAccountId); - builder.setOwnerAddress(bsAddress); - SetAccountIdContract contract = builder.build(); - Transaction transaction = blockingStubFull.setAccountId(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - transaction = signTransaction(ecKey, transaction); + transaction = signTransaction(ecKey, transaction); + logger.info( + "Txid is " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + /** constructor. */ + public static Return sendcoin2( + byte[] to, + long amount, + byte[] owner, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + // Protocol.Account search = queryAccount(priKey, blockingStubFull); + + TransferContract.Builder builder = TransferContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsOwner = ByteString.copyFrom(owner); + builder.setToAddress(bsTo); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.createTransaction2(contract); + if (transactionExtention == null) { + return transactionExtention.getResult(); } - - /** - * constructor. - */ - - public static String updateAssetDelay(byte[] address, byte[] description, byte[] url, - long newLimit, long newPublicLimit, long delaySeconds, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(address); - builder.setDescription(ByteString.copyFrom(description)); - builder.setUrl(ByteString.copyFrom(url)); - builder.setNewLimit(newLimit); - builder.setNewPublicLimit(newPublicLimit); - builder.setOwnerAddress(basAddreess); - - UpdateAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateAsset(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return null; - } - - transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return ret; + } else { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); } - - /** - * constructor. - */ - - public static Return sendcoin2(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.createTransaction2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } - return ret; + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return transactionExtention.getResult(); } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - /** - * constructor. - */ + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); + return response; + } + return ret; + } - public static String sendcoinGetTransactionId(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - //Test raw data + /** constructor. */ + public static String sendcoinGetTransactionId( + byte[] to, + long amount, + byte[] owner, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + // String priKey = testKey002; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + // Protocol.Account search = queryAccount(priKey, blockingStubFull); + + TransferContract.Builder builder = TransferContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsOwner = ByteString.copyFrom(owner); + builder.setToAddress(bsTo); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction ==null"); + return null; + } + // Test raw data /* Protocol.Transaction.raw.Builder builder1 = transaction.getRawData().toBuilder(); builder1.setData(ByteString.copyFromUtf8("12345678")); Transaction.Builder builder2 = transaction.toBuilder(); builder2.setRawData(builder1); transaction = builder2.build();*/ - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - //logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return null; - } else { - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** - * constructor. - */ - - public static Optional getTransactionById(String txId, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction = blockingStubFull.getTransactionById(request); - - return Optional.ofNullable(transaction); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); + return null; + } else { + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } + } - /** - * constructor. - */ + /** constructor. */ + public static Optional getTransactionById( + String txId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); + BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); + Transaction transaction = blockingStubFull.getTransactionById(request); - public static Optional getTransactionById(String txId, - WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction = blockingStubFull.getTransactionById(request); - return Optional.ofNullable(transaction); - } + return Optional.ofNullable(transaction); + } - /** - * constructor. - */ - public static Long getAssetBalanceByAssetId(ByteString assetId, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Account assetOwnerAccount = queryAccount(priKey, blockingStubFull); - Long assetOwnerAssetBalance = 0L; - for (String id : assetOwnerAccount.getAssetV2Map().keySet()) { - if (assetId.toStringUtf8().equalsIgnoreCase(id)) { - assetOwnerAssetBalance = assetOwnerAccount.getAssetV2Map().get(id); - } - } - logger.info("asset balance is " + assetOwnerAssetBalance); - return assetOwnerAssetBalance; - } + /** constructor. */ + public static Optional getTransactionById( + String txId, WalletGrpc.WalletBlockingStub blockingStubFull) { + ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); + BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); + Transaction transaction = blockingStubFull.getTransactionById(request); + return Optional.ofNullable(transaction); + } + /** constructor. */ + public static Long getAssetBalanceByAssetId( + ByteString assetId, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Account assetOwnerAccount = queryAccount(priKey, blockingStubFull); + Long assetOwnerAssetBalance = 0L; + for (String id : assetOwnerAccount.getAssetV2Map().keySet()) { + if (assetId.toStringUtf8().equalsIgnoreCase(id)) { + assetOwnerAssetBalance = assetOwnerAccount.getAssetV2Map().get(id); + } + } + logger.info("asset balance is " + assetOwnerAssetBalance); + return assetOwnerAssetBalance; + } /* public static Optional getDeferredTransactionById(String txId, @@ -1602,308 +1662,302 @@ public static Optional getDeferredTransactionById(String tx } */ + /** constructor. */ + public static Optional getTransactionByIdSolidity( + String txId, WalletGrpc.WalletBlockingStub blockingStubSolidity) { + ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); + BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); + Transaction transaction = blockingStubSolidity.getTransactionById(request); + return Optional.ofNullable(transaction); + } - /** - * constructor. - */ - - public static Optional getTransactionByIdSolidity(String txId, - WalletGrpc.WalletBlockingStub blockingStubSolidity) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction = blockingStubSolidity.getTransactionById(request); - return Optional.ofNullable(transaction); - } - - /** - * constructor. - */ - - public static String printTransaction(Transaction transaction) { - String result = ""; - result += "hash: "; - result += "\n"; - result += ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.toByteArray())); - result += "\n"; - result += "txid: "; - result += "\n"; - result += ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - result += "\n"; - - if (transaction.getRawData() != null) { - result += "raw_data: "; - result += "\n"; - result += "{"; - result += "\n"; - result += printTransactionRow(transaction.getRawData()); - result += "}"; - result += "\n"; - } + /** constructor. */ + public static String printTransaction(Transaction transaction) { + String result = ""; + result += "hash: "; + result += "\n"; + result += + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.toByteArray())); + result += "\n"; + result += "txid: "; + result += "\n"; + result += + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + result += "\n"; + + if (transaction.getRawData() != null) { + result += "raw_data: "; + result += "\n"; + result += "{"; + result += "\n"; + result += printTransactionRow(transaction.getRawData()); + result += "}"; + result += "\n"; + } + + return result; + } - return result; - } + /** constructor. */ + public static long printTransactionRow(Transaction.raw raw) { + long timestamp = raw.getTimestamp(); - /** - * constructor. - */ + return timestamp; + } - public static long printTransactionRow(Transaction.raw raw) { - long timestamp = raw.getTimestamp(); + /** constructor. */ + public static boolean updateAsset( + byte[] address, + byte[] description, + byte[] url, + long newLimit, + long newPublicLimit, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); + ByteString basAddreess = ByteString.copyFrom(address); + builder.setDescription(ByteString.copyFrom(description)); + builder.setUrl(ByteString.copyFrom(url)); + builder.setNewLimit(newLimit); + builder.setNewPublicLimit(newPublicLimit); + builder.setOwnerAddress(basAddreess); + + UpdateAssetContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.updateAsset(contract); - return timestamp; + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + return false; } - /** - * constructor. - */ - - public static boolean updateAsset(byte[] address, byte[] description, byte[] url, long newLimit, - long newPublicLimit, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(address); - builder.setDescription(ByteString.copyFrom(description)); - builder.setUrl(ByteString.copyFrom(url)); - builder.setNewLimit(newLimit); - builder.setNewPublicLimit(newPublicLimit); - builder.setOwnerAddress(basAddreess); - - UpdateAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); + /** constructor. */ + public static Return updateAsset2( + byte[] address, + byte[] description, + byte[] url, + long newLimit, + long newPublicLimit, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); + ByteString basAddreess = ByteString.copyFrom(address); + builder.setDescription(ByteString.copyFrom(description)); + builder.setUrl(ByteString.copyFrom(url)); + builder.setNewLimit(newLimit); + builder.setNewPublicLimit(newPublicLimit); + builder.setOwnerAddress(basAddreess); + + UpdateAssetContract contract = builder.build(); + + TransactionExtention transactionExtention = blockingStubFull.updateAsset2(contract); + if (transactionExtention == null) { + return transactionExtention.getResult(); } - - /** - * constructor. - */ - - public static Return updateAsset2(byte[] address, byte[] description, byte[] url, long newLimit, - long newPublicLimit, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(address); - builder.setDescription(ByteString.copyFrom(description)); - builder.setUrl(ByteString.copyFrom(url)); - builder.setNewLimit(newLimit); - builder.setNewPublicLimit(newPublicLimit); - builder.setOwnerAddress(basAddreess); - - UpdateAssetContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.updateAsset2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - //logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } - return ret; + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return ret; + } else { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return transactionExtention.getResult(); } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - /** - * constructor. - */ + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); + return response; + } + return ret; + } - public static boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - logger.info("transaction == null"); - } else { - logger.info("transaction.getRawData().getContractCount() == 0"); - } - return false; - } - transaction = signTransaction(ecKey, transaction); + /** constructor. */ + public static boolean transferAsset( + byte[] to, + byte[] assertName, + long amount, + byte[] address, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsName = ByteString.copyFrom(assertName); + ByteString bsOwner = ByteString.copyFrom(address); + builder.setToAddress(bsTo); + builder.setAssetName(bsName); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferAssetContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + if (transaction == null) { + logger.info("transaction == null"); + } else { + logger.info("transaction.getRawData().getContractCount() == 0"); + } + return false; } + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - /** - * constructor. - */ - - public static boolean updateAccount(byte[] addressBytes, byte[] accountNameBytes, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + /** constructor. */ + public static boolean updateAccount( + byte[] addressBytes, + byte[] accountNameBytes, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; - AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(addressBytes); - ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); + AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); + ByteString basAddreess = ByteString.copyFrom(addressBytes); + ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); - builder.setAccountName(bsAccountName); - builder.setOwnerAddress(basAddreess); + builder.setAccountName(bsAccountName); + builder.setOwnerAddress(basAddreess); - AccountUpdateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateAccount(contract); + AccountUpdateContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.updateAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - - public static boolean waitSolidityNodeSynFullNodeData( - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Block solidityCurrentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Integer wait = 0; - logger.info("Fullnode block num is " + currentBlock.getBlockHeader().getRawData().getNumber()); - - while (solidityCurrentBlock.getBlockHeader().getRawData().getNumber() - < currentBlock.getBlockHeader().getRawData().getNumber() + 1 && wait < ((getWitnessNum(blockingStubFull) >= 27) - ? 27 : getWitnessNum(blockingStubFull) + 1)) { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - logger.info("Soliditynode num is " + solidityCurrentBlock.getBlockHeader().getRawData() - .getNumber()); - solidityCurrentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - if (wait == 24) { - logger.info("Didn't syn,skip to next case."); - return false; - } - wait++; - } - return true; - } - - /** - * constructor. - */ - - public static boolean waitProduceNextBlock(WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - final Long currentNum = currentBlock.getBlockHeader().getRawData().getNumber(); - - Block nextBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); - - Integer wait = 0; - logger.info( - "Block num is " + currentBlock.getBlockHeader().getRawData().getNumber()); - while (nextNum <= currentNum + 1 && wait <= 45) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - //logger.info("Wait to produce next block"); - nextBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); - if (wait == 45) { - logger.info("These 45 second didn't produce a block,please check."); - return false; - } - wait++; - } - logger.info("quit normally"); - return true; + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("Please check!!! transaction == null"); + return false; } + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - /** - * constructor. - */ + /** constructor. */ + public static boolean waitSolidityNodeSynFullNodeData( + WalletGrpc.WalletBlockingStub blockingStubFull, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Block solidityCurrentBlock = + blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Integer wait = 0; + logger.info("Fullnode block num is " + currentBlock.getBlockHeader().getRawData().getNumber()); + + while (solidityCurrentBlock.getBlockHeader().getRawData().getNumber() + < currentBlock.getBlockHeader().getRawData().getNumber() + 1 + && wait + < ((getWitnessNum(blockingStubFull) >= 27) + ? 27 + : getWitnessNum(blockingStubFull) + 1)) { + try { + Thread.sleep(3000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info( + "Soliditynode num is " + solidityCurrentBlock.getBlockHeader().getRawData().getNumber()); + solidityCurrentBlock = + blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + if (wait == 24) { + logger.info("Didn't syn,skip to next case."); + return false; + } + wait++; + } + return true; + } - public static AccountNetMessage getAccountNet(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccountNet(request); + /** constructor. */ + public static boolean waitProduceNextBlock(WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + final Long currentNum = currentBlock.getBlockHeader().getRawData().getNumber(); + + Block nextBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); + + Integer wait = 0; + logger.info("Block num is " + currentBlock.getBlockHeader().getRawData().getNumber()); + while (nextNum <= currentNum + 1 && wait <= 45) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + // logger.info("Wait to produce next block"); + nextBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); + if (wait == 45) { + logger.info("These 45 second didn't produce a block,please check."); + return false; + } + wait++; } + logger.info("quit normally"); + return true; + } + + /** constructor. */ + public static AccountNetMessage getAccountNet( + byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString addressBs = ByteString.copyFrom(address); + Account request = Account.newBuilder().setAddress(addressBs).build(); + return blockingStubFull.getAccountNet(request); + } /* public static byte[] addPreFix(byte[] address) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); @@ -1925,5425 +1979,5650 @@ public static AccountNetMessage getAccountNet(byte[] address, }*/ - /** - * constructor. - */ + /** constructor. */ + public static byte[] getFinalAddress(String priKey) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + WalletClient walletClient; + walletClient = new WalletClient(priKey); + // walletClient.init(0); + return walletClient.getAddress(); + } - public static byte[] getFinalAddress(String priKey) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - WalletClient walletClient; - walletClient = new WalletClient(priKey); - //walletClient.init(0); - return walletClient.getAddress(); + /** constructor. */ + public static String createAccountGetTxid( + byte[] ownerAddress, + byte[] newAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setAccountAddress(ByteString.copyFrom(newAddress)); + AccountCreateContract contract = builder.build(); + Transaction transaction = blockingStubFull.createAccount(contract); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); } - - /** - * constructor. - */ - - public static String createAccountGetTxid(byte[] ownerAddress, byte[] newAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - Transaction transaction = blockingStubFull.createAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - //logger.info("brodacast succesfully"); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + // logger.info("brodacast succesfully"); + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } + } - /** - * constructor. - */ - - public static boolean createAccount(byte[] ownerAddress, byte[] newAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - Transaction transaction = blockingStubFull.createAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); + /** constructor. */ + public static boolean createAccount( + byte[] ownerAddress, + byte[] newAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setAccountAddress(ByteString.copyFrom(newAddress)); + AccountCreateContract contract = builder.build(); + Transaction transaction = blockingStubFull.createAccount(contract); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); } + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - /** - * constructor. - */ - - public static Return createAccount2(byte[] ownerAddress, byte[] newAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.createAccount2(contract); + /** constructor. */ + public static Return createAccount2( + byte[] ownerAddress, + byte[] newAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setAccountAddress(ByteString.copyFrom(newAddress)); + AccountCreateContract contract = builder.build(); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + TransactionExtention transactionExtention = blockingStubFull.createAccount2(contract); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - //logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } - return ret; + if (transactionExtention == null) { + return transactionExtention.getResult(); + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return ret; + } else { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return transactionExtention.getResult(); } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - /** - * constructor. - */ + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); + return response; + } + return ret; + } - public static boolean voteWitness(byte[] ownerAddress, String priKey, - HashMap witnessMap, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + /** constructor. */ + public static boolean voteWitness( + byte[] ownerAddress, + String priKey, + HashMap witnessMap, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + VoteWitnessContract.Builder builder = VoteWitnessContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + for (byte[] address : witnessMap.keySet()) { + VoteWitnessContract.Vote.Builder voteBuilder = VoteWitnessContract.Vote.newBuilder(); + voteBuilder.setVoteAddress(ByteString.copyFrom(address)); + voteBuilder.setVoteCount(witnessMap.get(address)); + builder.addVotes(voteBuilder.build()); + } - - byte[] owner = ownerAddress; - VoteWitnessContract.Builder builder = VoteWitnessContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - for (byte[] address : witnessMap.keySet()) { - VoteWitnessContract.Vote.Builder voteBuilder = VoteWitnessContract.Vote.newBuilder(); - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(witnessMap.get(address)); - builder.addVotes(voteBuilder.build()); - } - - VoteWitnessContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.voteWitnessAccount2(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } - - - /** - * constructor. - */ - - public static boolean createProposal(byte[] ownerAddress, String priKey, - HashMap parametersMap, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalCreateContract.Builder builder = ProposalCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.putAllParameters(parametersMap); - - ProposalCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalCreate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } - - /** - * constructor. - */ - - public static boolean approveProposal(byte[] ownerAddress, String priKey, long id, - boolean isAddApproval, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalApproveContract.Builder builder = ProposalApproveContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setProposalId(id); - builder.setIsAddApproval(isAddApproval); - ProposalApproveContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalApprove(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - - public static boolean deleteProposal(byte[] ownerAddress, String priKey, long id, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalDeleteContract.Builder builder = ProposalDeleteContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setProposalId(id); - - ProposalDeleteContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalDelete(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - - public static boolean printAddress(String key) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - logger.info(key); - logger.info(ByteArray.toHexString(getFinalAddress(key))); - logger.info(Base58.encode58Check(getFinalAddress(key))); - return true; - } - - /** - * constructor. - */ - - public static String getAddressString(String key) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - return Base58.encode58Check(getFinalAddress(key)); + VoteWitnessContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.voteWitnessAccount2(contract); + if (transactionExtention == null) { + return false; } - - /** - * constructor. - */ - - - public static ArrayList getAddressInfo(String key) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ArrayList accountList = new ArrayList(); - accountList.add(key); - accountList.add(ByteArray.toHexString(getFinalAddress(key))); - accountList.add(Base58.encode58Check(getFinalAddress(key))); - return accountList; + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; } - - /** - * constructor. - */ - - public static boolean setAccountId(byte[] accountIdBytes, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SetAccountIdContract.Builder builder = SetAccountIdContract.newBuilder(); - ByteString bsAddress = ByteString.copyFrom(owner); - ByteString bsAccountId = ByteString.copyFrom(accountIdBytes); - builder.setAccountId(bsAccountId); - builder.setOwnerAddress(bsAddress); - SetAccountIdContract contract = builder.build(); - Transaction transaction = blockingStubFull.setAccountId(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - - public static Boolean freezeBalanceGetTronPower(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, ByteString receiverAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return freezeBalanceForReceiver(addRess, freezeBalance, - freezeDuration, resourceCode, receiverAddress, priKey, blockingStubFull); - } - - /** - * constructor. - */ - - public static Boolean freezeBalanceGetEnergy(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); - - FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - public static AccountResourceMessage getAccountResource(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccountResource(request); - } - - /** - * constructor. - */ - - public static boolean buyStorage(long quantity, byte[] address, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BuyStorageContract.Builder builder = BuyStorageContract.newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddress).setQuant(quantity); - BuyStorageContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.buyStorage(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - public static boolean sellStorage(long quantity, byte[] address, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - SellStorageContract.Builder builder = SellStorageContract.newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddress).setStorageBytes(quantity); - SellStorageContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.sellStorage(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - public static byte[] deployContractFallbackReceive(String contractName, String abiString, - String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, - byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi2(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); - - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - //logger.info("brodacast succesfully"); - return contractAddress; - } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - /** - * constructor. - */ - public static byte[] deployContract(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, - byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); - - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); + return response.getResult(); + } - byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + /** constructor. */ + public static boolean createProposal( + byte[] ownerAddress, + String priKey, + HashMap parametersMap, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + ProposalCreateContract.Builder builder = ProposalCreateContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.putAllParameters(parametersMap); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - //logger.info("brodacast succesfully"); - return contractAddress; - } + ProposalCreateContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.proposalCreate(contract); + if (transactionExtention == null) { + return false; } - - /** - * constructor. - */ - public static byte[] deployContract(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContract(contractName, abiString, code, data, feeLimit, value, - consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, - blockingStubFull); - } - - /** - * constructor. - */ - public static byte[] deployContractFallback(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContractFallbackReceive(contractName, abiString, code, data, feeLimit, value, - consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, - blockingStubFull); - } - - /** - * constructor. - */ - - public static byte[] deployContractForLibrary(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - String libraryAddress, String priKey, byte[] ownerAddress, String compilerVersion, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(1000L); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - if (compilerVersion.equals("v5") || compilerVersion.equals("V5")) { - byteCode = replaceLibraryAddresscompilerVersion(code, libraryAddress, "v5"); - } else { - //old version - byteCode = replaceLibraryAddresscompilerVersion(code, libraryAddress, null); - } - - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(0); - contractBuilder.setTokenId(Long.parseLong("0")); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); - - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - //logger.info("brodacast succesfully"); - return contractAddress; - } - + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; } - - /** - * constructor. - */ - - public static String deployContractAndGetTransactionInfoById(String contractName, - String abiString, String code, String data, Long feeLimit, long value, - long consumeUserResourcePercent, String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContractAndGetTransactionInfoById(contractName, abiString, code, data, feeLimit, - value, consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, - blockingStubFull); + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - /** - * constructor. - */ - - public static String deployContractAndGetTransactionInfoById(String contractName, - String abiString, String code, String data, Long feeLimit, long value, - long consumeUserResourcePercent, long originEnergyLimit, String tokenId, long tokenValue, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); - - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); + return response.getResult(); + } - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - byte[] contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - //logger.info("brodacast succesfully"); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } + /** constructor. */ + public static boolean approveProposal( + byte[] ownerAddress, + String priKey, + long id, + boolean isAddApproval, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + ProposalApproveContract.Builder builder = ProposalApproveContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setProposalId(id); + builder.setIsAddApproval(isAddApproval); + ProposalApproveContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.proposalApprove(contract); + if (transactionExtention == null) { + return false; } - - /** - * constructor. - */ - - public static SmartContract.ABI jsonStr2Abi(String jsonStr) { - if (jsonStr == null) { - return null; - } - - JsonParser jsonParser = new JsonParser(); - JsonElement jsonElementRoot = jsonParser.parse(jsonStr); - JsonArray jsonRoot = jsonElementRoot.getAsJsonArray(); - SmartContract.ABI.Builder abiBuilder = SmartContract.ABI.newBuilder(); - for (int index = 0; index < jsonRoot.size(); index++) { - JsonElement abiItem = jsonRoot.get(index); - boolean anonymous = - abiItem.getAsJsonObject().get("anonymous") != null && abiItem.getAsJsonObject() - .get("anonymous").getAsBoolean(); - final boolean constant = - abiItem.getAsJsonObject().get("constant") != null && abiItem.getAsJsonObject() - .get("constant").getAsBoolean(); - final String name = - abiItem.getAsJsonObject().get("name") != null ? abiItem.getAsJsonObject().get("name") - .getAsString() : null; - JsonArray inputs = - abiItem.getAsJsonObject().get("inputs") != null ? abiItem.getAsJsonObject().get("inputs") - .getAsJsonArray() : null; - final JsonArray outputs = - abiItem.getAsJsonObject().get("outputs") != null ? abiItem.getAsJsonObject() - .get("outputs").getAsJsonArray() : null; - String type = - abiItem.getAsJsonObject().get("type") != null ? abiItem.getAsJsonObject().get("type") - .getAsString() : null; - final boolean payable = - abiItem.getAsJsonObject().get("payable") != null && abiItem.getAsJsonObject() - .get("payable").getAsBoolean(); - final String stateMutability = - abiItem.getAsJsonObject().get("stateMutability") != null ? abiItem.getAsJsonObject() - .get("stateMutability").getAsString() : null; - if (type == null) { - logger.error("No type!"); - return null; - } - if (!type.equalsIgnoreCase("fallback") && null == inputs) { - logger.error("No inputs!"); - return null; - } - - SmartContract.ABI.Entry.Builder entryBuilder = SmartContract.ABI.Entry.newBuilder(); - entryBuilder.setAnonymous(anonymous); - entryBuilder.setConstant(constant); - if (name != null) { - entryBuilder.setName(name); - } - - /* { inputs : optional } since fallback function not requires inputs*/ - if (inputs != null) { - for (int j = 0; j < inputs.size(); j++) { - JsonElement inputItem = inputs.get(j); - if (inputItem.getAsJsonObject().get("name") == null - || inputItem.getAsJsonObject().get("type") == null) { - logger.error("Input argument invalid due to no name or no type!"); - return null; - } - String inputName = inputItem.getAsJsonObject().get("name").getAsString(); - String inputType = inputItem.getAsJsonObject().get("type").getAsString(); - ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param.newBuilder(); - JsonElement indexed = inputItem.getAsJsonObject().get("indexed"); - - paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); - paramBuilder.setName(inputName); - paramBuilder.setType(inputType); - entryBuilder.addInputs(paramBuilder.build()); - } - } - - /* { outputs : optional } */ - if (outputs != null) { - for (int k = 0; k < outputs.size(); k++) { - JsonElement outputItem = outputs.get(k); - if (outputItem.getAsJsonObject().get("name") == null - || outputItem.getAsJsonObject().get("type") == null) { - logger.error("Output argument invalid due to no name or no type!"); - return null; - } - String outputName = outputItem.getAsJsonObject().get("name").getAsString(); - String outputType = outputItem.getAsJsonObject().get("type").getAsString(); - SmartContract.ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param - .newBuilder(); - JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); - - paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); - paramBuilder.setName(outputName); - paramBuilder.setType(outputType); - entryBuilder.addOutputs(paramBuilder.build()); - } - } - - entryBuilder.setType(getEntryType(type)); - entryBuilder.setPayable(payable); - if (stateMutability != null) { - entryBuilder.setStateMutability(getStateMutability(stateMutability)); - } - - abiBuilder.addEntrys(entryBuilder.build()); - } - - return abiBuilder.build(); + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; } - - /** - * constructor. - */ - - public static SmartContract.ABI jsonStr2Abi2(String jsonStr) { - if (jsonStr == null) { - return null; - } - - JsonParser jsonParser = new JsonParser(); - JsonElement jsonElementRoot = jsonParser.parse(jsonStr); - JsonArray jsonRoot = jsonElementRoot.getAsJsonArray(); - SmartContract.ABI.Builder abiBuilder = SmartContract.ABI.newBuilder(); - for (int index = 0; index < jsonRoot.size(); index++) { - JsonElement abiItem = jsonRoot.get(index); - boolean anonymous = - abiItem.getAsJsonObject().get("anonymous") != null && abiItem.getAsJsonObject() - .get("anonymous").getAsBoolean(); - final boolean constant = - abiItem.getAsJsonObject().get("constant") != null && abiItem.getAsJsonObject() - .get("constant").getAsBoolean(); - final String name = - abiItem.getAsJsonObject().get("name") != null ? abiItem.getAsJsonObject().get("name") - .getAsString() : null; - JsonArray inputs = - abiItem.getAsJsonObject().get("inputs") != null ? abiItem.getAsJsonObject().get("inputs") - .getAsJsonArray() : null; - final JsonArray outputs = - abiItem.getAsJsonObject().get("outputs") != null ? abiItem.getAsJsonObject() - .get("outputs").getAsJsonArray() : null; - String type = - abiItem.getAsJsonObject().get("type") != null ? abiItem.getAsJsonObject().get("type") - .getAsString() : null; - final boolean payable = - abiItem.getAsJsonObject().get("payable") != null && abiItem.getAsJsonObject() - .get("payable").getAsBoolean(); - final String stateMutability = - abiItem.getAsJsonObject().get("stateMutability") != null ? abiItem.getAsJsonObject() - .get("stateMutability").getAsString() : null; - if (type == null) { - logger.error("No type!"); - return null; - } - if (!type.equalsIgnoreCase("fallback") && !type.equalsIgnoreCase("receive") - && null == inputs) { - logger.error("No inputs!"); - return null; - } - - SmartContract.ABI.Entry.Builder entryBuilder = SmartContract.ABI.Entry.newBuilder(); - entryBuilder.setAnonymous(anonymous); - entryBuilder.setConstant(constant); - if (name != null) { - entryBuilder.setName(name); - } - - /* { inputs : optional } since fallback function not requires inputs*/ - if (inputs != null) { - for (int j = 0; j < inputs.size(); j++) { - JsonElement inputItem = inputs.get(j); - if (inputItem.getAsJsonObject().get("name") == null - || inputItem.getAsJsonObject().get("type") == null) { - logger.error("Input argument invalid due to no name or no type!"); - return null; - } - String inputName = inputItem.getAsJsonObject().get("name").getAsString(); - String inputType = inputItem.getAsJsonObject().get("type").getAsString(); - ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param.newBuilder(); - JsonElement indexed = inputItem.getAsJsonObject().get("indexed"); - - paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); - paramBuilder.setName(inputName); - paramBuilder.setType(inputType); - entryBuilder.addInputs(paramBuilder.build()); - } - } - - /* { outputs : optional } */ - if (outputs != null) { - for (int k = 0; k < outputs.size(); k++) { - JsonElement outputItem = outputs.get(k); - if (outputItem.getAsJsonObject().get("name") == null - || outputItem.getAsJsonObject().get("type") == null) { - logger.error("Output argument invalid due to no name or no type!"); - return null; - } - String outputName = outputItem.getAsJsonObject().get("name").getAsString(); - String outputType = outputItem.getAsJsonObject().get("type").getAsString(); - SmartContract.ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param - .newBuilder(); - JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); - - paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); - paramBuilder.setName(outputName); - paramBuilder.setType(outputType); - entryBuilder.addOutputs(paramBuilder.build()); - } - } - entryBuilder.setType(getEntryType2(type)); - - if (stateMutability != null) { - entryBuilder.setStateMutability(getStateMutability(stateMutability)); - } - - abiBuilder.addEntrys(entryBuilder.build()); - } - - return abiBuilder.build(); + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } + /** constructor. */ + public static boolean deleteProposal( + byte[] ownerAddress, String priKey, long id, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + ProposalDeleteContract.Builder builder = ProposalDeleteContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setProposalId(id); - /** - * constructor. - */ - - public static SmartContract.ABI.Entry.EntryType getEntryType(String type) { - switch (type) { - case "constructor": - return SmartContract.ABI.Entry.EntryType.Constructor; - case "function": - return SmartContract.ABI.Entry.EntryType.Function; - case "event": - return SmartContract.ABI.Entry.EntryType.Event; - case "fallback": - return SmartContract.ABI.Entry.EntryType.Fallback; - case "error": - return SmartContract.ABI.Entry.EntryType.Error; - default: - return SmartContract.ABI.Entry.EntryType.UNRECOGNIZED; - } + ProposalDeleteContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.proposalDelete(contract); + if (transactionExtention == null) { + return false; } - - /** - * constructor. - */ - public static SmartContract.ABI.Entry.EntryType getEntryType2(String type) { - switch (type) { - case "constructor": - return SmartContract.ABI.Entry.EntryType.Constructor; - case "function": - return SmartContract.ABI.Entry.EntryType.Function; - case "event": - return SmartContract.ABI.Entry.EntryType.Event; - case "fallback": - return SmartContract.ABI.Entry.EntryType.Fallback; - case "receive": - return SmartContract.ABI.Entry.EntryType.Receive; - default: - return SmartContract.ABI.Entry.EntryType.UNRECOGNIZED; - } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; } - - /** - * constructor. - */ - - public static SmartContract.ABI.Entry.StateMutabilityType getStateMutability( - String stateMutability) { - switch (stateMutability) { - case "pure": - return SmartContract.ABI.Entry.StateMutabilityType.Pure; - case "view": - return SmartContract.ABI.Entry.StateMutabilityType.View; - case "nonpayable": - return SmartContract.ABI.Entry.StateMutabilityType.Nonpayable; - case "payable": - return SmartContract.ABI.Entry.StateMutabilityType.Payable; - default: - return SmartContract.ABI.Entry.StateMutabilityType.UNRECOGNIZED; - } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - /** - * constructor. - */ + /** constructor. */ + public static boolean printAddress(String key) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + logger.info(key); + logger.info(ByteArray.toHexString(getFinalAddress(key))); + logger.info(Base58.encode58Check(getFinalAddress(key))); + return true; + } - public static byte[] generateContractAddress(Transaction trx, byte[] owneraddress) { + /** constructor. */ + public static String getAddressString(String key) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + return Base58.encode58Check(getFinalAddress(key)); + } - // get owner address - // this address should be as same as the onweraddress in trx, DONNOT modify it - byte[] ownerAddress = owneraddress; + /** constructor. */ + public static ArrayList getAddressInfo(String key) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ArrayList accountList = new ArrayList(); + accountList.add(key); + accountList.add(ByteArray.toHexString(getFinalAddress(key))); + accountList.add(Base58.encode58Check(getFinalAddress(key))); + return accountList; + } - // get tx hash - byte[] txRawDataHash = Sha256Hash - .of(CommonParameter.getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()) - .getBytes(); + /** constructor. */ + public static boolean setAccountId( + byte[] accountIdBytes, + byte[] ownerAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + SetAccountIdContract.Builder builder = SetAccountIdContract.newBuilder(); + ByteString bsAddress = ByteString.copyFrom(owner); + ByteString bsAccountId = ByteString.copyFrom(accountIdBytes); + builder.setAccountId(bsAccountId); + builder.setOwnerAddress(bsAddress); + SetAccountIdContract contract = builder.build(); + Transaction transaction = blockingStubFull.setAccountId(contract); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction == null"); + } + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - // combine - byte[] combined = new byte[txRawDataHash.length + ownerAddress.length]; - System.arraycopy(txRawDataHash, 0, combined, 0, txRawDataHash.length); - System.arraycopy(ownerAddress, 0, combined, txRawDataHash.length, ownerAddress.length); + /** constructor. */ + public static Boolean freezeBalanceGetTronPower( + byte[] addRess, + long freezeBalance, + long freezeDuration, + int resourceCode, + ByteString receiverAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + return freezeBalanceForReceiver( + addRess, + freezeBalance, + freezeDuration, + resourceCode, + receiverAddress, + priKey, + blockingStubFull); + } - return sha3omit12(combined); + /** constructor. */ + public static Boolean freezeBalanceGetEnergy( + byte[] addRess, + long freezeBalance, + long freezeDuration, + int resourceCode, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + byte[] address = addRess; + long frozenBalance = freezeBalance; + long frozenDuration = freezeDuration; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); + ByteString byteAddreess = ByteString.copyFrom(address); + + builder + .setOwnerAddress(byteAddreess) + .setFrozenBalance(frozenBalance) + .setFrozenDuration(frozenDuration) + .setResourceValue(resourceCode); + + FreezeBalanceContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction = null"); + return false; } + transaction = TransactionUtils.setTimestamp(transaction); + transaction = TransactionUtils.sign(transaction, ecKey); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - /** - * constructor. - */ + /** constructor. */ + public static AccountResourceMessage getAccountResource( + byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString addressBs = ByteString.copyFrom(address); + Account request = Account.newBuilder().setAddress(addressBs).build(); + return blockingStubFull.getAccountResource(request); + } - public static SmartContract getContract(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString byteString = ByteString.copyFrom(address); - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(byteString).build(); - logger.info("contract name is " + blockingStubFull.getContract(bytesMessage).getName()); - logger.info("contract address is " + WalletClient.encode58Check(address)); - return blockingStubFull.getContract(bytesMessage); + /** constructor. */ + public static boolean buyStorage( + long quantity, + byte[] address, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + BuyStorageContract.Builder builder = BuyStorageContract.newBuilder(); + ByteString byteAddress = ByteString.copyFrom(address); + builder.setOwnerAddress(byteAddress).setQuant(quantity); + BuyStorageContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.buyStorage(contract); + if (transactionExtention == null) { + return false; } - - /** - * constructor. - */ - - public static SmartContractDataWrapper getContractInfo(byte[] address, - WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString byteString = ByteString.copyFrom(address); - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(byteString).build(); - logger.info( - "contract name is " + blockingStubFull.getContractInfo(bytesMessage).getSmartContract() - .getName()); - logger.info("contract address is " + WalletClient.encode58Check(address)); - return blockingStubFull.getContractInfo(bytesMessage); + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; } - - private static byte[] replaceLibraryAddress(String code, String libraryAddressPair) { - - String[] libraryAddressList = libraryAddressPair.split("[,]"); - - for (int i = 0; i < libraryAddressList.length; i++) { - String cur = libraryAddressList[i]; - - int lastPosition = cur.lastIndexOf(":"); - if (-1 == lastPosition) { - throw new RuntimeException("libraryAddress delimit by ':'"); - } - String libraryName = cur.substring(0, lastPosition); - String addr = cur.substring(lastPosition + 1); - String libraryAddressHex = ByteArray.toHexString(Commons.decodeFromBase58Check(addr)) - .substring(2); - - String repeated = new String(new char[40 - libraryName.length() - 2]).replace("\0", "_"); - String beReplaced = "__" + libraryName + repeated; - Matcher m = Pattern.compile(beReplaced).matcher(code); - code = m.replaceAll(libraryAddressHex); - } - - return Hex.decode(code); + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - private static byte[] replaceLibraryAddress_1(String code, byte[] libraryAddress) { - - String libraryAddressHex = ByteArray.toHexString(libraryAddress).substring(2); + /** constructor. */ + public static boolean sellStorage( + long quantity, + byte[] address, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + SellStorageContract.Builder builder = SellStorageContract.newBuilder(); + ByteString byteAddress = ByteString.copyFrom(address); + builder.setOwnerAddress(byteAddress).setStorageBytes(quantity); + SellStorageContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.sellStorage(contract); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - Matcher m = Pattern.compile("__.*__").matcher(code); - code = m.replaceAll(libraryAddressHex); - return Hex.decode(code); + /** constructor. */ + public static byte[] deployContractFallbackReceive( + String contractName, + String abiString, + String code, + String data, + Long feeLimit, + long value, + long consumeUserResourcePercent, + long originEnergyLimit, + String tokenId, + long tokenValue, + String libraryAddress, + String priKey, + byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + SmartContract.ABI abi = jsonStr2Abi2(abiString); + if (abi == null) { + logger.error("abi is null"); + return null; + } + // byte[] codeBytes = Hex.decode(code); + SmartContract.Builder builder = SmartContract.newBuilder(); + builder.setName(contractName); + builder.setOriginAddress(ByteString.copyFrom(owner)); + builder.setAbi(abi); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + builder.setOriginEnergyLimit(originEnergyLimit); + + if (value != 0) { + + builder.setCallValue(value); + } + + byte[] byteCode; + if (null != libraryAddress) { + byteCode = replaceLibraryAddress(code, libraryAddress); + } else { + byteCode = Hex.decode(code); + } + builder.setBytecode(ByteString.copyFrom(byteCode)); + + Builder contractBuilder = CreateSmartContract.newBuilder(); + contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); + contractBuilder.setCallTokenValue(tokenValue); + contractBuilder.setTokenId(Long.parseLong(tokenId)); + CreateSmartContract contractDeployContract = + contractBuilder.setNewContract(builder.build()).build(); + + TransactionExtention transactionExtention = + blockingStubFull.deployContract(contractDeployContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return null; + } + + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); + + byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; } + transaction = signTransaction(ecKey, transaction); + System.out.println( + "txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + contractAddress = generateContractAddress(transaction, owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - private static byte[] replaceLibraryAddresscompilerVersion(String code, String libraryAddressPair, - String compilerVersion) { + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + // logger.info("brodacast succesfully"); + return contractAddress; + } + } - String[] libraryAddressList = libraryAddressPair.split("[,]"); + /** constructor. */ + public static byte[] deployContract( + String contractName, + String abiString, + String code, + String data, + Long feeLimit, + long value, + long consumeUserResourcePercent, + long originEnergyLimit, + String tokenId, + long tokenValue, + String libraryAddress, + String priKey, + byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + SmartContract.ABI abi = jsonStr2Abi(abiString); + if (abi == null) { + logger.error("abi is null"); + return null; + } + // byte[] codeBytes = Hex.decode(code); + SmartContract.Builder builder = SmartContract.newBuilder(); + builder.setName(contractName); + builder.setOriginAddress(ByteString.copyFrom(owner)); + builder.setAbi(abi); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + builder.setOriginEnergyLimit(originEnergyLimit); + + if (value != 0) { + + builder.setCallValue(value); + } + + byte[] byteCode; + if (null != libraryAddress) { + byteCode = replaceLibraryAddress(code, libraryAddress); + } else { + byteCode = Hex.decode(code); + } + builder.setBytecode(ByteString.copyFrom(byteCode)); + + Builder contractBuilder = CreateSmartContract.newBuilder(); + contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); + contractBuilder.setCallTokenValue(tokenValue); + contractBuilder.setTokenId(Long.parseLong(tokenId)); + CreateSmartContract contractDeployContract = + contractBuilder.setNewContract(builder.build()).build(); + + TransactionExtention transactionExtention = + blockingStubFull.deployContract(contractDeployContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return null; + } + + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); + + byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println( + "txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + contractAddress = generateContractAddress(transaction, owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - for (int i = 0; i < libraryAddressList.length; i++) { - String cur = libraryAddressList[i]; + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + // logger.info("brodacast succesfully"); + return contractAddress; + } + } - int lastPosition = cur.lastIndexOf(":"); - if (-1 == lastPosition) { - throw new RuntimeException("libraryAddress delimit by ':'"); - } - String libraryName = cur.substring(0, lastPosition); - String addr = cur.substring(lastPosition + 1); - String libraryAddressHex; - libraryAddressHex = (new String(Hex.encode(Commons.decodeFromBase58Check(addr)), - StandardCharsets.US_ASCII)).substring(2); + /** constructor. */ + public static byte[] deployContract( + String contractName, + String abiString, + String code, + String data, + Long feeLimit, + long value, + long consumeUserResourcePercent, + String libraryAddress, + String priKey, + byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + return deployContract( + contractName, + abiString, + code, + data, + feeLimit, + value, + consumeUserResourcePercent, + 1000L, + "0", + 0L, + libraryAddress, + priKey, + ownerAddress, + blockingStubFull); + } - String beReplaced; - if (compilerVersion == null) { - //old version - String repeated = new String(new char[40 - libraryName.length() - 2]).replace("\0", "_"); - beReplaced = "__" + libraryName + repeated; - } else if (compilerVersion.equalsIgnoreCase("v5")) { - //0.5.4 version - String libraryNameKeccak256 = ByteArray.toHexString(sha3(ByteArray.fromString(libraryName))) - .substring(0, 34); - beReplaced = "__\\$" + libraryNameKeccak256 + "\\$__"; - } else { - throw new RuntimeException("unknown compiler version."); - } + /** constructor. */ + public static byte[] deployContractFallback( + String contractName, + String abiString, + String code, + String data, + Long feeLimit, + long value, + long consumeUserResourcePercent, + String libraryAddress, + String priKey, + byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + return deployContractFallbackReceive( + contractName, + abiString, + code, + data, + feeLimit, + value, + consumeUserResourcePercent, + 1000L, + "0", + 0L, + libraryAddress, + priKey, + ownerAddress, + blockingStubFull); + } - Matcher m = Pattern.compile(beReplaced).matcher(code); - code = m.replaceAll(libraryAddressHex); - } + /** constructor. */ + public static byte[] deployContractForLibrary( + String contractName, + String abiString, + String code, + String data, + Long feeLimit, + long value, + long consumeUserResourcePercent, + String libraryAddress, + String priKey, + byte[] ownerAddress, + String compilerVersion, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + SmartContract.ABI abi = jsonStr2Abi(abiString); + if (abi == null) { + logger.error("abi is null"); + return null; + } + // byte[] codeBytes = Hex.decode(code); + SmartContract.Builder builder = SmartContract.newBuilder(); + builder.setName(contractName); + builder.setOriginAddress(ByteString.copyFrom(owner)); + builder.setAbi(abi); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + builder.setOriginEnergyLimit(1000L); + + if (value != 0) { + + builder.setCallValue(value); + } + + byte[] byteCode; + if (null != libraryAddress) { + if (compilerVersion.equals("v5") || compilerVersion.equals("V5")) { + byteCode = replaceLibraryAddresscompilerVersion(code, libraryAddress, "v5"); + } else { + // old version + byteCode = replaceLibraryAddresscompilerVersion(code, libraryAddress, null); + } + + } else { + byteCode = Hex.decode(code); + } + builder.setBytecode(ByteString.copyFrom(byteCode)); + + Builder contractBuilder = CreateSmartContract.newBuilder(); + contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); + contractBuilder.setCallTokenValue(0); + contractBuilder.setTokenId(Long.parseLong("0")); + CreateSmartContract contractDeployContract = + contractBuilder.setNewContract(builder.build()).build(); + + TransactionExtention transactionExtention = + blockingStubFull.deployContract(contractDeployContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return null; + } + + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); + + byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println( + "txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + contractAddress = generateContractAddress(transaction, owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - return Hex.decode(code); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + // logger.info("brodacast succesfully"); + return contractAddress; } + } - /** - * constructor. - */ + /** constructor. */ + public static String deployContractAndGetTransactionInfoById( + String contractName, + String abiString, + String code, + String data, + Long feeLimit, + long value, + long consumeUserResourcePercent, + String libraryAddress, + String priKey, + byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + return deployContractAndGetTransactionInfoById( + contractName, + abiString, + code, + data, + feeLimit, + value, + consumeUserResourcePercent, + 1000L, + "0", + 0L, + libraryAddress, + priKey, + ownerAddress, + blockingStubFull); + } - public static boolean updateSetting(byte[] contractAddress, long consumeUserResourcePercent, - String priKey, byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - - UpdateSettingContract updateSettingContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateSetting(updateSettingContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } + /** constructor. */ + public static String deployContractAndGetTransactionInfoById( + String contractName, + String abiString, + String code, + String data, + Long feeLimit, + long value, + long consumeUserResourcePercent, + long originEnergyLimit, + String tokenId, + long tokenValue, + String libraryAddress, + String priKey, + byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + SmartContract.ABI abi = jsonStr2Abi(abiString); + if (abi == null) { + logger.error("abi is null"); + return null; + } + // byte[] codeBytes = Hex.decode(code); + SmartContract.Builder builder = SmartContract.newBuilder(); + builder.setName(contractName); + builder.setOriginAddress(ByteString.copyFrom(owner)); + builder.setAbi(abi); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + builder.setOriginEnergyLimit(originEnergyLimit); + + if (value != 0) { + + builder.setCallValue(value); + } + + byte[] byteCode; + if (null != libraryAddress) { + byteCode = replaceLibraryAddress(code, libraryAddress); + } else { + byteCode = Hex.decode(code); + } + builder.setBytecode(ByteString.copyFrom(byteCode)); + + Builder contractBuilder = CreateSmartContract.newBuilder(); + contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); + contractBuilder.setCallTokenValue(tokenValue); + contractBuilder.setTokenId(Long.parseLong(tokenId)); + CreateSmartContract contractDeployContract = + contractBuilder.setNewContract(builder.build()).build(); + + TransactionExtention transactionExtention = + blockingStubFull.deployContract(contractDeployContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return null; + } + + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); - public static boolean updateSettingDelay(byte[] contractAddress, long consumeUserResourcePercent, - long delaySeconds, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - - UpdateSettingContract updateSettingContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateSetting(updateSettingContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - /* transactionExtention = TransactionUtils.setDelaySecondsToExtension( - transactionExtention, delaySeconds); if (transactionExtention == null) { - return false; + return null; } Return ret = transactionExtention.getResult(); if (!ret.getResult()) { System.out.println("Code = " + ret.getCode()); System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; + return null; } Transaction transaction = transactionExtention.getTransaction(); if (transaction == null || transaction.getRawData().getContractCount() == 0) { System.out.println("Transaction is empty"); - return false; + return null; } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); transaction = signTransaction(ecKey, transaction); + System.out.println( + "txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + byte[] contractAddress = generateContractAddress(transaction, owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult();*/ - return false; + if (response.getResult() == false) { + return null; + } else { + // logger.info("brodacast succesfully"); + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } + } - /** - * constructor. - */ - - public static String updateSettingDelayGetTxid(byte[] contractAddress, - long consumeUserResourcePercent, long delaySeconds, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - - UpdateSettingContract updateSettingContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateSetting(updateSettingContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } + /** constructor. */ + public static SmartContract.ABI jsonStr2Abi(String jsonStr) { + if (jsonStr == null) { + return null; + } + + JsonParser jsonParser = new JsonParser(); + JsonElement jsonElementRoot = jsonParser.parse(jsonStr); + JsonArray jsonRoot = jsonElementRoot.getAsJsonArray(); + SmartContract.ABI.Builder abiBuilder = SmartContract.ABI.newBuilder(); + for (int index = 0; index < jsonRoot.size(); index++) { + JsonElement abiItem = jsonRoot.get(index); + boolean anonymous = + abiItem.getAsJsonObject().get("anonymous") != null + && abiItem.getAsJsonObject().get("anonymous").getAsBoolean(); + final boolean constant = + abiItem.getAsJsonObject().get("constant") != null + && abiItem.getAsJsonObject().get("constant").getAsBoolean(); + final String name = + abiItem.getAsJsonObject().get("name") != null + ? abiItem.getAsJsonObject().get("name").getAsString() + : null; + JsonArray inputs = + abiItem.getAsJsonObject().get("inputs") != null + ? abiItem.getAsJsonObject().get("inputs").getAsJsonArray() + : null; + final JsonArray outputs = + abiItem.getAsJsonObject().get("outputs") != null + ? abiItem.getAsJsonObject().get("outputs").getAsJsonArray() + : null; + String type = + abiItem.getAsJsonObject().get("type") != null + ? abiItem.getAsJsonObject().get("type").getAsString() + : null; + final boolean payable = + abiItem.getAsJsonObject().get("payable") != null + && abiItem.getAsJsonObject().get("payable").getAsBoolean(); + final String stateMutability = + abiItem.getAsJsonObject().get("stateMutability") != null + ? abiItem.getAsJsonObject().get("stateMutability").getAsString() + : null; + if (type == null) { + logger.error("No type!"); return null; - } - - /** - * constructor. - */ - public static String updateEnergyLimitDelayGetTxid(byte[] contractAddress, long originEnergyLimit, - long delaySeconds, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateEnergyLimitContract.Builder builder = UpdateEnergyLimitContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setOriginEnergyLimit(originEnergyLimit); - - UpdateEnergyLimitContract updateEnergyLimitContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateEnergyLimit(updateEnergyLimitContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - //transactionExtention = TransactionUtils.setDelaySecondsToExtension( - // transactionExtention, delaySeconds); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); + } + if (!type.equalsIgnoreCase("fallback") && null == inputs) { + logger.error("No inputs!"); + return null; + } + + SmartContract.ABI.Entry.Builder entryBuilder = SmartContract.ABI.Entry.newBuilder(); + entryBuilder.setAnonymous(anonymous); + entryBuilder.setConstant(constant); + if (name != null) { + entryBuilder.setName(name); + } + + /* { inputs : optional } since fallback function not requires inputs*/ + if (inputs != null) { + for (int j = 0; j < inputs.size(); j++) { + JsonElement inputItem = inputs.get(j); + if (inputItem.getAsJsonObject().get("name") == null + || inputItem.getAsJsonObject().get("type") == null) { + logger.error("Input argument invalid due to no name or no type!"); return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); + } + String inputName = inputItem.getAsJsonObject().get("name").getAsString(); + String inputType = inputItem.getAsJsonObject().get("type").getAsString(); + ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param.newBuilder(); + JsonElement indexed = inputItem.getAsJsonObject().get("indexed"); + + paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); + paramBuilder.setName(inputName); + paramBuilder.setType(inputType); + entryBuilder.addInputs(paramBuilder.build()); + } + } + + /* { outputs : optional } */ + if (outputs != null) { + for (int k = 0; k < outputs.size(); k++) { + JsonElement outputItem = outputs.get(k); + if (outputItem.getAsJsonObject().get("name") == null + || outputItem.getAsJsonObject().get("type") == null) { + logger.error("Output argument invalid due to no name or no type!"); return null; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - - - /** - * 61 constructor. - */ - - public static Optional getTransactionInfoById(String txId, - WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - TransactionInfo transactionInfo; - transactionInfo = blockingStubFull.getTransactionInfoById(request); - return Optional.ofNullable(transactionInfo); - } - - /** - * 61 constructor. - */ - public static Optional getTransactionInfoByIdFromSolidity(String txId, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - TransactionInfo transactionInfo; - transactionInfo = blockingStubFull.getTransactionInfoById(request); - return Optional.ofNullable(transactionInfo); - } - - - /** - * constructor. - */ - public static Optional getTransactionInfoByBlockNum(long blockNum, - WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - TransactionInfoList transactionInfoList; - transactionInfoList = blockingStubFull.getTransactionInfoByBlockNum(builder.build()); - return Optional.ofNullable(transactionInfoList); - } - - /** - * constructor. - */ - public static Optional getTransactionInfoByBlockNumFromSolidity( - long blockNum, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - TransactionInfoList transactionInfoList; - transactionInfoList = blockingStubSolidity.getTransactionInfoByBlockNum(builder.build()); - return Optional.ofNullable(transactionInfoList); - } - - /** - * constructor. - */ - public static String triggerContract(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return triggerContract(contractAddress, method, argsStr, isHex, callValue, feeLimit, "0", 0, - ownerAddress, priKey, blockingStubFull); - } - - /** - * constructor. - */ - - public static String triggerContract(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } + } + String outputName = outputItem.getAsJsonObject().get("name").getAsString(); + String outputType = outputItem.getAsJsonObject().get("type").getAsString(); + SmartContract.ABI.Entry.Param.Builder paramBuilder = + SmartContract.ABI.Entry.Param.newBuilder(); + JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); - byte[] owner = ownerAddress; - byte[] input = new byte[0]; - if (!method.equalsIgnoreCase("#")) { - input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); + paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); + paramBuilder.setName(outputName); + paramBuilder.setType(outputType); + entryBuilder.addOutputs(paramBuilder.build()); } + } - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } + entryBuilder.setType(getEntryType(type)); + entryBuilder.setPayable(payable); + if (stateMutability != null) { + entryBuilder.setStateMutability(getStateMutability(stateMutability)); + } - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); + abiBuilder.addEntrys(entryBuilder.build()); + } - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); + return abiBuilder.build(); + } - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); + /** constructor. */ + public static SmartContract.ABI jsonStr2Abi2(String jsonStr) { + if (jsonStr == null) { + return null; + } + + JsonParser jsonParser = new JsonParser(); + JsonElement jsonElementRoot = jsonParser.parse(jsonStr); + JsonArray jsonRoot = jsonElementRoot.getAsJsonArray(); + SmartContract.ABI.Builder abiBuilder = SmartContract.ABI.newBuilder(); + for (int index = 0; index < jsonRoot.size(); index++) { + JsonElement abiItem = jsonRoot.get(index); + boolean anonymous = + abiItem.getAsJsonObject().get("anonymous") != null + && abiItem.getAsJsonObject().get("anonymous").getAsBoolean(); + final boolean constant = + abiItem.getAsJsonObject().get("constant") != null + && abiItem.getAsJsonObject().get("constant").getAsBoolean(); + final String name = + abiItem.getAsJsonObject().get("name") != null + ? abiItem.getAsJsonObject().get("name").getAsString() + : null; + JsonArray inputs = + abiItem.getAsJsonObject().get("inputs") != null + ? abiItem.getAsJsonObject().get("inputs").getAsJsonArray() + : null; + final JsonArray outputs = + abiItem.getAsJsonObject().get("outputs") != null + ? abiItem.getAsJsonObject().get("outputs").getAsJsonArray() + : null; + String type = + abiItem.getAsJsonObject().get("type") != null + ? abiItem.getAsJsonObject().get("type").getAsString() + : null; + final boolean payable = + abiItem.getAsJsonObject().get("payable") != null + && abiItem.getAsJsonObject().get("payable").getAsBoolean(); + final String stateMutability = + abiItem.getAsJsonObject().get("stateMutability") != null + ? abiItem.getAsJsonObject().get("stateMutability").getAsString() + : null; + if (type == null) { + logger.error("No type!"); + return null; + } + if (!type.equalsIgnoreCase("fallback") + && !type.equalsIgnoreCase("receive") + && null == inputs) { + logger.error("No inputs!"); + return null; + } + + SmartContract.ABI.Entry.Builder entryBuilder = SmartContract.ABI.Entry.newBuilder(); + entryBuilder.setAnonymous(anonymous); + entryBuilder.setConstant(constant); + if (name != null) { + entryBuilder.setName(name); + } + + /* { inputs : optional } since fallback function not requires inputs*/ + if (inputs != null) { + for (int j = 0; j < inputs.size(); j++) { + JsonElement inputItem = inputs.get(j); + if (inputItem.getAsJsonObject().get("name") == null + || inputItem.getAsJsonObject().get("type") == null) { + logger.error("Input argument invalid due to no name or no type!"); return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { + } + String inputName = inputItem.getAsJsonObject().get("name").getAsString(); + String inputType = inputItem.getAsJsonObject().get("type").getAsString(); + ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param.newBuilder(); + JsonElement indexed = inputItem.getAsJsonObject().get("indexed"); + + paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); + paramBuilder.setName(inputName); + paramBuilder.setType(inputType); + entryBuilder.addInputs(paramBuilder.build()); + } + } + + /* { outputs : optional } */ + if (outputs != null) { + for (int k = 0; k < outputs.size(); k++) { + JsonElement outputItem = outputs.get(k); + if (outputItem.getAsJsonObject().get("name") == null + || outputItem.getAsJsonObject().get("type") == null) { + logger.error("Output argument invalid due to no name or no type!"); return null; - } else { - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - - /** - * constructor. - */ - public static String triggerContractBoth(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletGrpc.WalletBlockingStub blockingStubFull1) { - return triggerContractBoth(contractAddress, method, argsStr, isHex, callValue, feeLimit, "0", 0, - ownerAddress, priKey, blockingStubFull, blockingStubFull1); - } + } + String outputName = outputItem.getAsJsonObject().get("name").getAsString(); + String outputType = outputItem.getAsJsonObject().get("type").getAsString(); + SmartContract.ABI.Entry.Param.Builder paramBuilder = + SmartContract.ABI.Entry.Param.newBuilder(); + JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); - /** - * constructor. - */ - - public static String triggerContractBoth(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - WalletGrpc.WalletBlockingStub blockingStubFull1) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; + paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); + paramBuilder.setName(outputName); + paramBuilder.setType(outputType); + entryBuilder.addOutputs(paramBuilder.build()); } + } + entryBuilder.setType(getEntryType2(type)); - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } + if (stateMutability != null) { + entryBuilder.setStateMutability(getStateMutability(stateMutability)); + } - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransactionBoth(transaction, blockingStubFull, - blockingStubFull1); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } + abiBuilder.addEntrys(entryBuilder.build()); } + return abiBuilder.build(); + } - /** - * constructor. - */ + /** constructor. */ + public static SmartContract.ABI.Entry.EntryType getEntryType(String type) { + switch (type) { + case "constructor": + return SmartContract.ABI.Entry.EntryType.Constructor; + case "function": + return SmartContract.ABI.Entry.EntryType.Function; + case "event": + return SmartContract.ABI.Entry.EntryType.Event; + case "fallback": + return SmartContract.ABI.Entry.EntryType.Fallback; + case "error": + return SmartContract.ABI.Entry.EntryType.Error; + default: + return SmartContract.ABI.Entry.EntryType.UNRECOGNIZED; + } + } - public static String triggerParamListContract(byte[] contractAddress, String method, - List params, Boolean isHex, long callValue, long feeLimit, String tokenId, - long tokenValue, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** constructor. */ + public static SmartContract.ABI.Entry.EntryType getEntryType2(String type) { + switch (type) { + case "constructor": + return SmartContract.ABI.Entry.EntryType.Constructor; + case "function": + return SmartContract.ABI.Entry.EntryType.Function; + case "event": + return SmartContract.ABI.Entry.EntryType.Event; + case "fallback": + return SmartContract.ABI.Entry.EntryType.Fallback; + case "receive": + return SmartContract.ABI.Entry.EntryType.Receive; + default: + return SmartContract.ABI.Entry.EntryType.UNRECOGNIZED; + } + } - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, params)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } + /** constructor. */ + public static SmartContract.ABI.Entry.StateMutabilityType getStateMutability( + String stateMutability) { + switch (stateMutability) { + case "pure": + return SmartContract.ABI.Entry.StateMutabilityType.Pure; + case "view": + return SmartContract.ABI.Entry.StateMutabilityType.View; + case "nonpayable": + return SmartContract.ABI.Entry.StateMutabilityType.Nonpayable; + case "payable": + return SmartContract.ABI.Entry.StateMutabilityType.Payable; + default: + return SmartContract.ABI.Entry.StateMutabilityType.UNRECOGNIZED; + } + } - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } + /** constructor. */ + public static byte[] generateContractAddress(Transaction trx, byte[] owneraddress) { + // get owner address + // this address should be as same as the onweraddress in trx, DONNOT modify it + byte[] ownerAddress = owneraddress; - } + // get tx hash + byte[] txRawDataHash = + Sha256Hash.of( + CommonParameter.getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()) + .getBytes(); - /** - * constructor. - */ + // combine + byte[] combined = new byte[txRawDataHash.length + ownerAddress.length]; + System.arraycopy(txRawDataHash, 0, combined, 0, txRawDataHash.length); + System.arraycopy(ownerAddress, 0, combined, txRawDataHash.length, ownerAddress.length); - public static Boolean exchangeCreate(byte[] firstTokenId, long firstTokenBalance, - byte[] secondTokenId, long secondTokenBalance, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + return sha3omit12(combined); + } - byte[] owner = ownerAddress; + /** constructor. */ + public static SmartContract getContract( + byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString byteString = ByteString.copyFrom(address); + BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(byteString).build(); + logger.info("contract name is " + blockingStubFull.getContract(bytesMessage).getName()); + logger.info("contract address is " + WalletClient.encode58Check(address)); + return blockingStubFull.getContract(bytesMessage); + } - ExchangeCreateContract.Builder builder = ExchangeCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)) - .setFirstTokenId(ByteString.copyFrom(firstTokenId)).setFirstTokenBalance(firstTokenBalance) - .setSecondTokenId(ByteString.copyFrom(secondTokenId)) - .setSecondTokenBalance(secondTokenBalance); - ExchangeCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeCreate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + /** constructor. */ + public static SmartContractDataWrapper getContractInfo( + byte[] address, WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString byteString = ByteString.copyFrom(address); + BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(byteString).build(); + logger.info( + "contract name is " + + blockingStubFull.getContractInfo(bytesMessage).getSmartContract().getName()); + logger.info("contract address is " + WalletClient.encode58Check(address)); + return blockingStubFull.getContractInfo(bytesMessage); + } - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + private static byte[] replaceLibraryAddress(String code, String libraryAddressPair) { - return response.getResult(); + String[] libraryAddressList = libraryAddressPair.split("[,]"); + + for (int i = 0; i < libraryAddressList.length; i++) { + String cur = libraryAddressList[i]; + + int lastPosition = cur.lastIndexOf(":"); + if (-1 == lastPosition) { + throw new RuntimeException("libraryAddress delimit by ':'"); + } + String libraryName = cur.substring(0, lastPosition); + String addr = cur.substring(lastPosition + 1); + String libraryAddressHex = + ByteArray.toHexString(Commons.decodeFromBase58Check(addr)).substring(2); + + String repeated = new String(new char[40 - libraryName.length() - 2]).replace("\0", "_"); + String beReplaced = "__" + libraryName + repeated; + Matcher m = Pattern.compile(beReplaced).matcher(code); + code = m.replaceAll(libraryAddressHex); } - /** - * constructor. - */ + return Hex.decode(code); + } - public static Boolean injectExchange(long exchangeId, byte[] tokenId, long quant, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + private static byte[] replaceLibraryAddress_1(String code, byte[] libraryAddress) { - byte[] owner = ownerAddress; + String libraryAddressHex = ByteArray.toHexString(libraryAddress).substring(2); - ExchangeInjectContract.Builder builder = ExchangeInjectContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); - ExchangeInjectContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeInject(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + Matcher m = Pattern.compile("__.*__").matcher(code); + code = m.replaceAll(libraryAddressHex); + return Hex.decode(code); + } + + private static byte[] replaceLibraryAddresscompilerVersion( + String code, String libraryAddressPair, String compilerVersion) { + + String[] libraryAddressList = libraryAddressPair.split("[,]"); + + for (int i = 0; i < libraryAddressList.length; i++) { + String cur = libraryAddressList[i]; + + int lastPosition = cur.lastIndexOf(":"); + if (-1 == lastPosition) { + throw new RuntimeException("libraryAddress delimit by ':'"); + } + String libraryName = cur.substring(0, lastPosition); + String addr = cur.substring(lastPosition + 1); + String libraryAddressHex; + libraryAddressHex = + (new String(Hex.encode(Commons.decodeFromBase58Check(addr)), StandardCharsets.US_ASCII)) + .substring(2); + + String beReplaced; + if (compilerVersion == null) { + // old version + String repeated = new String(new char[40 - libraryName.length() - 2]).replace("\0", "_"); + beReplaced = "__" + libraryName + repeated; + } else if (compilerVersion.equalsIgnoreCase("v5")) { + // 0.5.4 version + String libraryNameKeccak256 = + ByteArray.toHexString(sha3(ByteArray.fromString(libraryName))).substring(0, 34); + beReplaced = "__\\$" + libraryNameKeccak256 + "\\$__"; + } else { + throw new RuntimeException("unknown compiler version."); + } + + Matcher m = Pattern.compile(beReplaced).matcher(code); + code = m.replaceAll(libraryAddressHex); + } + + return Hex.decode(code); + } - return response.getResult(); + /** constructor. */ + public static boolean updateSetting( + byte[] contractAddress, + long consumeUserResourcePercent, + String priKey, + byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + + UpdateSettingContract updateSettingContract = builder.build(); + TransactionExtention transactionExtention = + blockingStubFull.updateSetting(updateSettingContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return false; + } + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - public static Optional getExchangeList( - WalletGrpc.WalletBlockingStub blockingStubFull) { - ExchangeList exchangeList = blockingStubFull.listExchanges(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(exchangeList); + /** constructor. */ + public static boolean updateSettingDelay( + byte[] contractAddress, + long consumeUserResourcePercent, + long delaySeconds, + String priKey, + byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + + UpdateSettingContract updateSettingContract = builder.build(); + TransactionExtention transactionExtention = + blockingStubFull.updateSetting(updateSettingContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return false; + } + /* transactionExtention = TransactionUtils.setDelaySecondsToExtension( + transactionExtention, delaySeconds); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult();*/ + return false; + } - /** - * constructor. - */ + /** constructor. */ + public static String updateSettingDelayGetTxid( + byte[] contractAddress, + long consumeUserResourcePercent, + long delaySeconds, + String priKey, + byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + + UpdateSettingContract updateSettingContract = builder.build(); + TransactionExtention transactionExtention = + blockingStubFull.updateSetting(updateSettingContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return null; + } + return null; + } - public static Optional getExchangeList( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - ExchangeList exchangeList = blockingStubSolidity - .listExchanges(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(exchangeList); + /** constructor. */ + public static String updateEnergyLimitDelayGetTxid( + byte[] contractAddress, + long originEnergyLimit, + long delaySeconds, + String priKey, + byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + UpdateEnergyLimitContract.Builder builder = UpdateEnergyLimitContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setOriginEnergyLimit(originEnergyLimit); + + UpdateEnergyLimitContract updateEnergyLimitContract = builder.build(); + TransactionExtention transactionExtention = + blockingStubFull.updateEnergyLimit(updateEnergyLimitContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return null; + } + // transactionExtention = TransactionUtils.setDelaySecondsToExtension( + // transactionExtention, delaySeconds); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } + /** 61 constructor. */ + public static Optional getTransactionInfoById( + String txId, WalletGrpc.WalletBlockingStub blockingStubFull) { + ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); + BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); + TransactionInfo transactionInfo; + transactionInfo = blockingStubFull.getTransactionInfoById(request); + return Optional.ofNullable(transactionInfo); + } - /** - * constructor. - */ + /** 61 constructor. */ + public static Optional getTransactionInfoByIdFromSolidity( + String txId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); + BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); + TransactionInfo transactionInfo; + transactionInfo = blockingStubFull.getTransactionInfoById(request); + return Optional.ofNullable(transactionInfo); + } - public static Optional getExchange(String id, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - BytesMessage request = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))).build(); - Exchange exchange = blockingStubSolidity.getExchangeById(request); - return Optional.ofNullable(exchange); - } + /** constructor. */ + public static Optional getTransactionInfoByBlockNum( + long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { + NumberMessage.Builder builder = NumberMessage.newBuilder(); + builder.setNum(blockNum); + TransactionInfoList transactionInfoList; + transactionInfoList = blockingStubFull.getTransactionInfoByBlockNum(builder.build()); + return Optional.ofNullable(transactionInfoList); + } - /** - * constructor. - */ + /** constructor. */ + public static Optional getTransactionInfoByBlockNumFromSolidity( + long blockNum, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + NumberMessage.Builder builder = NumberMessage.newBuilder(); + builder.setNum(blockNum); + TransactionInfoList transactionInfoList; + transactionInfoList = blockingStubSolidity.getTransactionInfoByBlockNum(builder.build()); + return Optional.ofNullable(transactionInfoList); + } - public static Optional getExchange(String id, - WalletGrpc.WalletBlockingStub blockingStubFull) { - BytesMessage request = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))).build(); - Exchange exchange = blockingStubFull.getExchangeById(request); - return Optional.ofNullable(exchange); - } + /** constructor. */ + public static String triggerContract( + byte[] contractAddress, + String method, + String argsStr, + Boolean isHex, + long callValue, + long feeLimit, + byte[] ownerAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + return triggerContract( + contractAddress, + method, + argsStr, + isHex, + callValue, + feeLimit, + "0", + 0, + ownerAddress, + priKey, + blockingStubFull); + } - /** - * constructor. - */ + /** constructor. */ + public static String triggerContract( + byte[] contractAddress, + String method, + String argsStr, + Boolean isHex, + long callValue, + long feeLimit, + String tokenId, + long tokenValue, + byte[] ownerAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + if (argsStr.equalsIgnoreCase("#")) { + logger.info("argsstr is #"); + argsStr = ""; + } - public static boolean exchangeWithdraw(long exchangeId, byte[] tokenId, long quant, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - - ExchangeWithdrawContract.Builder builder = ExchangeWithdrawContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); - ExchangeWithdrawContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeWithdraw(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + byte[] owner = ownerAddress; + byte[] input = new byte[0]; + if (!method.equalsIgnoreCase("#")) { + input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); + } - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); + + TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create call trx failed!"); + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction.getRetCount() != 0 + && transactionExtention.getConstantResult(0) != null + && transactionExtention.getResult() != null) { + byte[] result = transactionExtention.getConstantResult(0).toByteArray(); + System.out.println("message:" + transaction.getRet(0).getRet()); + System.out.println( + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + System.out.println("Result:" + Hex.toHexString(result)); + return null; + } + + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + + transactionExtention = texBuilder.build(); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println( + "trigger txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); } + } - /** - * constructor. - */ + /** constructor. */ + public static String triggerContractBoth( + byte[] contractAddress, + String method, + String argsStr, + Boolean isHex, + long callValue, + long feeLimit, + byte[] ownerAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull, + WalletGrpc.WalletBlockingStub blockingStubFull1) { + return triggerContractBoth( + contractAddress, + method, + argsStr, + isHex, + callValue, + feeLimit, + "0", + 0, + ownerAddress, + priKey, + blockingStubFull, + blockingStubFull1); + } - public static boolean exchangeTransaction(long exchangeId, byte[] tokenId, long quant, - long expected, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - - ExchangeTransactionContract.Builder builder = ExchangeTransactionContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant).setExpected(expected); - ExchangeTransactionContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeTransaction(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + /** constructor. */ + public static String triggerContractBoth( + byte[] contractAddress, + String method, + String argsStr, + Boolean isHex, + long callValue, + long feeLimit, + String tokenId, + long tokenValue, + byte[] ownerAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull, + WalletGrpc.WalletBlockingStub blockingStubFull1) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + if (argsStr.equalsIgnoreCase("#")) { + logger.info("argsstr is #"); + argsStr = ""; + } + + byte[] owner = ownerAddress; + byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); + + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); + + TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create call trx failed!"); + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction.getRetCount() != 0 + && transactionExtention.getConstantResult(0) != null + && transactionExtention.getResult() != null) { + byte[] result = transactionExtention.getConstantResult(0).toByteArray(); + System.out.println("message:" + transaction.getRet(0).getRet()); + System.out.println( + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + System.out.println("Result:" + Hex.toHexString(result)); + return null; + } + + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println( + "trigger txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = + broadcastTransactionBoth(transaction, blockingStubFull, blockingStubFull1); + if (response.getResult() == false) { + return null; + } else { + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } + } + + /** constructor. */ + public static String triggerParamListContract( + byte[] contractAddress, + String method, + List params, + Boolean isHex, + long callValue, + long feeLimit, + String tokenId, + long tokenValue, + byte[] ownerAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + byte[] input = Hex.decode(AbiUtil.parseMethod(method, params)); - /** - * constructor. - */ + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); + + TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create call trx failed!"); + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction.getRetCount() != 0 + && transactionExtention.getConstantResult(0) != null + && transactionExtention.getResult() != null) { + byte[] result = transactionExtention.getConstantResult(0).toByteArray(); + System.out.println("message:" + transaction.getRet(0).getRet()); + System.out.println( + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + System.out.println("Result:" + Hex.toHexString(result)); + return null; + } + + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println( + "trigger txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } + } - public static String deployContractWithConstantParame(String contractName, String abiString, - String code, String constructorStr, String argsStr, String data, Long feeLimit, long value, - long consumeUserResourcePercent, String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContractWithConstantParame(contractName, abiString, code, constructorStr, argsStr, - data, feeLimit, value, consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, - ownerAddress, blockingStubFull); + /** constructor. */ + public static Boolean exchangeCreate( + byte[] firstTokenId, + long firstTokenBalance, + byte[] secondTokenId, + long secondTokenBalance, + byte[] ownerAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + + ExchangeCreateContract.Builder builder = ExchangeCreateContract.newBuilder(); + builder + .setOwnerAddress(ByteString.copyFrom(owner)) + .setFirstTokenId(ByteString.copyFrom(firstTokenId)) + .setFirstTokenBalance(firstTokenBalance) + .setSecondTokenId(ByteString.copyFrom(secondTokenId)) + .setSecondTokenBalance(secondTokenBalance); + ExchangeCreateContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.exchangeCreate(contract); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + System.out.println( + "txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); - /** - * constructor. - */ + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - public static String deployContractWithConstantParame(String contractName, String abiString, - String code, String constructorStr, String argsStr, String data, Long feeLimit, long value, - long consumeUserResourcePercent, long originEnergyLimit, String tokenId, long tokenValue, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + return response.getResult(); + } - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } + /** constructor. */ + public static Boolean injectExchange( + long exchangeId, + byte[] tokenId, + long quant, + byte[] ownerAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + + ExchangeInjectContract.Builder builder = ExchangeInjectContract.newBuilder(); + builder + .setOwnerAddress(ByteString.copyFrom(owner)) + .setExchangeId(exchangeId) + .setTokenId(ByteString.copyFrom(tokenId)) + .setQuant(quant); + ExchangeInjectContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.exchangeInject(contract); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + System.out.println( + "txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - code += Hex.toHexString(AbiUtil.encodeInput(constructorStr, argsStr)); - byte[] owner = ownerAddress; - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); + return response.getResult(); + } - if (value != 0) { + public static Optional getExchangeList( + WalletGrpc.WalletBlockingStub blockingStubFull) { + ExchangeList exchangeList = blockingStubFull.listExchanges(EmptyMessage.newBuilder().build()); + return Optional.ofNullable(exchangeList); + } - builder.setCallValue(value); - } + /** constructor. */ + public static Optional getExchangeList( + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + ExchangeList exchangeList = + blockingStubSolidity.listExchanges(EmptyMessage.newBuilder().build()); + return Optional.ofNullable(exchangeList); + } - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); - - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } + /** constructor. */ + public static Optional getExchange( + String id, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + BytesMessage request = + BytesMessage.newBuilder() + .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))) + .build(); + Exchange exchange = blockingStubSolidity.getExchangeById(request); + return Optional.ofNullable(exchange); + } - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); + /** constructor. */ + public static Optional getExchange( + String id, WalletGrpc.WalletBlockingStub blockingStubFull) { + BytesMessage request = + BytesMessage.newBuilder() + .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))) + .build(); + Exchange exchange = blockingStubFull.getExchangeById(request); + return Optional.ofNullable(exchange); + } - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - byte[] contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - //logger.info("brodacast succesfully"); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } + /** constructor. */ + public static boolean exchangeWithdraw( + long exchangeId, + byte[] tokenId, + long quant, + byte[] ownerAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + byte[] owner = ownerAddress; + + ExchangeWithdrawContract.Builder builder = ExchangeWithdrawContract.newBuilder(); + builder + .setOwnerAddress(ByteString.copyFrom(owner)) + .setExchangeId(exchangeId) + .setTokenId(ByteString.copyFrom(tokenId)) + .setQuant(quant); + ExchangeWithdrawContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.exchangeWithdraw(contract); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + System.out.println( + "txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); - /** - * constructor. - */ - - public static Boolean freezeBalanceForReceiver(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, ByteString receiverAddressBytes, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); - if (receiverAddressBytes != null) { - builder.setReceiverAddress(receiverAddressBytes); - } - FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); + /** constructor. */ + public static boolean exchangeTransaction( + long exchangeId, + byte[] tokenId, + long quant, + long expected, + byte[] ownerAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + byte[] owner = ownerAddress; + + ExchangeTransactionContract.Builder builder = ExchangeTransactionContract.newBuilder(); + builder + .setOwnerAddress(ByteString.copyFrom(owner)) + .setExchangeId(exchangeId) + .setTokenId(ByteString.copyFrom(tokenId)) + .setQuant(quant) + .setExpected(expected); + ExchangeTransactionContract contract = builder.build(); + TransactionExtention transactionExtention = blockingStubFull.exchangeTransaction(contract); + if (transactionExtention == null) { + return false; } - - - /** - * constructor. - */ - - public static Optional getDelegatedResource(byte[] fromAddress, - byte[] toAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString fromAddressBs = ByteString.copyFrom(fromAddress); - ByteString toAddressBs = ByteString.copyFrom(toAddress); - - DelegatedResourceMessage request = DelegatedResourceMessage.newBuilder() - .setFromAddress(fromAddressBs).setToAddress(toAddressBs).build(); - DelegatedResourceList delegatedResource = blockingStubFull.getDelegatedResource(request); - return Optional.ofNullable(delegatedResource); + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; } - - /** - * constructor. - */ - public static Optional getDelegatedResourceFromSolidity(byte[] fromAddress, - byte[] toAddress, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString fromAddressBs = ByteString.copyFrom(fromAddress); - ByteString toAddressBs = ByteString.copyFrom(toAddress); - - DelegatedResourceMessage request = DelegatedResourceMessage.newBuilder() - .setFromAddress(fromAddressBs).setToAddress(toAddressBs).build(); - DelegatedResourceList delegatedResource = blockingStubFull.getDelegatedResource(request); - return Optional.ofNullable(delegatedResource); + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + System.out.println( + "txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - /** - * constructor. - */ + /** constructor. */ + public static String deployContractWithConstantParame( + String contractName, + String abiString, + String code, + String constructorStr, + String argsStr, + String data, + Long feeLimit, + long value, + long consumeUserResourcePercent, + String libraryAddress, + String priKey, + byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + return deployContractWithConstantParame( + contractName, + abiString, + code, + constructorStr, + argsStr, + data, + feeLimit, + value, + consumeUserResourcePercent, + 1000L, + "0", + 0L, + libraryAddress, + priKey, + ownerAddress, + blockingStubFull); + } - public static Optional getDelegatedResourceAccountIndex( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + /** constructor. */ + public static String deployContractWithConstantParame( + String contractName, + String abiString, + String code, + String constructorStr, + String argsStr, + String data, + Long feeLimit, + long value, + long consumeUserResourcePercent, + long originEnergyLimit, + String tokenId, + long tokenValue, + String libraryAddress, + String priKey, + byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + SmartContract.ABI abi = jsonStr2Abi(abiString); + if (abi == null) { + logger.error("abi is null"); + return null; + } + + code += Hex.toHexString(AbiUtil.encodeInput(constructorStr, argsStr)); + byte[] owner = ownerAddress; + SmartContract.Builder builder = SmartContract.newBuilder(); + builder.setName(contractName); + builder.setOriginAddress(ByteString.copyFrom(owner)); + builder.setAbi(abi); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + builder.setOriginEnergyLimit(originEnergyLimit); + + if (value != 0) { + + builder.setCallValue(value); + } + + byte[] byteCode; + if (null != libraryAddress) { + byteCode = replaceLibraryAddress(code, libraryAddress); + } else { + byteCode = Hex.decode(code); + } + builder.setBytecode(ByteString.copyFrom(byteCode)); + + Builder contractBuilder = CreateSmartContract.newBuilder(); + contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); + contractBuilder.setCallTokenValue(tokenValue); + contractBuilder.setTokenId(Long.parseLong(tokenId)); + CreateSmartContract contractDeployContract = + contractBuilder.setNewContract(builder.build()).build(); + + TransactionExtention transactionExtention = + blockingStubFull.deployContract(contractDeployContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return null; + } + + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); - ByteString addressBs = ByteString.copyFrom(address); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println( + "txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + byte[] contractAddress = generateContractAddress(transaction, owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + // logger.info("brodacast succesfully"); + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } + } - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(addressBs).build(); + /** constructor. */ + public static Boolean freezeBalanceForReceiver( + byte[] addRess, + long freezeBalance, + long freezeDuration, + int resourceCode, + ByteString receiverAddressBytes, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + byte[] address = addRess; + long frozenBalance = freezeBalance; + long frozenDuration = freezeDuration; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); + ByteString byteAddreess = ByteString.copyFrom(address); + + builder + .setOwnerAddress(byteAddreess) + .setFrozenBalance(frozenBalance) + .setFrozenDuration(frozenDuration) + .setResourceValue(resourceCode); + if (receiverAddressBytes != null) { + builder.setReceiverAddress(receiverAddressBytes); + } + FreezeBalanceContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - DelegatedResourceAccountIndex accountIndex = blockingStubFull - .getDelegatedResourceAccountIndex(bytesMessage); - return Optional.ofNullable(accountIndex); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + logger.info("transaction = null"); + return false; } + transaction = TransactionUtils.setTimestamp(transaction); + transaction = TransactionUtils.sign(transaction, ecKey); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } + /** constructor. */ + public static Optional getDelegatedResource( + byte[] fromAddress, byte[] toAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString fromAddressBs = ByteString.copyFrom(fromAddress); + ByteString toAddressBs = ByteString.copyFrom(toAddress); + + DelegatedResourceMessage request = + DelegatedResourceMessage.newBuilder() + .setFromAddress(fromAddressBs) + .setToAddress(toAddressBs) + .build(); + DelegatedResourceList delegatedResource = blockingStubFull.getDelegatedResource(request); + return Optional.ofNullable(delegatedResource); + } - /** - * constructor. - */ - public static Optional - getDelegatedResourceAccountIndexFromSolidity(byte[] address, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + /** constructor. */ + public static Optional getDelegatedResourceFromSolidity( + byte[] fromAddress, + byte[] toAddress, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString fromAddressBs = ByteString.copyFrom(fromAddress); + ByteString toAddressBs = ByteString.copyFrom(toAddress); + + DelegatedResourceMessage request = + DelegatedResourceMessage.newBuilder() + .setFromAddress(fromAddressBs) + .setToAddress(toAddressBs) + .build(); + DelegatedResourceList delegatedResource = blockingStubFull.getDelegatedResource(request); + return Optional.ofNullable(delegatedResource); + } - ByteString addressBs = ByteString.copyFrom(address); + /** constructor. */ + public static Optional getDelegatedResourceAccountIndex( + byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(addressBs).build(); + ByteString addressBs = ByteString.copyFrom(address); - DelegatedResourceAccountIndex accountIndex = blockingStubFull - .getDelegatedResourceAccountIndex(bytesMessage); - return Optional.ofNullable(accountIndex); - } + BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(addressBs).build(); + DelegatedResourceAccountIndex accountIndex = + blockingStubFull.getDelegatedResourceAccountIndex(bytesMessage); + return Optional.ofNullable(accountIndex); + } - /** - * constructor. - */ + /** constructor. */ + public static Optional + getDelegatedResourceAccountIndexFromSolidity( + byte[] address, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - public static AssetIssueContract getAssetIssueByName(String assetName, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - return blockingStubFull.getAssetIssueByName(request); - } + ByteString addressBs = ByteString.copyFrom(address); - /** - * constructor. - */ - public static AssetIssueContract getAssetIssueByNameFromSolidity(String assetName, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - return blockingStubFull.getAssetIssueByName(request); - } + BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(addressBs).build(); + DelegatedResourceAccountIndex accountIndex = + blockingStubFull.getDelegatedResourceAccountIndex(bytesMessage); + return Optional.ofNullable(accountIndex); + } - /** - * constructor. - */ + /** constructor. */ + public static AssetIssueContract getAssetIssueByName( + String assetName, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); + BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); + return blockingStubFull.getAssetIssueByName(request); + } - public static Optional getAssetIssueListByName(String assetName, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - AssetIssueList assetIssueList = blockingStubFull.getAssetIssueListByName(request); - return Optional.ofNullable(assetIssueList); - } - - /** - * constructor. - */ - public static Optional getAssetIssueListByNameFromSolidity(String assetName, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - AssetIssueList assetIssueList = blockingStubFull.getAssetIssueListByName(request); - return Optional.ofNullable(assetIssueList); - } - - /** - * constructor. - */ - public static Optional listAssetIssueFromSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - GrpcAPI.AssetIssueList assetIssueList = blockingStubFull - .getAssetIssueList(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(assetIssueList); - } + /** constructor. */ + public static AssetIssueContract getAssetIssueByNameFromSolidity( + String assetName, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); + BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); + return blockingStubFull.getAssetIssueByName(request); + } - /** - * constructor. - */ - public static Optional listAssetIssuepaginatedFromSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull, Long offset, Long limit) { - GrpcAPI.PaginatedMessage.Builder pageMessageBuilder = GrpcAPI.PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - AssetIssueList assetIssueList = blockingStubFull - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - return Optional.ofNullable(assetIssueList); - } + /** constructor. */ + public static Optional getAssetIssueListByName( + String assetName, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); + BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); + AssetIssueList assetIssueList = blockingStubFull.getAssetIssueListByName(request); + return Optional.ofNullable(assetIssueList); + } + /** constructor. */ + public static Optional getAssetIssueListByNameFromSolidity( + String assetName, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); + BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); + AssetIssueList assetIssueList = blockingStubFull.getAssetIssueListByName(request); + return Optional.ofNullable(assetIssueList); + } - /** - * constructor. - */ - public static Optional listWitnesses( - WalletGrpc.WalletBlockingStub blockingStubFull) { - GrpcAPI.WitnessList witnessList = blockingStubFull - .listWitnesses(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(witnessList); - } - - /** - * constructor. - */ - public static Optional listWitnessesFromSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - GrpcAPI.WitnessList witnessList = blockingStubFull - .listWitnesses(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(witnessList); - } - - - /** - * constructor. - */ - - public static AssetIssueContract getAssetIssueById(String assetId, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetIdBs = ByteString.copyFrom(assetId.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetIdBs).build(); - return blockingStubFull.getAssetIssueById(request); - } - - /** - * constructor. - */ - public static AssetIssueContract getAssetIssueByIdFromSolidity(String assetId, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetIdBs = ByteString.copyFrom(assetId.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetIdBs).build(); - return blockingStubFull.getAssetIssueById(request); - } - - /** - * constructor. - */ - public static Optional getAssetIssueByAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - AssetIssueList assetIssueList = blockingStubFull.getAssetIssueByAccount(request); - return Optional.ofNullable(assetIssueList); - } - - private static Permission json2Permission(JSONObject json) { - Permission.Builder permissionBuilder = Permission.newBuilder(); - if (json.containsKey("type")) { - int type = json.getInteger("type"); - permissionBuilder.setTypeValue(type); - } - if (json.containsKey("permission_name")) { - String permissionName = json.getString("permission_name"); - permissionBuilder.setPermissionName(permissionName); - } - if (json.containsKey("threshold")) { - //long threshold = json.getLong("threshold"); - long threshold = Long.parseLong(json.getString("threshold")); - permissionBuilder.setThreshold(threshold); - } - if (json.containsKey("parent_id")) { - int parentId = json.getInteger("parent_id"); - permissionBuilder.setParentId(parentId); - } - if (json.containsKey("operations")) { - byte[] operations = ByteArray.fromHexString(json.getString("operations")); - permissionBuilder.setOperations(ByteString.copyFrom(operations)); - } - if (json.containsKey("keys")) { - JSONArray keys = json.getJSONArray("keys"); - List keyList = new ArrayList<>(); - for (int i = 0; i < keys.size(); i++) { - Key.Builder keyBuilder = Key.newBuilder(); - JSONObject key = keys.getJSONObject(i); - String address = key.getString("address"); - long weight = Long.parseLong(key.getString("weight")); - //long weight = key.getLong("weight"); - //keyBuilder.setAddress(ByteString.copyFrom(address.getBytes())); - keyBuilder.setAddress(ByteString.copyFrom(WalletClient.decodeFromBase58Check(address))); - keyBuilder.setWeight(weight); - keyList.add(keyBuilder.build()); - } - permissionBuilder.addAllKeys(keyList); - } - return permissionBuilder.build(); - } - - /** - * constructor. - */ - public static boolean accountPermissionUpdate(String permissionJson, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] priKeys) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + /** constructor. */ + public static Optional listAssetIssueFromSolidity( + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + GrpcAPI.AssetIssueList assetIssueList = + blockingStubFull.getAssetIssueList(EmptyMessage.newBuilder().build()); + return Optional.ofNullable(assetIssueList); + } - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); + /** constructor. */ + public static Optional listAssetIssuepaginatedFromSolidity( + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull, Long offset, Long limit) { + GrpcAPI.PaginatedMessage.Builder pageMessageBuilder = GrpcAPI.PaginatedMessage.newBuilder(); + pageMessageBuilder.setOffset(offset); + pageMessageBuilder.setLimit(limit); + AssetIssueList assetIssueList = + blockingStubFull.getPaginatedAssetIssueList(pageMessageBuilder.build()); + return Optional.ofNullable(assetIssueList); + } - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownerpermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesspermission = permissions.getJSONObject("witness_permission"); - JSONArray activepermissions = permissions.getJSONArray("active_permissions"); + /** constructor. */ + public static Optional listWitnesses( + WalletGrpc.WalletBlockingStub blockingStubFull) { + GrpcAPI.WitnessList witnessList = + blockingStubFull.listWitnesses(EmptyMessage.newBuilder().build()); + return Optional.ofNullable(witnessList); + } - if (ownerpermission != null) { - Permission ownerPermission = json2Permission(ownerpermission); - builder.setOwner(ownerPermission); - } - if (witnesspermission != null) { - Permission witnessPermission = json2Permission(witnesspermission); - builder.setWitness(witnessPermission); - } - if (activepermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activepermissions.size(); j++) { - JSONObject permission = activepermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); + /** constructor. */ + public static Optional listWitnessesFromSolidity( + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + GrpcAPI.WitnessList witnessList = + blockingStubFull.listWitnesses(EmptyMessage.newBuilder().build()); + return Optional.ofNullable(witnessList); + } - AccountPermissionUpdateContract contract = builder.build(); + /** constructor. */ + public static AssetIssueContract getAssetIssueById( + String assetId, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString assetIdBs = ByteString.copyFrom(assetId.getBytes()); + BytesMessage request = BytesMessage.newBuilder().setValue(assetIdBs).build(); + return blockingStubFull.getAssetIssueById(request); + } - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } + /** constructor. */ + public static AssetIssueContract getAssetIssueByIdFromSolidity( + String assetId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString assetIdBs = ByteString.copyFrom(assetId.getBytes()); + BytesMessage request = BytesMessage.newBuilder().setValue(assetIdBs).build(); + return blockingStubFull.getAssetIssueById(request); + } + /** constructor. */ + public static Optional getAssetIssueByAccount( + byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ByteString addressBs = ByteString.copyFrom(address); + Account request = Account.newBuilder().setAddress(addressBs).build(); + AssetIssueList assetIssueList = blockingStubFull.getAssetIssueByAccount(request); + return Optional.ofNullable(assetIssueList); + } - /** - * constructor. - */ - public static long getFreezeBalanceCount(byte[] accountAddress, String ecKey, Long targetEnergy, - WalletGrpc.WalletBlockingStub blockingStubFull) { - //Precision change as the entire network freezes - AccountResourceMessage resourceInfo = getAccountResource(accountAddress, blockingStubFull); + private static Permission json2Permission(JSONObject json) { + Permission.Builder permissionBuilder = Permission.newBuilder(); + if (json.containsKey("type")) { + int type = json.getInteger("type"); + permissionBuilder.setTypeValue(type); + } + if (json.containsKey("permission_name")) { + String permissionName = json.getString("permission_name"); + permissionBuilder.setPermissionName(permissionName); + } + if (json.containsKey("threshold")) { + // long threshold = json.getLong("threshold"); + long threshold = Long.parseLong(json.getString("threshold")); + permissionBuilder.setThreshold(threshold); + } + if (json.containsKey("parent_id")) { + int parentId = json.getInteger("parent_id"); + permissionBuilder.setParentId(parentId); + } + if (json.containsKey("operations")) { + byte[] operations = ByteArray.fromHexString(json.getString("operations")); + permissionBuilder.setOperations(ByteString.copyFrom(operations)); + } + if (json.containsKey("keys")) { + JSONArray keys = json.getJSONArray("keys"); + List keyList = new ArrayList<>(); + for (int i = 0; i < keys.size(); i++) { + Key.Builder keyBuilder = Key.newBuilder(); + JSONObject key = keys.getJSONObject(i); + String address = key.getString("address"); + long weight = Long.parseLong(key.getString("weight")); + // long weight = key.getLong("weight"); + // keyBuilder.setAddress(ByteString.copyFrom(address.getBytes())); + keyBuilder.setAddress(ByteString.copyFrom(WalletClient.decodeFromBase58Check(address))); + keyBuilder.setWeight(weight); + keyList.add(keyBuilder.build()); + } + permissionBuilder.addAllKeys(keyList); + } + return permissionBuilder.build(); + } - Account info = queryAccount(accountAddress, blockingStubFull); + /** constructor. */ + public static boolean accountPermissionUpdate( + String permissionJson, + byte[] owner, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull, + String[] priKeys) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); + + JSONObject permissions = JSONObject.parseObject(permissionJson); + JSONObject ownerpermission = permissions.getJSONObject("owner_permission"); + JSONObject witnesspermission = permissions.getJSONObject("witness_permission"); + JSONArray activepermissions = permissions.getJSONArray("active_permissions"); + + if (ownerpermission != null) { + Permission ownerPermission = json2Permission(ownerpermission); + builder.setOwner(ownerPermission); + } + if (witnesspermission != null) { + Permission witnessPermission = json2Permission(witnesspermission); + builder.setWitness(witnessPermission); + } + if (activepermissions != null) { + List activePermissionList = new ArrayList<>(); + for (int j = 0; j < activepermissions.size(); j++) { + JSONObject permission = activepermissions.getJSONObject(j); + activePermissionList.add(json2Permission(permission)); + } + builder.addAllActives(activePermissionList); + } + builder.setOwnerAddress(ByteString.copyFrom(owner)); - Account getAccount = queryAccount(ecKey, blockingStubFull); + AccountPermissionUpdateContract contract = builder.build(); - long balance = info.getBalance(); - long frozenBalance = info.getAccountResource().getFrozenBalanceForEnergy().getFrozenBalance(); - long totalEnergyLimit = resourceInfo.getTotalEnergyLimit(); - long totalEnergyWeight = resourceInfo.getTotalEnergyWeight(); - long energyUsed = resourceInfo.getEnergyUsed(); - long energyLimit = resourceInfo.getEnergyLimit(); + TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - if (energyUsed > energyLimit) { - targetEnergy = energyUsed - energyLimit + targetEnergy; - } + /** constructor. */ + public static long getFreezeBalanceCount( + byte[] accountAddress, + String ecKey, + Long targetEnergy, + WalletGrpc.WalletBlockingStub blockingStubFull) { + // Precision change as the entire network freezes + AccountResourceMessage resourceInfo = getAccountResource(accountAddress, blockingStubFull); - if (totalEnergyWeight == 0) { - return 1000_000L; - } + Account info = queryAccount(accountAddress, blockingStubFull); - // totalEnergyLimit / (totalEnergyWeight + needBalance) = needEnergy / needBalance - final BigInteger totalEnergyWeightBi = BigInteger.valueOf(totalEnergyWeight); - long needBalance = totalEnergyWeightBi.multiply(BigInteger.valueOf(1_000_000)) - .multiply(BigInteger.valueOf(targetEnergy)) - .divide(BigInteger.valueOf(totalEnergyLimit - targetEnergy)).longValue(); + Account getAccount = queryAccount(ecKey, blockingStubFull); - logger.info("getFreezeBalanceCount, needBalance: " + needBalance); + long balance = info.getBalance(); + long frozenBalance = info.getAccountResource().getFrozenBalanceForEnergy().getFrozenBalance(); + long totalEnergyLimit = resourceInfo.getTotalEnergyLimit(); + long totalEnergyWeight = resourceInfo.getTotalEnergyWeight(); + long energyUsed = resourceInfo.getEnergyUsed(); + long energyLimit = resourceInfo.getEnergyLimit(); - if (needBalance < 1000000L) { - needBalance = 1000000L; - logger.info("getFreezeBalanceCount, needBalance less than 1 TRX, modify to: " + needBalance); - } - return needBalance; - } - - /** - * constructor. - */ - public static Long getAssetIssueValue(byte[] accountAddress, ByteString assetIssueId, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Long assetIssueCount = 0L; - Account contractAccount = queryAccount(accountAddress, blockingStubFull); - Map createAssetIssueMap = contractAccount.getAssetV2Map(); - for (Map.Entry entry : createAssetIssueMap.entrySet()) { - if (assetIssueId.toStringUtf8().equals(entry.getKey())) { - assetIssueCount = entry.getValue(); - } - } - return assetIssueCount; - } - - /** - * constructor. - */ - public static List getStrings(byte[] data) { - int index = 0; - List ret = new ArrayList<>(); - while (index < data.length) { - ret.add(byte2HexStr(data, index, 32)); - index += 32; - } - return ret; + if (energyUsed > energyLimit) { + targetEnergy = energyUsed - energyLimit + targetEnergy; } - /** - * constructor. - */ - public static String byte2HexStr(byte[] b, int offset, int length) { - StringBuilder ssBuilder = new StringBuilder(); - for (int n = offset; n < offset + length && n < b.length; n++) { - String stmp = Integer.toHexString(b[n] & 0xFF); - ssBuilder.append((stmp.length() == 1) ? "0" + stmp : stmp); - } - return ssBuilder.toString().toUpperCase().trim(); + if (totalEnergyWeight == 0) { + return 1000_000L; } + // totalEnergyLimit / (totalEnergyWeight + needBalance) = needEnergy / needBalance + final BigInteger totalEnergyWeightBi = BigInteger.valueOf(totalEnergyWeight); + long needBalance = + totalEnergyWeightBi + .multiply(BigInteger.valueOf(1_000_000)) + .multiply(BigInteger.valueOf(targetEnergy)) + .divide(BigInteger.valueOf(totalEnergyLimit - targetEnergy)) + .longValue(); - /** - * constructor. - */ - public static Transaction addTransactionSign(Transaction transaction, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - Transaction.Builder transactionBuilderSigned = transaction.toBuilder(); - byte[] hash = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()); - - ECDSASignature signature = ecKey.sign(hash); - ByteString bsSign = ByteString.copyFrom(signature.toByteArray()); - transactionBuilderSigned.addSignature(bsSign); - transaction = transactionBuilderSigned.build(); - return transaction; - } - - /** - * constructor. - */ - public static GrpcAPI.Return deployContractAndGetResponse(String contractName, String abiString, - String code, String data, Long feeLimit, long value, long consumeUserResourcePercent, - long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, - byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + logger.info("getFreezeBalanceCount, needBalance: " + needBalance); - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); + if (needBalance < 1000000L) { + needBalance = 1000000L; + logger.info("getFreezeBalanceCount, needBalance less than 1 TRX, modify to: " + needBalance); + } + return needBalance; + } - if (value != 0) { + /** constructor. */ + public static Long getAssetIssueValue( + byte[] accountAddress, + ByteString assetIssueId, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Long assetIssueCount = 0L; + Account contractAccount = queryAccount(accountAddress, blockingStubFull); + Map createAssetIssueMap = contractAccount.getAssetV2Map(); + for (Map.Entry entry : createAssetIssueMap.entrySet()) { + if (assetIssueId.toStringUtf8().equals(entry.getKey())) { + assetIssueCount = entry.getValue(); + } + } + return assetIssueCount; + } - builder.setCallValue(value); - } + /** constructor. */ + public static List getStrings(byte[] data) { + int index = 0; + List ret = new ArrayList<>(); + while (index < data.length) { + ret.add(byte2HexStr(data, index, 32)); + index += 32; + } + return ret; + } - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); - - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } + /** constructor. */ + public static String byte2HexStr(byte[] b, int offset, int length) { + StringBuilder ssBuilder = new StringBuilder(); + for (int n = offset; n < offset + length && n < b.length; n++) { + String stmp = Integer.toHexString(b[n] & 0xFF); + ssBuilder.append((stmp.length() == 1) ? "0" + stmp : stmp); + } + return ssBuilder.toString().toUpperCase().trim(); + } - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); + /** constructor. */ + public static Transaction addTransactionSign( + Transaction transaction, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; + + Transaction.Builder transactionBuilderSigned = transaction.toBuilder(); + byte[] hash = + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()); + + ECDSASignature signature = ecKey.sign(hash); + ByteString bsSign = ByteString.copyFrom(signature.toByteArray()); + transactionBuilderSigned.addSignature(bsSign); + transaction = transactionBuilderSigned.build(); + return transaction; + } - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - byte[] contractAddress = generateContractAddress(transaction, owner); + /** constructor. */ + public static GrpcAPI.Return deployContractAndGetResponse( + String contractName, + String abiString, + String code, + String data, + Long feeLimit, + long value, + long consumeUserResourcePercent, + long originEnergyLimit, + String tokenId, + long tokenValue, + String libraryAddress, + String priKey, + byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + SmartContract.ABI abi = jsonStr2Abi(abiString); + if (abi == null) { + logger.error("abi is null"); + return null; + } + // byte[] codeBytes = Hex.decode(code); + SmartContract.Builder builder = SmartContract.newBuilder(); + builder.setName(contractName); + builder.setOriginAddress(ByteString.copyFrom(owner)); + builder.setAbi(abi); + builder.setConsumeUserResourcePercent(consumeUserResourcePercent); + builder.setOriginEnergyLimit(originEnergyLimit); + + if (value != 0) { + + builder.setCallValue(value); + } + + byte[] byteCode; + if (null != libraryAddress) { + byteCode = replaceLibraryAddress(code, libraryAddress); + } else { + byteCode = Hex.decode(code); + } + builder.setBytecode(ByteString.copyFrom(byteCode)); + + Builder contractBuilder = CreateSmartContract.newBuilder(); + contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); + contractBuilder.setCallTokenValue(tokenValue); + contractBuilder.setTokenId(Long.parseLong(tokenId)); + CreateSmartContract contractDeployContract = + contractBuilder.setNewContract(builder.build()).build(); + + TransactionExtention transactionExtention = + blockingStubFull.deployContract(contractDeployContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return null; + } + + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); - return response; + if (transactionExtention == null) { + return null; } - - /** - * constructor. - */ - public static GrpcAPI.Return triggerContractAndGetResponse(byte[] contractAddress, String method, - String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response; + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println( + "txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + byte[] contractAddress = generateContractAddress(transaction, owner); + System.out.println( + "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - /** - * constructor. - */ - public static boolean updateEnergyLimit(byte[] contractAddress, long originEnergyLimit, - String priKey, byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateEnergyLimitContract.Builder builder = UpdateEnergyLimitContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setOriginEnergyLimit(originEnergyLimit); - - UpdateEnergyLimitContract updateEnergyLimitContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateEnergyLimit(updateEnergyLimitContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - public static GrpcAPI.Return accountPermissionUpdateForResponse(String permissionJson, - byte[] owner, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); + return response; + } - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownerpermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesspermission = permissions.getJSONObject("witness_permission"); - JSONArray activepermissions = permissions.getJSONArray("active_permissions"); + /** constructor. */ + public static GrpcAPI.Return triggerContractAndGetResponse( + byte[] contractAddress, + String method, + String argsStr, + Boolean isHex, + long callValue, + long feeLimit, + String tokenId, + long tokenValue, + byte[] ownerAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + if (argsStr.equalsIgnoreCase("#")) { + logger.info("argsstr is #"); + argsStr = ""; + } - if (ownerpermission != null) { - Permission ownerPermission = json2Permission(ownerpermission); - builder.setOwner(ownerPermission); - } - if (witnesspermission != null) { - Permission witnessPermission = json2Permission(witnesspermission); - builder.setWitness(witnessPermission); - } - if (activepermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activepermissions.size(); j++) { - JSONObject permission = activepermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); + byte[] owner = ownerAddress; + byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - AccountPermissionUpdateContract contract = builder.build(); + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); + + TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create call trx failed!"); + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction.getRetCount() != 0 + && transactionExtention.getConstantResult(0) != null + && transactionExtention.getResult() != null) { + byte[] result = transactionExtention.getConstantResult(0).toByteArray(); + System.out.println("message:" + transaction.getRet(0).getRet()); + System.out.println( + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + System.out.println("Result:" + Hex.toHexString(result)); + return null; + } + + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println( + "trigger txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response; + } - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return ret; - } + /** constructor. */ + public static boolean updateEnergyLimit( + byte[] contractAddress, + long originEnergyLimit, + String priKey, + byte[] ownerAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + byte[] owner = ownerAddress; + UpdateEnergyLimitContract.Builder builder = UpdateEnergyLimitContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setOriginEnergyLimit(originEnergyLimit); + + UpdateEnergyLimitContract updateEnergyLimitContract = builder.build(); + TransactionExtention transactionExtention = + blockingStubFull.updateEnergyLimit(updateEnergyLimitContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create trx failed!"); + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response; + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return false; + } + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } - public static TransactionApprovedList getTransactionApprovedList(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return blockingStubFull.getTransactionApprovedList(transaction); + /** constructor. */ + public static GrpcAPI.Return accountPermissionUpdateForResponse( + String permissionJson, + byte[] owner, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); + + JSONObject permissions = JSONObject.parseObject(permissionJson); + JSONObject ownerpermission = permissions.getJSONObject("owner_permission"); + JSONObject witnesspermission = permissions.getJSONObject("witness_permission"); + JSONArray activepermissions = permissions.getJSONArray("active_permissions"); + + if (ownerpermission != null) { + Permission ownerPermission = json2Permission(ownerpermission); + builder.setOwner(ownerPermission); + } + if (witnesspermission != null) { + Permission witnessPermission = json2Permission(witnesspermission); + builder.setWitness(witnessPermission); + } + if (activepermissions != null) { + List activePermissionList = new ArrayList<>(); + for (int j = 0; j < activepermissions.size(); j++) { + JSONObject permission = activepermissions.getJSONObject(j); + activePermissionList.add(json2Permission(permission)); + } + builder.addAllActives(activePermissionList); } + builder.setOwnerAddress(ByteString.copyFrom(owner)); - /** - * constructor. - */ - public static long getFreezeBalanceNetCount(byte[] accountAddress, String ecKey, Long targetNet, - WalletGrpc.WalletBlockingStub blockingStubFull) { - //Precision change as the entire network freezes - AccountResourceMessage resourceInfo = getAccountResource(accountAddress, blockingStubFull); + AccountPermissionUpdateContract contract = builder.build(); - Account info = queryAccount(accountAddress, blockingStubFull); + TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return ret; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return ret; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - Account getAccount = queryAccount(ecKey, blockingStubFull); + return response; + } - long balance = info.getBalance(); - long totalNetLimit = resourceInfo.getTotalNetLimit(); - long totalNetWeight = resourceInfo.getTotalNetWeight(); - long netUsed = resourceInfo.getNetUsed(); - long netLimit = resourceInfo.getNetLimit(); + public static TransactionApprovedList getTransactionApprovedList( + Transaction transaction, WalletGrpc.WalletBlockingStub blockingStubFull) { + return blockingStubFull.getTransactionApprovedList(transaction); + } - if (netUsed > netLimit) { - targetNet = netUsed - netLimit + targetNet; - } + /** constructor. */ + public static long getFreezeBalanceNetCount( + byte[] accountAddress, + String ecKey, + Long targetNet, + WalletGrpc.WalletBlockingStub blockingStubFull) { + // Precision change as the entire network freezes + AccountResourceMessage resourceInfo = getAccountResource(accountAddress, blockingStubFull); - if (totalNetWeight == 0) { - return 1000_000L; - } + Account info = queryAccount(accountAddress, blockingStubFull); - // totalNetLimit / (totalNetWeight + needBalance) = needNet / needBalance - final BigInteger totalNetWeightBi = BigInteger.valueOf(totalNetWeight); - long needBalance = totalNetWeightBi.multiply(BigInteger.valueOf(1_000_000)) - .multiply(BigInteger.valueOf(targetNet)) - .divide(BigInteger.valueOf(totalNetLimit - targetNet)).longValue(); + Account getAccount = queryAccount(ecKey, blockingStubFull); - logger.info("getFreezeBalanceNetCount, needBalance: " + needBalance); + long balance = info.getBalance(); + long totalNetLimit = resourceInfo.getTotalNetLimit(); + long totalNetWeight = resourceInfo.getTotalNetWeight(); + long netUsed = resourceInfo.getNetUsed(); + long netLimit = resourceInfo.getNetLimit(); - if (needBalance < 1000000L) { - needBalance = 1000000L; - logger - .info("getFreezeBalanceNetCount, needBalance less than 1 TRX, modify to: " + needBalance); - } - return needBalance; - } - - /** - * constructor. - */ - public static GrpcAPI.Return broadcastTransaction(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull) { - int i = 10; - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - while (!response.getResult() && response.getCode() == response_code.SERVER_BUSY - && i > 0) { - try { - Thread.sleep(300); - } catch (InterruptedException e) { - e.printStackTrace(); - } - i--; - response = blockingStubFull.broadcastTransaction(transaction); - logger.info("repeate times = " + (10 - i)); - } + if (netUsed > netLimit) { + targetNet = netUsed - netLimit + targetNet; + } - if (response.getResult() == false) { - logger.info("Code = " + response.getCode()); - logger.info("Message = " + response.getMessage().toStringUtf8()); - } - return response; + if (totalNetWeight == 0) { + return 1000_000L; } - /** - * constructor. - */ - public static GrpcAPI.Return broadcastTransactionBoth(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletGrpc.WalletBlockingStub blockingStubFull1) { - int i = 10; - waitProduceNextBlock(blockingStubFull1); - GrpcAPI.Return response = blockingStubFull1.broadcastTransaction(transaction); - GrpcAPI.Return response1 = blockingStubFull.broadcastTransaction(transaction); - while (response.getResult() == false && response.getCode() == response_code.SERVER_BUSY - && i > 0) { - try { - Thread.sleep(300); - } catch (InterruptedException e) { - e.printStackTrace(); - } - i--; - response = blockingStubFull.broadcastTransaction(transaction); - logger.info("repeate times = " + (10 - i)); - } + // totalNetLimit / (totalNetWeight + needBalance) = needNet / needBalance + final BigInteger totalNetWeightBi = BigInteger.valueOf(totalNetWeight); + long needBalance = + totalNetWeightBi + .multiply(BigInteger.valueOf(1_000_000)) + .multiply(BigInteger.valueOf(targetNet)) + .divide(BigInteger.valueOf(totalNetLimit - targetNet)) + .longValue(); - if (response.getResult() == false) { - logger.info("Code = " + response.getCode()); - logger.info("Message = " + response.getMessage().toStringUtf8()); - } - return response; - } + logger.info("getFreezeBalanceNetCount, needBalance: " + needBalance); - /** - * constructor. - */ - public static String exec(String command) throws InterruptedException { - String returnString = ""; - Process pro = null; - Runtime runTime = Runtime.getRuntime(); - if (runTime == null) { - logger.error("Create runtime false!"); - } - try { - pro = runTime.exec(command); - BufferedReader input = new BufferedReader(new InputStreamReader(pro.getInputStream())); - PrintWriter output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream())); - String line; - while ((line = input.readLine()) != null) { - returnString = returnString + line + "\n"; - } - input.close(); - output.close(); - pro.destroy(); - } catch (IOException ex) { - logger.error(null, ex); - } - return returnString; + if (needBalance < 1000000L) { + needBalance = 1000000L; + logger.info( + "getFreezeBalanceNetCount, needBalance less than 1 TRX, modify to: " + needBalance); } + return needBalance; + } - /** - * constructor. - */ - public static HashMap getBycodeAbiNoOptimize(String solFile, String contractName) { - final String compile = Configuration.getByPath("testng.conf") - .getString("defaultParameter.solidityCompile"); + /** constructor. */ + public static GrpcAPI.Return broadcastTransaction( + Transaction transaction, WalletGrpc.WalletBlockingStub blockingStubFull) { + int i = 10; + GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); + while (!response.getResult() && response.getCode() == response_code.SERVER_BUSY && i > 0) { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + i--; + response = blockingStubFull.broadcastTransaction(transaction); + logger.info("repeate times = " + (10 - i)); + } + + if (response.getResult() == false) { + logger.info("Code = " + response.getCode()); + logger.info("Message = " + response.getMessage().toStringUtf8()); + } + return response; + } - String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); - String outputPath = "src/test/resources/soliditycode//output" + dirPath; + /** constructor. */ + public static GrpcAPI.Return broadcastTransactionBoth( + Transaction transaction, + WalletGrpc.WalletBlockingStub blockingStubFull, + WalletGrpc.WalletBlockingStub blockingStubFull1) { + int i = 10; + waitProduceNextBlock(blockingStubFull1); + GrpcAPI.Return response = blockingStubFull1.broadcastTransaction(transaction); + GrpcAPI.Return response1 = blockingStubFull.broadcastTransaction(transaction); + while (response.getResult() == false + && response.getCode() == response_code.SERVER_BUSY + && i > 0) { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + i--; + response = blockingStubFull.broadcastTransaction(transaction); + logger.info("repeate times = " + (10 - i)); + } + + if (response.getResult() == false) { + logger.info("Code = " + response.getCode()); + logger.info("Message = " + response.getMessage().toStringUtf8()); + } + return response; + } - File binFile = new File(outputPath + "/" + contractName + ".bin"); - File abiFile = new File(outputPath + "/" + contractName + ".abi"); - if (binFile.exists()) { - binFile.delete(); - } - if (abiFile.exists()) { - abiFile.delete(); - } + /** constructor. */ + public static String exec(String command) throws InterruptedException { + String returnString = ""; + Process pro = null; + Runtime runTime = Runtime.getRuntime(); + if (runTime == null) { + logger.error("Create runtime false!"); + } + try { + pro = runTime.exec(command); + BufferedReader input = new BufferedReader(new InputStreamReader(pro.getInputStream())); + PrintWriter output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream())); + String line; + while ((line = input.readLine()) != null) { + returnString = returnString + line + "\n"; + } + input.close(); + output.close(); + pro.destroy(); + } catch (IOException ex) { + logger.error(null, ex); + } + return returnString; + } - HashMap retMap = new HashMap<>(); - String absolutePath = System.getProperty("user.dir"); - logger.debug("absolutePath: " + absolutePath); - logger.debug("solFile: " + solFile); - logger.debug("outputPath: " + outputPath); - String cmd = - compile + " --bin --abi --overwrite " + absolutePath + "/" - + solFile + " -o " - + absolutePath + "/" + outputPath; - logger.info("cmd: " + cmd); - - String byteCode = null; - String abI = null; - - // compile solidity file - try { - exec(cmd); - } catch (InterruptedException e) { - e.printStackTrace(); - } - // get byteCode and ABI - try { - byteCode = fileRead(outputPath + "/" + contractName + ".bin", false); - retMap.put("byteCode", byteCode); - logger.debug("byteCode: " + byteCode); - abI = fileRead(outputPath + "/" + contractName + ".abi", false); - retMap.put("abI", abI); - logger.debug("abI: " + abI); - } catch (Exception e) { - e.printStackTrace(); - } - return retMap; - } + /** constructor. */ + public static HashMap getBycodeAbiNoOptimize( + String solFile, String contractName) { + final String compile = + Configuration.getByPath("testng.conf").getString("defaultParameter.solidityCompile"); + + String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); + String outputPath = "src/test/resources/soliditycode//output" + dirPath; + + File binFile = new File(outputPath + "/" + contractName + ".bin"); + File abiFile = new File(outputPath + "/" + contractName + ".abi"); + if (binFile.exists()) { + binFile.delete(); + } + if (abiFile.exists()) { + abiFile.delete(); + } + + HashMap retMap = new HashMap<>(); + String absolutePath = System.getProperty("user.dir"); + logger.debug("absolutePath: " + absolutePath); + logger.debug("solFile: " + solFile); + logger.debug("outputPath: " + outputPath); + String cmd = + compile + + " --bin --abi --overwrite " + + absolutePath + + "/" + + solFile + + " -o " + + absolutePath + + "/" + + outputPath; + logger.info("cmd: " + cmd); + + String byteCode = null; + String abI = null; + + // compile solidity file + try { + exec(cmd); + } catch (InterruptedException e) { + e.printStackTrace(); + } + // get byteCode and ABI + try { + byteCode = fileRead(outputPath + "/" + contractName + ".bin", false); + retMap.put("byteCode", byteCode); + logger.debug("byteCode: " + byteCode); + abI = fileRead(outputPath + "/" + contractName + ".abi", false); + retMap.put("abI", abI); + logger.debug("abI: " + abI); + } catch (Exception e) { + e.printStackTrace(); + } + return retMap; + } - /** - * constructor. - */ - public static HashMap getBycodeAbi(String solFile, String contractName) { - final String compile = Configuration.getByPath("testng.conf") - .getString("defaultParameter.solidityCompile"); + /** constructor. */ + public static HashMap getBycodeAbi(String solFile, String contractName) { + final String compile = + Configuration.getByPath("testng.conf").getString("defaultParameter.solidityCompile"); + + String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); + String outputPath = "src/test/resources/soliditycode//output" + dirPath; + + File binFile = new File(outputPath + "/" + contractName + ".bin"); + File abiFile = new File(outputPath + "/" + contractName + ".abi"); + if (binFile.exists()) { + binFile.delete(); + } + if (abiFile.exists()) { + abiFile.delete(); + } + + HashMap retMap = new HashMap<>(); + String absolutePath = System.getProperty("user.dir"); + logger.debug("absolutePath: " + absolutePath); + logger.debug("solFile: " + solFile); + logger.debug("outputPath: " + outputPath); + String cmd = + compile + + " --optimize --bin --abi --overwrite " + + absolutePath + + "/" + + solFile + + " -o " + + absolutePath + + "/" + + outputPath; + logger.info("cmd: " + cmd); + + String byteCode = null; + String abI = null; + + // compile solidity file + try { + exec(cmd); + } catch (InterruptedException e) { + e.printStackTrace(); + } + // get byteCode and ABI + try { + byteCode = fileRead(outputPath + "/" + contractName + ".bin", false); + retMap.put("byteCode", byteCode); + logger.debug("byteCode: " + byteCode); + abI = fileRead(outputPath + "/" + contractName + ".abi", false); + retMap.put("abI", abI); + logger.debug("abI: " + abI); + } catch (Exception e) { + e.printStackTrace(); + } + return retMap; + } - String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); - String outputPath = "src/test/resources/soliditycode//output" + dirPath; + /** constructor. */ + public static String fileRead(String filePath, boolean isLibrary) throws Exception { + File file = new File(filePath); + FileReader reader = new FileReader(file); + BufferedReader breader = new BufferedReader(reader); + StringBuilder sb = new StringBuilder(); + String s = ""; + if (!isLibrary) { + if ((s = breader.readLine()) != null) { + sb.append(s); + } + breader.close(); + } else { + String fistLine = breader.readLine(); + breader.readLine(); + if ((s = breader.readLine()) != null && !s.equals("")) { + s = s.substring(s.indexOf("-> ") + 3); + sb.append(s + ":"); + } else { + s = fistLine.substring(fistLine.indexOf("__") + 2, fistLine.lastIndexOf("__")); + sb.append(s + ":"); + } + breader.close(); + } + return sb.toString(); + } - File binFile = new File(outputPath + "/" + contractName + ".bin"); - File abiFile = new File(outputPath + "/" + contractName + ".abi"); - if (binFile.exists()) { - binFile.delete(); - } - if (abiFile.exists()) { - abiFile.delete(); - } + /** constructor. */ + public static HashMap getBycodeAbiForLibrary( + String solFile, String contractName) { + HashMap retMap = null; + String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); + String outputPath = "src/test/resources/soliditycode/output" + dirPath; + try { + retMap = PublicMethed.getBycodeAbi(solFile, contractName); + String library = fileRead(outputPath + "/" + contractName + ".bin", true); + retMap.put("library", library); + logger.debug("library: " + library); + } catch (Exception e) { + e.printStackTrace(); + } + + return retMap; + } - HashMap retMap = new HashMap<>(); - String absolutePath = System.getProperty("user.dir"); - logger.debug("absolutePath: " + absolutePath); - logger.debug("solFile: " + solFile); - logger.debug("outputPath: " + outputPath); - String cmd = - compile + " --optimize --bin --abi --overwrite " + absolutePath + "/" - + solFile + " -o " - + absolutePath + "/" + outputPath; - logger.info("cmd: " + cmd); - - String byteCode = null; - String abI = null; - - // compile solidity file - try { - exec(cmd); - } catch (InterruptedException e) { - e.printStackTrace(); - } - // get byteCode and ABI - try { - byteCode = fileRead(outputPath + "/" + contractName + ".bin", false); - retMap.put("byteCode", byteCode); - logger.debug("byteCode: " + byteCode); - abI = fileRead(outputPath + "/" + contractName + ".abi", false); - retMap.put("abI", abI); - logger.debug("abI: " + abI); - } catch (Exception e) { - e.printStackTrace(); - } - return retMap; + /** constructor. */ + public static String triggerConstantContract( + byte[] contractAddress, + String method, + String argsStr, + Boolean isHex, + long callValue, + long feeLimit, + String tokenId, + long tokenValue, + byte[] ownerAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); } - - /** - * constructor. - */ - public static String fileRead(String filePath, boolean isLibrary) throws Exception { - File file = new File(filePath); - FileReader reader = new FileReader(file); - BufferedReader breader = new BufferedReader(reader); - StringBuilder sb = new StringBuilder(); - String s = ""; - if (!isLibrary) { - if ((s = breader.readLine()) != null) { - sb.append(s); - } - breader.close(); - } else { - String fistLine = breader.readLine(); - breader.readLine(); - if ((s = breader.readLine()) != null && !s.equals("")) { - s = s.substring(s.indexOf("-> ") + 3); - sb.append(s + ":"); - } else { - s = fistLine.substring(fistLine.indexOf("__") + 2, fistLine.lastIndexOf("__")); - sb.append(s + ":"); - } - breader.close(); - } - return sb.toString(); + final ECKey ecKey = temKey; + if (argsStr.equalsIgnoreCase("#")) { + logger.info("argsstr is #"); + argsStr = ""; } - /** - * constructor. - */ - public static HashMap getBycodeAbiForLibrary(String solFile, - String contractName) { - HashMap retMap = null; - String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); - String outputPath = "src/test/resources/soliditycode/output" + dirPath; - try { - retMap = PublicMethed.getBycodeAbi(solFile, contractName); - String library = fileRead(outputPath + "/" + contractName + ".bin", true); - retMap.put("library", library); - logger.debug("library: " + library); - } catch (Exception e) { - e.printStackTrace(); - } + byte[] owner = ownerAddress; + byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - return retMap; + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); + + TransactionExtention transactionExtention = + blockingStubFull.triggerConstantContract(triggerContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create call trx failed!"); + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + return null; } - - /** - * constructor. - */ - public static String triggerConstantContract(byte[] contractAddress, String method, - String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull - .triggerConstantContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction.getRetCount() != 0 + && transactionExtention.getConstantResult(0) != null + && transactionExtention.getResult() != null) { + byte[] result = transactionExtention.getConstantResult(0).toByteArray(); + System.out.println("message:" + transaction.getRet(0).getRet()); + System.out.println( + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + System.out.println("Result:" + Hex.toHexString(result)); + return null; + } + + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); + rawBuilder.setFeeLimit(feeLimit); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); + if (transactionExtention == null) { + return null; } - - /** - * constructor. - */ - public static TransactionExtention triggerConstantContractForExtentionOnSolidity( - byte[] contractAddress, String method, String argsStr, Boolean isHex, long callValue, - long feeLimit, String tokenId, long tokenValue, byte[] ownerAddress, String priKey, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubSolidity - .triggerConstantContract(triggerContract); - return transactionExtention; - + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; } + transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println( + "trigger txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } + } - /** - * constructor. - */ - public static String clearContractAbi(byte[] contractAddress, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ClearABIContract.Builder builder = ClearABIContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - - ClearABIContract clearAbiContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.clearContractABI(clearAbiContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } + /** constructor. */ + public static TransactionExtention triggerConstantContractForExtentionOnSolidity( + byte[] contractAddress, + String method, + String argsStr, + Boolean isHex, + long callValue, + long feeLimit, + String tokenId, + long tokenValue, + byte[] ownerAddress, + String priKey, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + if (argsStr.equalsIgnoreCase("#")) { + logger.info("argsstr is #"); + argsStr = ""; + } + + byte[] owner = ownerAddress; + byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); + + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); + + TransactionExtention transactionExtention = + blockingStubSolidity.triggerConstantContract(triggerContract); + return transactionExtention; + } - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } + /** constructor. */ + public static String clearContractAbi( + byte[] contractAddress, + byte[] ownerAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); } + final ECKey ecKey = temKey; - /** - * constructor. - */ - public static TransactionExtention clearContractAbiForExtention(byte[] contractAddress, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + byte[] owner = ownerAddress; - byte[] owner = ownerAddress; - - ClearABIContract.Builder builder = ClearABIContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); + ClearABIContract.Builder builder = ClearABIContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); - ClearABIContract clearAbiContract = builder.build(); + ClearABIContract clearAbiContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.clearContractABI(clearAbiContract); - return transactionExtention; + TransactionExtention transactionExtention = blockingStubFull.clearContractABI(clearAbiContract); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + System.out.println("RPC create call trx failed!"); + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction.getRetCount() != 0 + && transactionExtention.getConstantResult(0) != null + && transactionExtention.getResult() != null) { + byte[] result = transactionExtention.getConstantResult(0).toByteArray(); + System.out.println("message:" + transaction.getRet(0).getRet()); + System.out.println( + ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); + System.out.println("Result:" + Hex.toHexString(result)); + return null; + } + + final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); + Transaction.Builder transBuilder = Transaction.newBuilder(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); + transBuilder.setRawData(rawBuilder); + for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { + ByteString s = transactionExtention.getTransaction().getSignature(i); + transBuilder.setSignature(i, s); + } + for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { + Result r = transactionExtention.getTransaction().getRet(i); + transBuilder.setRet(i, r); + } + texBuilder.setTransaction(transBuilder); + texBuilder.setResult(transactionExtention.getResult()); + texBuilder.setTxid(transactionExtention.getTxid()); + transactionExtention = texBuilder.build(); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } + transaction = signTransaction(ecKey, transaction); + System.out.println( + "trigger txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + if (response.getResult() == false) { + return null; + } else { + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } + } + /** constructor. */ + public static TransactionExtention clearContractAbiForExtention( + byte[] contractAddress, + byte[] ownerAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); } + final ECKey ecKey = temKey; - /** - * constructor. - */ - public static TransactionExtention triggerConstantContractForExtention(byte[] contractAddress, - String method, String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, - long tokenValue, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - if (tokenId.equalsIgnoreCase("") || tokenId.equalsIgnoreCase("#")) { - logger.info("tokenid is 0"); - tokenId = "0"; + byte[] owner = ownerAddress; - } + ClearABIContract.Builder builder = ClearABIContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .triggerConstantContract(triggerContract); - return transactionExtention; - - - } - - /** - * constructor. - */ - public static TransactionExtention triggerSolidityContractForExtention(byte[] contractAddress, - String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, - String priKey, WalletSolidityGrpc.WalletSolidityBlockingStub solidityBlockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } + ClearABIContract clearAbiContract = builder.build(); - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); + TransactionExtention transactionExtention = blockingStubFull.clearContractABI(clearAbiContract); + return transactionExtention; + } - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); + /** constructor. */ + public static TransactionExtention triggerConstantContractForExtention( + byte[] contractAddress, + String method, + String argsStr, + Boolean isHex, + long callValue, + long feeLimit, + String tokenId, + long tokenValue, + byte[] ownerAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + if (argsStr.equalsIgnoreCase("#")) { + logger.info("argsstr is #"); + argsStr = ""; + } + if (tokenId.equalsIgnoreCase("") || tokenId.equalsIgnoreCase("#")) { + logger.info("tokenid is 0"); + tokenId = "0"; + } + + byte[] owner = ownerAddress; + byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); + TransactionExtention transactionExtention = + blockingStubFull.triggerConstantContract(triggerContract); + return transactionExtention; + } - TransactionExtention transactionExtention = solidityBlockingStubFull - .triggerConstantContract(triggerContract); - return transactionExtention; + /** constructor. */ + public static TransactionExtention triggerSolidityContractForExtention( + byte[] contractAddress, + String method, + String argsStr, + Boolean isHex, + long callValue, + long feeLimit, + String tokenId, + long tokenValue, + byte[] ownerAddress, + String priKey, + WalletSolidityGrpc.WalletSolidityBlockingStub solidityBlockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + if (argsStr.equalsIgnoreCase("#")) { + logger.info("argsstr is #"); + argsStr = ""; + } + + byte[] owner = ownerAddress; + byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); + + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); + + TransactionExtention transactionExtention = + solidityBlockingStubFull.triggerConstantContract(triggerContract); + return transactionExtention; + } + /** constructor. */ + public static TransactionExtention triggerContractForExtention( + byte[] contractAddress, + String method, + String argsStr, + Boolean isHex, + long callValue, + long feeLimit, + String tokenId, + long tokenValue, + byte[] ownerAddress, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); } - - /** - * constructor. - */ - - public static TransactionExtention triggerContractForExtention(byte[] contractAddress, - String method, String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, - long tokenValue, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - return transactionExtention; - + final ECKey ecKey = temKey; + if (argsStr.equalsIgnoreCase("#")) { + logger.info("argsstr is #"); + argsStr = ""; } - /** - * constructor. - */ - public static String create2(String[] parameters) { - if (parameters == null || parameters.length != 3) { - logger.error("create2 needs 3 parameter:\ncreate2 address code salt"); - return null; - } - - byte[] address = WalletClient.decodeFromBase58Check(parameters[0]); - if (!WalletClient.addressValid(address)) { - logger.error("length of address must be 21 bytes."); - return null; - } - - byte[] code = Hex.decode(parameters[1]); - byte[] temp = Longs.toByteArray(Long.parseLong(parameters[2])); - if (temp.length != 8) { - logger.error("Invalid salt!"); - return null; - } - byte[] salt = new byte[32]; - System.arraycopy(temp, 0, salt, 24, 8); + byte[] owner = ownerAddress; + byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - byte[] mergedData = ByteUtil.merge(address, salt, sha3(code)); - String create2Address = Base58.encode58Check(sha3omit12(mergedData)); - - logger.info("create2 Address: " + create2Address); + TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)); + builder.setContractAddress(ByteString.copyFrom(contractAddress)); + builder.setData(ByteString.copyFrom(input)); + builder.setCallValue(callValue); + builder.setTokenId(Long.parseLong(tokenId)); + builder.setCallTokenValue(tokenValue); + TriggerSmartContract triggerContract = builder.build(); + + TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); + return transactionExtention; + } - return create2Address; + /** constructor. */ + public static String create2(String[] parameters) { + if (parameters == null || parameters.length != 3) { + logger.error("create2 needs 3 parameter:\ncreate2 address code salt"); + return null; } + byte[] address = WalletClient.decodeFromBase58Check(parameters[0]); + if (!WalletClient.addressValid(address)) { + logger.error("length of address must be 21 bytes."); + return null; + } - /** - * constructor. - */ - public static boolean sendShieldCoin(byte[] publicZenTokenOwnerAddress, long fromAmount, - ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, - byte[] publicZenTokenToAddress, long toAmount, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - PrivateParameters.Builder builder = PrivateParameters.newBuilder(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); - builder.setFromAmount(fromAmount); - } - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); - builder.setToAmount(toAmount); - } - - if (shieldAddressInfo != null) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - - //String shieldAddress = noteInfo.getPaymentAddress(); - //ShieldAddressInfo addressInfo = - // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - builder.setAsk(ByteString.copyFrom(expandedSpendingKey.getAsk())); - builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); - builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); - } catch (Exception e) { - System.out.println(e); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - //System.out.println("address " + noteInfo.getPaymentAddress()); - //System.out.println("value " + noteInfo.getValue()); - //System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); - //System.out.println("trxId " + noteInfo.getTrxId()); - //System.out.println("index " + noteInfo.getIndex()); - //System.out.println("meno " + new String(noteInfo.getMemo())); - - SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); - spendNoteBuilder.setNote(noteBuild.build()); - try { - spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - - IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); - spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); - spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); - - builder.addShieldedSpends(spendNoteBuilder.build()); - - } else { - byte[] ovk = ByteArray - .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - builder.setOvk(ByteString.copyFrom(ovk)); - } - - if (shieldOutputList.size() > 0) { - for (int i = 0; i < shieldOutputList.size(); ++i) { - builder - .addShieldedReceives(ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); - } - } - - TransactionExtention transactionExtention = blockingStubFull - .createShieldedTransaction(builder.build()); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - Any any = transaction.getRawData().getContract(0).getParameter(); - - try { - ShieldedTransferContract shieldedTransferContract = any - .unpack(ShieldedTransferContract.class); - if (shieldedTransferContract.getFromAmount() > 0 || fromAmount == 321321) { - transaction = signTransactionForShield(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - } else { - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - } - } catch (Exception e) { - System.out.println(e); - } - return broadcastTransaction(transaction, blockingStubFull).getResult(); - } - - /** - * constructor. - */ - public static boolean sendShieldCoinWithoutAsk(byte[] publicZenTokenOwnerAddress, long fromAmount, - ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, - byte[] publicZenTokenToAddress, long toAmount, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - PrivateParametersWithoutAsk.Builder builder = PrivateParametersWithoutAsk.newBuilder(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); - builder.setFromAmount(fromAmount); - } - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); - builder.setToAmount(toAmount); - } + byte[] code = Hex.decode(parameters[1]); + byte[] temp = Longs.toByteArray(Long.parseLong(parameters[2])); + if (temp.length != 8) { + logger.error("Invalid salt!"); + return null; + } + byte[] salt = new byte[32]; + System.arraycopy(temp, 0, salt, 24, 8); - byte[] ask = new byte[32]; - if (shieldAddressInfo != null) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); - if (merkleVoucherInfo.getVouchersCount() != 1) { - System.out.println("Can't get all merkel tree, please check the notes."); - return false; - } - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - - //String shieldAddress = noteInfo.getPaymentAddress(); - //ShieldAddressInfo addressInfo = - // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); - String shieldAddress = noteTx.getNote().getPaymentAddress(); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - System.arraycopy(expandedSpendingKey.getAsk(), 0, ask, 0, 32); - builder.setAk( - ByteString.copyFrom(ExpandedSpendingKey.getAkFromAsk(expandedSpendingKey.getAsk()))); - builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); - builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); - } catch (Exception e) { - System.out.println(e); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - //System.out.println("address " + noteInfo.getPaymentAddress()); - //System.out.println("value " + noteInfo.getValue()); - //System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); - //System.out.println("trxId " + noteInfo.getTrxId()); - //System.out.println("index " + noteInfo.getIndex()); - //System.out.println("meno " + new String(noteInfo.getMemo())); - - SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); - spendNoteBuilder.setNote(noteBuild.build()); - try { - spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - - spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); - spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); - - builder.addShieldedSpends(spendNoteBuilder.build()); - - } else { - byte[] ovk = ByteArray - .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - builder.setOvk(ByteString.copyFrom(ovk)); - } + byte[] mergedData = ByteUtil.merge(address, salt, sha3(code)); + String create2Address = Base58.encode58Check(sha3omit12(mergedData)); - if (shieldOutputList.size() > 0) { - for (int i = 0; i < shieldOutputList.size(); ++i) { - builder - .addShieldedReceives(ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); - } - } + logger.info("create2 Address: " + create2Address); - TransactionExtention transactionExtention = blockingStubFull - .createShieldedTransactionWithoutSpendAuthSig(builder.build()); - if (transactionExtention == null) { - System.out.println("sendShieldCoinWithoutAsk failure."); - return false; - } - BytesMessage trxHash = blockingStubFull - .getShieldTransactionHash(transactionExtention.getTransaction()); - if (trxHash == null || trxHash.getValue().toByteArray().length != 32) { - System.out.println("sendShieldCoinWithoutAsk get transaction hash failure."); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRawData().getContract(0).getType() - != ContractType.ShieldedTransferContract) { - System.out.println("This method only for ShieldedTransferContract, please check!"); - return false; - } - Any any = transaction.getRawData().getContract(0).getParameter(); - Transaction transaction1 = transactionExtention.getTransaction(); - try { - ShieldedTransferContract shieldContract = any.unpack(ShieldedTransferContract.class); - List spendDescList = shieldContract.getSpendDescriptionList(); - ShieldedTransferContract.Builder contractBuild = shieldContract.toBuilder() - .clearSpendDescription(); - for (int i = 0; i < spendDescList.size(); i++) { - - SpendAuthSigParameters.Builder builder1 = SpendAuthSigParameters.newBuilder(); - builder1.setAsk(ByteString.copyFrom(ask)); - builder1.setTxHash(ByteString.copyFrom(trxHash.getValue().toByteArray())); - builder1.setAlpha(builder.getShieldedSpends(i).getAlpha()); - SpendDescription.Builder spendDescription = spendDescList.get(i).toBuilder(); - BytesMessage authSig = blockingStubFull.createSpendAuthSig(builder1.build()); - spendDescription - .setSpendAuthoritySignature(ByteString.copyFrom(authSig.getValue().toByteArray())); - - contractBuild.addSpendDescription(spendDescription.build()); - } - - Transaction.raw.Builder rawBuilder = transaction.toBuilder().getRawDataBuilder() - .clearContract().addContract( - Transaction.Contract.newBuilder().setType(ContractType.ShieldedTransferContract) - .setParameter(Any.pack(contractBuild.build())).build()); - - transaction = transaction.toBuilder().clearRawData().setRawData(rawBuilder).build(); - - transactionExtention = transactionExtention.toBuilder().setTransaction(transaction).build(); - - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - transaction1 = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - if (transaction1.getRawData().getContract(0).getType() - != ContractType.ShieldedTransferContract) { - transaction1 = signTransaction(ecKey, transaction1); - } else { - Any any1 = transaction1.getRawData().getContract(0).getParameter(); - ShieldedTransferContract shieldedTransferContract = any1 - .unpack(ShieldedTransferContract.class); - if (shieldedTransferContract.getFromAmount() > 0) { - transaction1 = signTransactionForShield(ecKey, transaction1); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction1.getRawData().toByteArray()))); - } - } - } catch (Exception e) { - System.out.println(e); - } - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction1.getRawData().toByteArray()))); - return broadcastTransaction(transaction1, blockingStubFull).getResult(); - } - - - /** - * constructor. - */ - public static List addShieldOutputList(List shieldOutList, String shieldToAddress, - String toAmountString, String menoString) { - String shieldAddress = shieldToAddress; - String amountString = toAmountString; - if (menoString.equals("null")) { - menoString = ""; - } - long shieldAmount = 0; - if (!StringUtil.isNullOrEmpty(amountString)) { - shieldAmount = Long.valueOf(amountString); - } + return create2Address; + } - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setValue(shieldAmount); - try { - noteBuild.setRcm(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - noteBuild.setMemo(ByteString.copyFrom(menoString.getBytes())); - shieldOutList.add(noteBuild.build()); - //logger.info(shieldOutList.toString()); - return shieldOutList; + /** constructor. */ + public static boolean sendShieldCoin( + byte[] publicZenTokenOwnerAddress, + long fromAmount, + ShieldAddressInfo shieldAddressInfo, + NoteTx noteTx, + List shieldOutputList, + byte[] publicZenTokenToAddress, + long toAmount, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + PrivateParameters.Builder builder = PrivateParameters.newBuilder(); + if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { + builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); + builder.setFromAmount(fromAmount); + } + if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { + builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); + builder.setToAmount(toAmount); + } + + if (shieldAddressInfo != null) { + OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); + + // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); + OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); + outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); + outPointBuild.setIndex(noteTx.getIndex()); + request.addOutPoints(outPointBuild.build()); + + // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); + + // String shieldAddress = noteInfo.getPaymentAddress(); + // ShieldAddressInfo addressInfo = + // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); + SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); + try { + ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); + builder.setAsk(ByteString.copyFrom(expandedSpendingKey.getAsk())); + builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); + builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); + } catch (Exception e) { + System.out.println(e); + } + + Note.Builder noteBuild = Note.newBuilder(); + noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); + noteBuild.setValue(noteTx.getNote().getValue()); + noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); + noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); + + // System.out.println("address " + noteInfo.getPaymentAddress()); + // System.out.println("value " + noteInfo.getValue()); + // System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); + // System.out.println("trxId " + noteInfo.getTrxId()); + // System.out.println("index " + noteInfo.getIndex()); + // System.out.println("meno " + new String(noteInfo.getMemo())); + + SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); + spendNoteBuilder.setNote(noteBuild.build()); + try { + spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); + } catch (Exception e) { + System.out.println(e); + } + + IncrementalMerkleVoucherInfo merkleVoucherInfo = + blockingStubFull.getMerkleTreeVoucherInfo(request.build()); + spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); + spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); + + builder.addShieldedSpends(spendNoteBuilder.build()); + + } else { + byte[] ovk = + ByteArray.fromHexString( + "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); + builder.setOvk(ByteString.copyFrom(ovk)); + } + + if (shieldOutputList.size() > 0) { + for (int i = 0; i < shieldOutputList.size(); ++i) { + builder.addShieldedReceives( + ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); + } + } + + TransactionExtention transactionExtention = + blockingStubFull.createShieldedTransaction(builder.build()); + if (transactionExtention == null) { + return false; } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + Any any = transaction.getRawData().getContract(0).getParameter(); - /** - * constructor. - */ - public static Optional generateShieldAddress() { - ShieldAddressInfo addressInfo = new ShieldAddressInfo(); - try { - DiversifierT diversifier = DiversifierT.random(); - SpendingKey spendingKey = SpendingKey.random(); - FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); - IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(diversifier).get(); - - addressInfo.setSk(spendingKey.getValue()); - addressInfo.setD(diversifier); - addressInfo.setIvk(incomingViewingKey.getValue()); - addressInfo.setOvk(fullViewingKey.getOvk()); - addressInfo.setPkD(paymentAddress.getPkD()); - - if (addressInfo.validateCheck()) { - return Optional.of(addressInfo); - } - } catch (Exception e) { - e.printStackTrace(); - } - - return Optional.empty(); + try { + ShieldedTransferContract shieldedTransferContract = + any.unpack(ShieldedTransferContract.class); + if (shieldedTransferContract.getFromAmount() > 0 || fromAmount == 321321) { + transaction = signTransactionForShield(ecKey, transaction); + System.out.println( + "trigger txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + } else { + System.out.println( + "trigger txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + } + } catch (Exception e) { + System.out.println(e); } + return broadcastTransaction(transaction, blockingStubFull).getResult(); + } - - /** - * constructor. - */ - public static DecryptNotes listShieldNote(Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - logger.info(ByteArray.toHexString(shieldAddressInfo.get().ivk)); - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); - logger.info(notes.toString()); - return notes; - } - - /** - * constructor. - */ - public static DecryptNotes getShieldNotesByIvk(Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - //startBlockNum = 0L; - logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum + 1); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); - logger.info(notes.toString()); - return notes; - } - - /** - * constructor. - */ - public static DecryptNotesMarked getShieldNotesAndMarkByIvk( - Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - //startBlockNum = 0L; - logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); - try { - IvkDecryptAndMarkParameters.Builder builder = IvkDecryptAndMarkParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum + 1); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - builder.setAk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getNk())); - DecryptNotesMarked decryptNotes = blockingStubFull.scanAndMarkNoteByIvk(builder.build()); - logger.info(decryptNotes.toString()); - return decryptNotes; - } catch (Exception e) { - logger.info(e.toString()); - return null; - } + /** constructor. */ + public static boolean sendShieldCoinWithoutAsk( + byte[] publicZenTokenOwnerAddress, + long fromAmount, + ShieldAddressInfo shieldAddressInfo, + NoteTx noteTx, + List shieldOutputList, + byte[] publicZenTokenToAddress, + long toAmount, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + PrivateParametersWithoutAsk.Builder builder = PrivateParametersWithoutAsk.newBuilder(); + if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { + builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); + builder.setFromAmount(fromAmount); + } + if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { + builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); + builder.setToAmount(toAmount); + } + + byte[] ask = new byte[32]; + if (shieldAddressInfo != null) { + OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); + + // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); + OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); + outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); + outPointBuild.setIndex(noteTx.getIndex()); + request.addOutPoints(outPointBuild.build()); + IncrementalMerkleVoucherInfo merkleVoucherInfo = + blockingStubFull.getMerkleTreeVoucherInfo(request.build()); + if (merkleVoucherInfo.getVouchersCount() != 1) { + System.out.println("Can't get all merkel tree, please check the notes."); + return false; + } + + // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); + + // String shieldAddress = noteInfo.getPaymentAddress(); + // ShieldAddressInfo addressInfo = + // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); + String shieldAddress = noteTx.getNote().getPaymentAddress(); + SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); + try { + ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); + System.arraycopy(expandedSpendingKey.getAsk(), 0, ask, 0, 32); + builder.setAk( + ByteString.copyFrom(ExpandedSpendingKey.getAkFromAsk(expandedSpendingKey.getAsk()))); + builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); + builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); + } catch (Exception e) { + System.out.println(e); + } + + Note.Builder noteBuild = Note.newBuilder(); + noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); + noteBuild.setValue(noteTx.getNote().getValue()); + noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); + noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); + + // System.out.println("address " + noteInfo.getPaymentAddress()); + // System.out.println("value " + noteInfo.getValue()); + // System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); + // System.out.println("trxId " + noteInfo.getTrxId()); + // System.out.println("index " + noteInfo.getIndex()); + // System.out.println("meno " + new String(noteInfo.getMemo())); + + SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); + spendNoteBuilder.setNote(noteBuild.build()); + try { + spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); + } catch (Exception e) { + System.out.println(e); + } + + spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); + spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); + + builder.addShieldedSpends(spendNoteBuilder.build()); + + } else { + byte[] ovk = + ByteArray.fromHexString( + "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); + builder.setOvk(ByteString.copyFrom(ovk)); + } + + if (shieldOutputList.size() > 0) { + for (int i = 0; i < shieldOutputList.size(); ++i) { + builder.addShieldedReceives( + ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); + } + } + + TransactionExtention transactionExtention = + blockingStubFull.createShieldedTransactionWithoutSpendAuthSig(builder.build()); + if (transactionExtention == null) { + System.out.println("sendShieldCoinWithoutAsk failure."); + return false; } - - /** - * constructor. - */ - public static DecryptNotesMarked getShieldNotesAndMarkByIvkOnSolidity( - Optional shieldAddressInfo, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Block currentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - //startBlockNum = 0L; - logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); - try { - IvkDecryptAndMarkParameters.Builder builder = IvkDecryptAndMarkParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum + 1); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - builder.setAk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getNk())); - DecryptNotesMarked decryptNotes = blockingStubSolidity.scanAndMarkNoteByIvk(builder.build()); - logger.info(decryptNotes.toString()); - return decryptNotes; - } catch (Exception e) { - logger.info(e.toString()); - return null; - } + BytesMessage trxHash = + blockingStubFull.getShieldTransactionHash(transactionExtention.getTransaction()); + if (trxHash == null || trxHash.getValue().toByteArray().length != 32) { + System.out.println("sendShieldCoinWithoutAsk get transaction hash failure."); + return false; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction.getRawData().getContract(0).getType() + != ContractType.ShieldedTransferContract) { + System.out.println("This method only for ShieldedTransferContract, please check!"); + return false; + } + Any any = transaction.getRawData().getContract(0).getParameter(); + Transaction transaction1 = transactionExtention.getTransaction(); + try { + ShieldedTransferContract shieldContract = any.unpack(ShieldedTransferContract.class); + List spendDescList = shieldContract.getSpendDescriptionList(); + ShieldedTransferContract.Builder contractBuild = + shieldContract.toBuilder().clearSpendDescription(); + for (int i = 0; i < spendDescList.size(); i++) { + + SpendAuthSigParameters.Builder builder1 = SpendAuthSigParameters.newBuilder(); + builder1.setAsk(ByteString.copyFrom(ask)); + builder1.setTxHash(ByteString.copyFrom(trxHash.getValue().toByteArray())); + builder1.setAlpha(builder.getShieldedSpends(i).getAlpha()); + SpendDescription.Builder spendDescription = spendDescList.get(i).toBuilder(); + BytesMessage authSig = blockingStubFull.createSpendAuthSig(builder1.build()); + spendDescription.setSpendAuthoritySignature( + ByteString.copyFrom(authSig.getValue().toByteArray())); + + contractBuild.addSpendDescription(spendDescription.build()); + } + + Transaction.raw.Builder rawBuilder = + transaction.toBuilder() + .getRawDataBuilder() + .clearContract() + .addContract( + Transaction.Contract.newBuilder() + .setType(ContractType.ShieldedTransferContract) + .setParameter(Any.pack(contractBuild.build())) + .build()); + + transaction = transaction.toBuilder().clearRawData().setRawData(rawBuilder).build(); + + transactionExtention = transactionExtention.toBuilder().setTransaction(transaction).build(); + + if (transactionExtention == null) { + return false; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return false; + } + transaction1 = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return false; + } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + + if (transaction1.getRawData().getContract(0).getType() + != ContractType.ShieldedTransferContract) { + transaction1 = signTransaction(ecKey, transaction1); + } else { + Any any1 = transaction1.getRawData().getContract(0).getParameter(); + ShieldedTransferContract shieldedTransferContract = + any1.unpack(ShieldedTransferContract.class); + if (shieldedTransferContract.getFromAmount() > 0) { + transaction1 = signTransactionForShield(ecKey, transaction1); + System.out.println( + "trigger txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction1.getRawData().toByteArray()))); + } + } + } catch (Exception e) { + System.out.println(e); } + System.out.println( + "trigger txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction1.getRawData().toByteArray()))); + return broadcastTransaction(transaction1, blockingStubFull).getResult(); + } - /** - * constructor. - */ - public static Integer getShieldNotesCount(Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - - if (currentBlockNum < 100) { - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(0); - builder.setEndBlockIndex(currentBlockNum); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); - logger.info(notes.toString()); - return notes.getNoteTxsCount(); - } - Integer count = 0; - Long startBlockNum = 0L; - while (startBlockNum + 100 < currentBlockNum) { - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum); - builder.setEndBlockIndex(startBlockNum + 100); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); - count = count + notes.getNoteTxsCount(); - startBlockNum = startBlockNum + 100; - } - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum); - builder.setEndBlockIndex(currentBlockNum); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); - count = count + notes.getNoteTxsCount(); - return count; - - } - - /** - * constructor. - */ - public static DecryptNotes getShieldNotesByIvkOnSolidity( - Optional shieldAddressInfo, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Block currentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum); - builder.setEndBlockIndex(currentBlockNum); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubSolidity.scanNoteByIvk(builder.build()); - logger.info(notes.toString()); - return notes; - } - - - /** - * constructor. - */ - public static DecryptNotes getShieldNotesByOvk(Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - logger.info("ovk:" + ByteArray.toHexString(shieldAddressInfo.get().ovk)); - OvkDecryptParameters.Builder builder = OvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum + 1); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setOvk(ByteString.copyFrom(shieldAddressInfo.get().getOvk())); - DecryptNotes notes = blockingStubFull.scanNoteByOvk(builder.build()); - logger.info(notes.toString()); - return notes; - } - - /** - * constructor. - */ - public static DecryptNotes getShieldNotesByOvkOnSolidity( - Optional shieldAddressInfo, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Block currentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - OvkDecryptParameters.Builder builder = OvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum); - builder.setEndBlockIndex(currentBlockNum); - builder.setOvk(ByteString.copyFrom(shieldAddressInfo.get().getOvk())); - DecryptNotes notes = blockingStubSolidity.scanNoteByOvk(builder.build()); - logger.info(notes.toString()); - return notes; - } - - - /** - * constructor. - */ - public static String getMemo(Note note) { - return ZenUtils.getMemo(note.getMemo().toByteArray()); - } - - /** - * constructor. - */ - public static SpendResult getSpendResult(ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - Optional merkleVoucherInfo = Optional - .of(blockingStubFull.getMerkleTreeVoucherInfo(request.build())); - - if (merkleVoucherInfo.isPresent() && merkleVoucherInfo.get().getVouchersCount() > 0) { - NoteParameters.Builder builder = NoteParameters.newBuilder(); - try { - builder.setAk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getNk())); - logger.info("AK:" + ByteArray.toHexString(shieldAddressInfo.getFullViewingKey().getAk())); - logger.info("NK:" + ByteArray.toHexString(shieldAddressInfo.getFullViewingKey().getNk())); - } catch (Exception e) { - Assert.assertTrue(1 == 1); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - builder.setNote(noteBuild.build()); - builder.setTxid(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - builder.setIndex(noteTx.getIndex()); - //builder.setVoucher(merkleVoucherInfo.getVouchers(0)); - - SpendResult result = blockingStubFull.isSpend(builder.build()); - return result; + /** constructor. */ + public static List addShieldOutputList( + List shieldOutList, String shieldToAddress, String toAmountString, String menoString) { + String shieldAddress = shieldToAddress; + String amountString = toAmountString; + if (menoString.equals("null")) { + menoString = ""; + } + long shieldAmount = 0; + if (!StringUtil.isNullOrEmpty(amountString)) { + shieldAmount = Long.valueOf(amountString); + } + + Note.Builder noteBuild = Note.newBuilder(); + noteBuild.setPaymentAddress(shieldAddress); + noteBuild.setPaymentAddress(shieldAddress); + noteBuild.setValue(shieldAmount); + try { + noteBuild.setRcm(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); + } catch (Exception e) { + System.out.println(e); + } + noteBuild.setMemo(ByteString.copyFrom(menoString.getBytes())); + shieldOutList.add(noteBuild.build()); + // logger.info(shieldOutList.toString()); + return shieldOutList; + } - } - return null; + /** constructor. */ + public static Optional generateShieldAddress() { + ShieldAddressInfo addressInfo = new ShieldAddressInfo(); + try { + DiversifierT diversifier = DiversifierT.random(); + SpendingKey spendingKey = SpendingKey.random(); + FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); + IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); + PaymentAddress paymentAddress = incomingViewingKey.address(diversifier).get(); + + addressInfo.setSk(spendingKey.getValue()); + addressInfo.setD(diversifier); + addressInfo.setIvk(incomingViewingKey.getValue()); + addressInfo.setOvk(fullViewingKey.getOvk()); + addressInfo.setPkD(paymentAddress.getPkD()); + + if (addressInfo.validateCheck()) { + return Optional.of(addressInfo); + } + } catch (Exception e) { + e.printStackTrace(); + } + + return Optional.empty(); + } - } + /** constructor. */ + public static DecryptNotes listShieldNote( + Optional shieldAddressInfo, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Long startBlockNum = 0L; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + logger.info(ByteArray.toHexString(shieldAddressInfo.get().ivk)); + IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum); + builder.setEndBlockIndex(currentBlockNum + 1); + builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); + DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); + logger.info(notes.toString()); + return notes; + } - /** - * constructor. - */ - public static SpendResult getSpendResultOnSolidity(ShieldAddressInfo shieldAddressInfo, - NoteTx noteTx, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - Optional merkleVoucherInfo = Optional - .of(blockingStubSolidity.getMerkleTreeVoucherInfo(request.build())); - - if (merkleVoucherInfo.isPresent() && merkleVoucherInfo.get().getVouchersCount() > 0) { - NoteParameters.Builder builder = NoteParameters.newBuilder(); - try { - builder.setAk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getNk())); - } catch (Exception e) { - Assert.assertTrue(1 == 1); - } - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - builder.setNote(noteBuild.build()); - builder.setTxid(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - builder.setIndex(noteTx.getIndex()); - //builder.setVoucher(merkleVoucherInfo.getVouchers(0)); - - SpendResult result = blockingStubSolidity.isSpend(builder.build()); - return result; - } - return null; - } + /** constructor. */ + public static DecryptNotes getShieldNotesByIvk( + Optional shieldAddressInfo, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Long startBlockNum = 0L; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + // startBlockNum = 0L; + logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); + IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum + 1); + builder.setEndBlockIndex(currentBlockNum + 1); + builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); + DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); + logger.info(notes.toString()); + return notes; + } - /** - * constructor. - */ - public static String getShieldNullifier(ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, - WalletGrpc.WalletBlockingStub blockingStubFull) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); - if (merkleVoucherInfo.getVouchersCount() < 1) { - System.out.println("get merkleVoucherInfo failure."); - return null; - } - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - String shieldAddress = noteTx.getNote().getPaymentAddress(); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - //TODO - FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); - NfParameters.Builder builder = NfParameters.newBuilder(); - builder.setNote(noteBuild.build()); - builder.setVoucher(merkleVoucherInfo.getVouchers(0)); - builder.setAk(ByteString.copyFrom(fullViewingKey.getAk())); - builder.setNk(ByteString.copyFrom(fullViewingKey.getNk())); - - BytesMessage nullifier = blockingStubFull.createShieldNullifier(builder.build()); - return ByteArray.toHexString(nullifier.getValue().toByteArray()); - - } catch (Exception e) { - e.printStackTrace(); - } - return null; + /** constructor. */ + public static DecryptNotesMarked getShieldNotesAndMarkByIvk( + Optional shieldAddressInfo, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Long startBlockNum = 0L; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + // startBlockNum = 0L; + logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); + try { + IvkDecryptAndMarkParameters.Builder builder = IvkDecryptAndMarkParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum + 1); + builder.setEndBlockIndex(currentBlockNum + 1); + builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); + builder.setAk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getAk())); + builder.setNk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getNk())); + DecryptNotesMarked decryptNotes = blockingStubFull.scanAndMarkNoteByIvk(builder.build()); + logger.info(decryptNotes.toString()); + return decryptNotes; + } catch (Exception e) { + logger.info(e.toString()); + return null; + } + } + /** constructor. */ + public static DecryptNotesMarked getShieldNotesAndMarkByIvkOnSolidity( + Optional shieldAddressInfo, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + Block currentBlock = + blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Long startBlockNum = 0L; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + // startBlockNum = 0L; + logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); + try { + IvkDecryptAndMarkParameters.Builder builder = IvkDecryptAndMarkParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum + 1); + builder.setEndBlockIndex(currentBlockNum + 1); + builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); + builder.setAk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getAk())); + builder.setNk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getNk())); + DecryptNotesMarked decryptNotes = blockingStubSolidity.scanAndMarkNoteByIvk(builder.build()); + logger.info(decryptNotes.toString()); + return decryptNotes; + } catch (Exception e) { + logger.info(e.toString()); + return null; } + } + /** constructor. */ + public static Integer getShieldNotesCount( + Optional shieldAddressInfo, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + + if (currentBlockNum < 100) { + IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); + builder.setStartBlockIndex(0); + builder.setEndBlockIndex(currentBlockNum); + builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); + DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); + logger.info(notes.toString()); + return notes.getNoteTxsCount(); + } + Integer count = 0; + Long startBlockNum = 0L; + while (startBlockNum + 100 < currentBlockNum) { + IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum); + builder.setEndBlockIndex(startBlockNum + 100); + builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); + DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); + count = count + notes.getNoteTxsCount(); + startBlockNum = startBlockNum + 100; + } + IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum); + builder.setEndBlockIndex(currentBlockNum); + builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); + DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); + count = count + notes.getNoteTxsCount(); + return count; + } - /** - * constructor. - */ - public static String sendShieldCoinGetTxid(byte[] publicZenTokenOwnerAddress, long fromAmount, - ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, - byte[] publicZenTokenToAddress, long toAmount, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + /** constructor. */ + public static DecryptNotes getShieldNotesByIvkOnSolidity( + Optional shieldAddressInfo, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + Block currentBlock = + blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Long startBlockNum = 0L; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum); + builder.setEndBlockIndex(currentBlockNum); + builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); + DecryptNotes notes = blockingStubSolidity.scanNoteByIvk(builder.build()); + logger.info(notes.toString()); + return notes; + } - PrivateParameters.Builder builder = PrivateParameters.newBuilder(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); - builder.setFromAmount(fromAmount); - } - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); - builder.setToAmount(toAmount); - } + /** constructor. */ + public static DecryptNotes getShieldNotesByOvk( + Optional shieldAddressInfo, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Long startBlockNum = 0L; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + logger.info("ovk:" + ByteArray.toHexString(shieldAddressInfo.get().ovk)); + OvkDecryptParameters.Builder builder = OvkDecryptParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum + 1); + builder.setEndBlockIndex(currentBlockNum + 1); + builder.setOvk(ByteString.copyFrom(shieldAddressInfo.get().getOvk())); + DecryptNotes notes = blockingStubFull.scanNoteByOvk(builder.build()); + logger.info(notes.toString()); + return notes; + } - if (shieldAddressInfo != null) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - - //String shieldAddress = noteInfo.getPaymentAddress(); - //ShieldAddressInfo addressInfo = - // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - builder.setAsk(ByteString.copyFrom(expandedSpendingKey.getAsk())); - builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); - builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); - } catch (Exception e) { - System.out.println(e); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - //System.out.println("address " + noteInfo.getPaymentAddress()); - //System.out.println("value " + noteInfo.getValue()); - //System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); - //System.out.println("trxId " + noteInfo.getTrxId()); - //System.out.println("index " + noteInfo.getIndex()); - //System.out.println("meno " + new String(noteInfo.getMemo())); - - SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); - spendNoteBuilder.setNote(noteBuild.build()); - try { - spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - - IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); - spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); - spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); - - builder.addShieldedSpends(spendNoteBuilder.build()); - - } else { - byte[] ovk = ByteArray - .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - builder.setOvk(ByteString.copyFrom(ovk)); - } + /** constructor. */ + public static DecryptNotes getShieldNotesByOvkOnSolidity( + Optional shieldAddressInfo, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + Block currentBlock = + blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); + Long startBlockNum = 0L; + if (currentBlockNum > 100) { + startBlockNum = currentBlockNum - 100; + } + OvkDecryptParameters.Builder builder = OvkDecryptParameters.newBuilder(); + builder.setStartBlockIndex(startBlockNum); + builder.setEndBlockIndex(currentBlockNum); + builder.setOvk(ByteString.copyFrom(shieldAddressInfo.get().getOvk())); + DecryptNotes notes = blockingStubSolidity.scanNoteByOvk(builder.build()); + logger.info(notes.toString()); + return notes; + } - if (shieldOutputList.size() > 0) { - for (int i = 0; i < shieldOutputList.size(); ++i) { - builder - .addShieldedReceives(ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); - } - } + /** constructor. */ + public static String getMemo(Note note) { + return ZenUtils.getMemo(note.getMemo().toByteArray()); + } - TransactionExtention transactionExtention = blockingStubFull - .createShieldedTransaction(builder.build()); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - Any any = transaction.getRawData().getContract(0).getParameter(); + /** constructor. */ + public static SpendResult getSpendResult( + ShieldAddressInfo shieldAddressInfo, + NoteTx noteTx, + WalletGrpc.WalletBlockingStub blockingStubFull) { - try { - ShieldedTransferContract shieldedTransferContract = any - .unpack(ShieldedTransferContract.class); - if (shieldedTransferContract.getFromAmount() > 0) { - transaction = signTransactionForShield(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - } else { - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - } - } catch (Exception e) { - System.out.println(e); - } - broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - - /** - * constructor. - */ - public static byte[] decode58Check(String input) { - byte[] decodeCheck = org.tron.common.utils.Base58.decode(input); - if (decodeCheck.length <= 4) { - return null; - } - byte[] decodeData = new byte[decodeCheck.length - 4]; - System.arraycopy(decodeCheck, 0, decodeData, 0, decodeData.length); - byte[] hash0 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), decodeData); - byte[] hash1 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), hash0); - if (hash1[0] == decodeCheck[decodeData.length] && hash1[1] == decodeCheck[decodeData.length + 1] - && hash1[2] == decodeCheck[decodeData.length + 2] && hash1[3] == decodeCheck[ - decodeData.length + 3]) { - return decodeData; - } - return null; - } + OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); + OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); + outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); + outPointBuild.setIndex(noteTx.getIndex()); + request.addOutPoints(outPointBuild.build()); + Optional merkleVoucherInfo = + Optional.of(blockingStubFull.getMerkleTreeVoucherInfo(request.build())); + + if (merkleVoucherInfo.isPresent() && merkleVoucherInfo.get().getVouchersCount() > 0) { + NoteParameters.Builder builder = NoteParameters.newBuilder(); + try { + builder.setAk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getAk())); + builder.setNk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getNk())); + logger.info("AK:" + ByteArray.toHexString(shieldAddressInfo.getFullViewingKey().getAk())); + logger.info("NK:" + ByteArray.toHexString(shieldAddressInfo.getFullViewingKey().getNk())); + } catch (Exception e) { + Assert.assertTrue(1 == 1); + } + + Note.Builder noteBuild = Note.newBuilder(); + noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); + noteBuild.setValue(noteTx.getNote().getValue()); + noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); + noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); + builder.setNote(noteBuild.build()); + builder.setTxid(ByteString.copyFrom(noteTx.getTxid().toByteArray())); + builder.setIndex(noteTx.getIndex()); + // builder.setVoucher(merkleVoucherInfo.getVouchers(0)); + + SpendResult result = blockingStubFull.isSpend(builder.build()); + return result; + } + return null; + } - /** - * constructor. - */ - public static void freedResource(byte[] fromAddress, String priKey, byte[] toAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - long balance = PublicMethed.queryAccount(fromAddress, blockingStubFull).getBalance(); - sendcoin(toAddress, balance - 500000, fromAddress, priKey, blockingStubFull); - } - - /** - * constructor. - */ - public static String parametersString(List parameters) { - String[] inputArr = new String[parameters.size()]; - int i = 0; - for (Object parameter : parameters) { - if (parameter instanceof List) { - StringBuilder sb = new StringBuilder(); - for (Object item : (List) parameter) { - if (sb.length() != 0) { - sb.append(","); - } - sb.append("\"").append(item).append("\""); - } - inputArr[i++] = "[" + sb.toString() + "]"; - } else { - inputArr[i++] = - (parameter instanceof String) ? ("\"" + parameter + "\"") : ("" + parameter); - } - } - String input = StringUtils.join(inputArr, ','); - return input; - } + /** constructor. */ + public static SpendResult getSpendResultOnSolidity( + ShieldAddressInfo shieldAddressInfo, + NoteTx noteTx, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); + OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); + outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); + outPointBuild.setIndex(noteTx.getIndex()); + request.addOutPoints(outPointBuild.build()); + Optional merkleVoucherInfo = + Optional.of(blockingStubSolidity.getMerkleTreeVoucherInfo(request.build())); + + if (merkleVoucherInfo.isPresent() && merkleVoucherInfo.get().getVouchersCount() > 0) { + NoteParameters.Builder builder = NoteParameters.newBuilder(); + try { + builder.setAk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getAk())); + builder.setNk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getNk())); + } catch (Exception e) { + Assert.assertTrue(1 == 1); + } + Note.Builder noteBuild = Note.newBuilder(); + noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); + noteBuild.setValue(noteTx.getNote().getValue()); + noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); + noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); + builder.setNote(noteBuild.build()); + builder.setTxid(ByteString.copyFrom(noteTx.getTxid().toByteArray())); + builder.setIndex(noteTx.getIndex()); + // builder.setVoucher(merkleVoucherInfo.getVouchers(0)); + + SpendResult result = blockingStubSolidity.isSpend(builder.build()); + return result; + } + return null; + } - /** - * constructor. - */ - public static String bytes32ToString(byte[] bytes) { - if (bytes == null) { - return "null"; - } - int imax = bytes.length - 1; - if (imax == -1) { - return ""; - } + /** constructor. */ + public static String getShieldNullifier( + ShieldAddressInfo shieldAddressInfo, + NoteTx noteTx, + WalletGrpc.WalletBlockingStub blockingStubFull) { + OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); + OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); + outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); + outPointBuild.setIndex(noteTx.getIndex()); + request.addOutPoints(outPointBuild.build()); + IncrementalMerkleVoucherInfo merkleVoucherInfo = + blockingStubFull.getMerkleTreeVoucherInfo(request.build()); + if (merkleVoucherInfo.getVouchersCount() < 1) { + System.out.println("get merkleVoucherInfo failure."); + return null; + } + Note.Builder noteBuild = Note.newBuilder(); + noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); + noteBuild.setValue(noteTx.getNote().getValue()); + noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); + noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); + + String shieldAddress = noteTx.getNote().getPaymentAddress(); + SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); + try { + // TODO + FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); + NfParameters.Builder builder = NfParameters.newBuilder(); + builder.setNote(noteBuild.build()); + builder.setVoucher(merkleVoucherInfo.getVouchers(0)); + builder.setAk(ByteString.copyFrom(fullViewingKey.getAk())); + builder.setNk(ByteString.copyFrom(fullViewingKey.getNk())); + + BytesMessage nullifier = blockingStubFull.createShieldNullifier(builder.build()); + return ByteArray.toHexString(nullifier.getValue().toByteArray()); + + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } - StringBuilder b = new StringBuilder(); - for (int i = 0; ; i++) { - b.append(bytes[i]); - if (i == imax) { - return b.toString(); - } - } + /** constructor. */ + public static String sendShieldCoinGetTxid( + byte[] publicZenTokenOwnerAddress, + long fromAmount, + ShieldAddressInfo shieldAddressInfo, + NoteTx noteTx, + List shieldOutputList, + byte[] publicZenTokenToAddress, + long toAmount, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + PrivateParameters.Builder builder = PrivateParameters.newBuilder(); + if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { + builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); + builder.setFromAmount(fromAmount); + } + if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { + builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); + builder.setToAmount(toAmount); + } + + if (shieldAddressInfo != null) { + OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); + + // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); + OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); + outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); + outPointBuild.setIndex(noteTx.getIndex()); + request.addOutPoints(outPointBuild.build()); + + // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); + + // String shieldAddress = noteInfo.getPaymentAddress(); + // ShieldAddressInfo addressInfo = + // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); + SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); + try { + ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); + builder.setAsk(ByteString.copyFrom(expandedSpendingKey.getAsk())); + builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); + builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); + } catch (Exception e) { + System.out.println(e); + } + + Note.Builder noteBuild = Note.newBuilder(); + noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); + noteBuild.setValue(noteTx.getNote().getValue()); + noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); + noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); + + // System.out.println("address " + noteInfo.getPaymentAddress()); + // System.out.println("value " + noteInfo.getValue()); + // System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); + // System.out.println("trxId " + noteInfo.getTrxId()); + // System.out.println("index " + noteInfo.getIndex()); + // System.out.println("meno " + new String(noteInfo.getMemo())); + + SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); + spendNoteBuilder.setNote(noteBuild.build()); + try { + spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); + } catch (Exception e) { + System.out.println(e); + } + + IncrementalMerkleVoucherInfo merkleVoucherInfo = + blockingStubFull.getMerkleTreeVoucherInfo(request.build()); + spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); + spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); + + builder.addShieldedSpends(spendNoteBuilder.build()); + + } else { + byte[] ovk = + ByteArray.fromHexString( + "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); + builder.setOvk(ByteString.copyFrom(ovk)); + } + + if (shieldOutputList.size() > 0) { + for (int i = 0; i < shieldOutputList.size(); ++i) { + builder.addShieldedReceives( + ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); + } + } + + TransactionExtention transactionExtention = + blockingStubFull.createShieldedTransaction(builder.build()); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; } + System.out.println( + "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); + Any any = transaction.getRawData().getContract(0).getParameter(); - /** - * constructor. - */ + try { + ShieldedTransferContract shieldedTransferContract = + any.unpack(ShieldedTransferContract.class); + if (shieldedTransferContract.getFromAmount() > 0) { + transaction = signTransactionForShield(ecKey, transaction); + System.out.println( + "trigger txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + } else { + System.out.println( + "trigger txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); + } + } catch (Exception e) { + System.out.println(e); + } + broadcastTransaction(transaction, blockingStubFull); + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); + } - public static Return transferAssetForReturn(byte[] to, byte[] assertName, long amount, - byte[] address, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - TransactionExtention transaction = blockingStubFull.transferAsset2(contract); - - if (transaction == null) { - return transaction.getResult(); - } - Return ret = transaction.getResult(); - return ret; + /** constructor. */ + public static byte[] decode58Check(String input) { + byte[] decodeCheck = org.tron.common.utils.Base58.decode(input); + if (decodeCheck.length <= 4) { + return null; + } + byte[] decodeData = new byte[decodeCheck.length - 4]; + System.arraycopy(decodeCheck, 0, decodeData, 0, decodeData.length); + byte[] hash0 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), decodeData); + byte[] hash1 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), hash0); + if (hash1[0] == decodeCheck[decodeData.length] + && hash1[1] == decodeCheck[decodeData.length + 1] + && hash1[2] == decodeCheck[decodeData.length + 2] + && hash1[3] == decodeCheck[decodeData.length + 3]) { + return decodeData; + } + return null; + } - } + /** constructor. */ + public static void freedResource( + byte[] fromAddress, + String priKey, + byte[] toAddress, + WalletGrpc.WalletBlockingStub blockingStubFull) { + long balance = PublicMethed.queryAccount(fromAddress, blockingStubFull).getBalance(); + sendcoin(toAddress, balance - 500000, fromAddress, priKey, blockingStubFull); + } + /** constructor. */ + public static String parametersString(List parameters) { + String[] inputArr = new String[parameters.size()]; + int i = 0; + for (Object parameter : parameters) { + if (parameter instanceof List) { + StringBuilder sb = new StringBuilder(); + for (Object item : (List) parameter) { + if (sb.length() != 0) { + sb.append(","); + } + sb.append("\"").append(item).append("\""); + } + inputArr[i++] = "[" + sb.toString() + "]"; + } else { + inputArr[i++] = + (parameter instanceof String) ? ("\"" + parameter + "\"") : ("" + parameter); + } + } + String input = StringUtils.join(inputArr, ','); + return input; + } - /** - * constructor. - */ + /** constructor. */ + public static String bytes32ToString(byte[] bytes) { + if (bytes == null) { + return "null"; + } + int imax = bytes.length - 1; + if (imax == -1) { + return ""; + } - public static Return sendcoinForReturn(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - TransactionExtention transaction = blockingStubFull.createTransaction2(contract); - if (transaction == null) { - return transaction.getResult(); - } - Return ret = transaction.getResult(); - return ret; + StringBuilder b = new StringBuilder(); + for (int i = 0; ; i++) { + b.append(bytes[i]); + if (i == imax) { + return b.toString(); + } } + } - /** - * constructor. - */ + /** constructor. */ + public static Return transferAssetForReturn( + byte[] to, + byte[] assertName, + long amount, + byte[] address, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsName = ByteString.copyFrom(assertName); + ByteString bsOwner = ByteString.copyFrom(address); + builder.setToAddress(bsTo); + builder.setAssetName(bsName); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferAssetContract contract = builder.build(); + TransactionExtention transaction = blockingStubFull.transferAsset2(contract); + + if (transaction == null) { + return transaction.getResult(); + } + Return ret = transaction.getResult(); + return ret; + } - public static Transaction sendcoinForTransaction(byte[] to, long amount, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + /** constructor. */ + public static Return sendcoinForReturn( + byte[] to, + long amount, + byte[] owner, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + // String priKey = testKey002; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + TransferContract.Builder builder = TransferContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsOwner = ByteString.copyFrom(owner); + builder.setToAddress(bsTo); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferContract contract = builder.build(); + TransactionExtention transaction = blockingStubFull.createTransaction2(contract); + if (transaction == null) { + return transaction.getResult(); + } + Return ret = transaction.getResult(); + return ret; + } + + /** constructor. */ + public static Transaction sendcoinForTransaction( + byte[] to, + long amount, + byte[] owner, + String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + // String priKey = testKey002; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + TransferContract.Builder builder = TransferContract.newBuilder(); + ByteString bsTo = ByteString.copyFrom(to); + ByteString bsOwner = ByteString.copyFrom(owner); + builder.setToAddress(bsTo); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + TransferContract contract = builder.build(); + TransactionExtention extention = blockingStubFull.createTransaction2(contract); + Protocol.Transaction transaction = extention.getTransaction(); + return transaction; + } - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); + /** constructor. */ + public static String marketSellAsset( + byte[] owner, + String priKey, + byte[] sellTokenId, + long sellTokenQuantity, + byte[] buyTokenId, + long buyTokenQuantity, + WalletGrpc.WalletBlockingStub blockingStubFull) { - TransferContract contract = builder.build(); - TransactionExtention extention = blockingStubFull.createTransaction2(contract); - Protocol.Transaction transaction = extention.getTransaction(); - return transaction; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + MarketContract.MarketSellAssetContract.Builder builder = + MarketContract.MarketSellAssetContract.newBuilder(); + builder + .setOwnerAddress(ByteString.copyFrom(owner)) + .setSellTokenId(ByteString.copyFrom(sellTokenId)) + .setSellTokenQuantity(sellTokenQuantity) + .setBuyTokenId(ByteString.copyFrom(buyTokenId)) + .setBuyTokenQuantity(buyTokenQuantity); + + TransactionExtention transactionExtention = blockingStubFull.marketSellAsset(builder.build()); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return null; + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; } - /** - * constructor. - */ - public static String marketSellAsset(byte[] owner, String priKey, byte[] sellTokenId, - long sellTokenQuantity, byte[] buyTokenId, long buyTokenQuantity, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - MarketContract.MarketSellAssetContract.Builder builder = MarketContract.MarketSellAssetContract - .newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setSellTokenQuantity(sellTokenQuantity) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .setBuyTokenQuantity(buyTokenQuantity); - - TransactionExtention transactionExtention = blockingStubFull.marketSellAsset(builder.build()); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } + if (transaction.getRawData().getContract(0).getType() + == ContractType.ShieldedTransferContract) { + return null; + } - if (transaction.getRawData().getContract(0).getType() - == ContractType.ShieldedTransferContract) { - return null; - } + transaction = signTransaction(ecKey, transaction); + broadcastTransaction(transaction, blockingStubFull); - transaction = signTransaction(ecKey, transaction); - broadcastTransaction(transaction, blockingStubFull); + String txid = + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); - String txid = ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + System.out.println("trigger txid = " + txid); + return txid; + } - System.out.println("trigger txid = " + txid); - return txid; + /** constructor. */ + public static Return marketSellAssetGetResposne( + byte[] owner, + String priKey, + byte[] sellTokenId, + long sellTokenQuantity, + byte[] buyTokenId, + long buyTokenQuantity, + WalletGrpc.WalletBlockingStub blockingStubFull) { + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); } + ECKey ecKey = temKey; - /** - * constructor. - */ - public static Return marketSellAssetGetResposne(byte[] owner, String priKey, byte[] sellTokenId, - long sellTokenQuantity, byte[] buyTokenId, long buyTokenQuantity, - WalletGrpc.WalletBlockingStub blockingStubFull) { + MarketContract.MarketSellAssetContract.Builder builder = + MarketContract.MarketSellAssetContract.newBuilder(); + builder + .setOwnerAddress(ByteString.copyFrom(owner)) + .setSellTokenId(ByteString.copyFrom(sellTokenId)) + .setSellTokenQuantity(sellTokenQuantity) + .setBuyTokenId(ByteString.copyFrom(buyTokenId)) + .setBuyTokenQuantity(buyTokenQuantity); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; + TransactionExtention transactionExtention = blockingStubFull.marketSellAsset(builder.build()); - MarketContract.MarketSellAssetContract.Builder builder = MarketContract.MarketSellAssetContract - .newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setSellTokenQuantity(sellTokenQuantity) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .setBuyTokenQuantity(buyTokenQuantity); - - TransactionExtention transactionExtention = blockingStubFull.marketSellAsset(builder.build()); + return transactionExtention.getResult(); + } - return transactionExtention.getResult(); + /** constructor. */ + public static String marketCancelOrder( + byte[] owner, String priKey, byte[] orderId, WalletGrpc.WalletBlockingStub blockingStubFull) { + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); } + final ECKey ecKey = temKey; - /** - * constructor. - */ - public static String marketCancelOrder(byte[] owner, String priKey, byte[] orderId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + MarketContract.MarketCancelOrderContract.Builder builder = + MarketContract.MarketCancelOrderContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; + TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); - MarketContract.MarketCancelOrderContract.Builder builder = MarketContract - .MarketCancelOrderContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); + if (transactionExtention == null) { + return null; + } + Return ret = transactionExtention.getResult(); + if (!ret.getResult()) { + System.out.println("Code = " + ret.getCode()); + System.out.println("Message = " + ret.getMessage().toStringUtf8()); + return ret.getMessage().toStringUtf8(); + } + Transaction transaction = transactionExtention.getTransaction(); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + System.out.println("Transaction is empty"); + return null; + } - TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); + if (transaction.getRawData().getContract(0).getType() + == ContractType.ShieldedTransferContract) { + return null; + } - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret.getMessage().toStringUtf8(); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } + transaction = signTransaction(ecKey, transaction); + broadcastTransaction(transaction, blockingStubFull); - if (transaction.getRawData().getContract(0).getType() - == ContractType.ShieldedTransferContract) { - return null; - } + String txid = + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); - transaction = signTransaction(ecKey, transaction); - broadcastTransaction(transaction, blockingStubFull); + System.out.println("trigger txid = " + txid); - String txid = ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + return txid; + } - System.out.println("trigger txid = " + txid); + /** constructor. */ + public static Return marketCancelOrderGetResposne( + byte[] owner, String priKey, byte[] orderId, WalletGrpc.WalletBlockingStub blockingStubFull) { - return txid; + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); } + ECKey ecKey = temKey; - /** - * constructor. - */ - - public static Return marketCancelOrderGetResposne(byte[] owner, String priKey, byte[] orderId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + MarketContract.MarketCancelOrderContract.Builder builder = + MarketContract.MarketCancelOrderContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; + TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); - MarketContract.MarketCancelOrderContract.Builder builder = MarketContract - .MarketCancelOrderContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); + if (transactionExtention == null) { + return null; + } + return transactionExtention.getResult(); + } - TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); + /** constructor. */ + public static Optional getMarketOrderByAccount( + byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { + ByteString addressBs = ByteString.copyFrom(address); + BytesMessage request = BytesMessage.newBuilder().setValue(addressBs).build(); - if (transactionExtention == null) { - return null; - } - return transactionExtention.getResult(); - } + Protocol.MarketOrderList marketOrderList; + marketOrderList = blockingStubFull.getMarketOrderByAccount(request); + return Optional.ofNullable(marketOrderList); + } - /** - * constructor. - */ - public static Optional getMarketOrderByAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - BytesMessage request = BytesMessage.newBuilder().setValue(addressBs).build(); - - Protocol.MarketOrderList marketOrderList; - marketOrderList = blockingStubFull.getMarketOrderByAccount(request); - return Optional.ofNullable(marketOrderList); - } - - /** - * constructor. - */ - public static Optional getMarketOrderByAccountSolidity(byte[] address, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - ByteString addressBs = ByteString.copyFrom(address); - BytesMessage request = BytesMessage.newBuilder().setValue(addressBs).build(); - - Protocol.MarketOrderList marketOrderList; - marketOrderList = blockingStubSolidity.getMarketOrderByAccount(request); - return Optional.ofNullable(marketOrderList); - } - - /** - * constructor. - */ - public static Optional getMarketOrderById(byte[] order, - WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString orderBytes = ByteString.copyFrom(order); - BytesMessage request = BytesMessage.newBuilder().setValue(orderBytes).build(); - Protocol.MarketOrder orderPair = blockingStubFull.getMarketOrderById(request); - return Optional.ofNullable(orderPair); - } - - /** - * constructor. - */ - public static Optional getMarketOrderByIdSolidity(byte[] order, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - ByteString orderBytes = ByteString.copyFrom(order); - BytesMessage request = BytesMessage.newBuilder().setValue(orderBytes).build(); - Protocol.MarketOrder orderPair = blockingStubSolidity.getMarketOrderById(request); - return Optional.ofNullable(orderPair); - } - - /** - * constructor. - */ - public static Optional getMarketPriceByPair(byte[] sellTokenId, - byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { - Protocol.MarketOrderPair request = - Protocol.MarketOrderPair.newBuilder() - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .build(); - - Protocol.MarketPriceList marketPriceList = blockingStubFull.getMarketPriceByPair(request); - return Optional.ofNullable(marketPriceList); - } - - /** - * constructor. - */ - public static Optional getMarketOrderListByPair(byte[] sellTokenId, - byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { - Protocol.MarketOrderPair request = - Protocol.MarketOrderPair.newBuilder() - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .build(); - - Protocol.MarketOrderList marketOrderList = blockingStubFull.getMarketOrderListByPair(request); - return Optional.ofNullable(marketOrderList); - } - - /** - * constructor. - */ - public static Optional getMarketOrderListByPairSolidity( - byte[] sellTokenId, - byte[] buyTokenId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Protocol.MarketOrderPair request = - Protocol.MarketOrderPair.newBuilder() - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .build(); - - Protocol.MarketOrderList marketOrderList = blockingStubSolidity - .getMarketOrderListByPair(request); - return Optional.ofNullable(marketOrderList); - } - - /** - * constructor. - */ - public static Optional getMarketPairList( - WalletGrpc.WalletBlockingStub blockingStubFull) { - Protocol.MarketOrderPairList marketOrderList = blockingStubFull - .getMarketPairList(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(marketOrderList); - } - - /** - * constructor. - */ - public static Optional getMarketPairListSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Protocol.MarketOrderPairList marketOrderList = blockingStubSolidity - .getMarketPairList(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(marketOrderList); - } - - /** - * constructor. - */ - public static String stringToHexString(String s) { - String str = ""; - for (int i = 0; i < s.length(); i++) { - int ch = s.charAt(i); - String s4 = Integer.toHexString(ch); - str = str + s4; - } - return str; - } + /** constructor. */ + public static Optional getMarketOrderByAccountSolidity( + byte[] address, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + ByteString addressBs = ByteString.copyFrom(address); + BytesMessage request = BytesMessage.newBuilder().setValue(addressBs).build(); - /** - * constructor. - */ - public static String hexStringToString(String s) { - if (s == null || s.equals("")) { - return null; - } - s = s.replace(" ", ""); - byte[] baKeyword = new byte[s.length() / 2]; - for (int i = 0; i < baKeyword.length; i++) { - try { - baKeyword[i] = (byte) (0xff & Integer.parseInt( - s.substring(i * 2, i * 2 + 2), 16)); - } catch (Exception e) { - e.printStackTrace(); - } - } - try { - s = new String(baKeyword, "gbk"); - new String(); - } catch (Exception e1) { - e1.printStackTrace(); - } - return s; - } - - /** - * constructor. - */ - public static String removeAll0sAtTheEndOfHexStr(String s) { - return s.replaceAll("(00)+$", ""); - } - - /** - * constructor. - */ - public static String replaceCode(String code, String address) { - if (code.indexOf("__$") == -1) { - return code; - } else { - int index = code.indexOf("_"); - String oldStr = code.substring(index - 1, index + 39); - Pattern p = Pattern.compile(oldStr); - Matcher m = p.matcher(code); - String result = m.replaceAll(address); - return result; - } - } + Protocol.MarketOrderList marketOrderList; + marketOrderList = blockingStubSolidity.getMarketOrderByAccount(request); + return Optional.ofNullable(marketOrderList); + } - /** - * constructor. - */ - public static Map getAllowance2(Long startNum, Long endNum, - WalletGrpc.WalletBlockingStub blockingStubFull) { - final String blackHole = Configuration.getByPath("testng.conf") - .getString("defaultParameter.blackHoleAddress"); - Long totalCount = 0L; - Map witnessBlockCount = new HashMap<>(); - Map witnessBrokerage = new HashMap<>(); - Map witnessVoteCount = new HashMap<>(); - Map witnessAllowance = new HashMap<>(); - List witnessList = PublicMethed.listWitnesses(blockingStubFull) - .get().getWitnessesList(); - for (Protocol.Witness witness : witnessList) { - witnessVoteCount.put(ByteArray.toHexString(witness.getAddress().toByteArray()), - witness.getVoteCount()); - GrpcAPI.BytesMessage bytesMessage = GrpcAPI.BytesMessage.newBuilder() - .setValue(witness.getAddress()).build(); - Long brokerager = blockingStubFull.getBrokerageInfo(bytesMessage).getNum(); - witnessBrokerage.put(ByteArray.toHexString(witness.getAddress().toByteArray()), brokerager); - totalCount += witness.getVoteCount(); - } - Optional infoById = null; - for (Long k = startNum; k < endNum; k++) { - String witnessAdd = ByteArray.toHexString(PublicMethed.getBlock(k, blockingStubFull) - .getBlockHeader().getRawData().getWitnessAddress().toByteArray()); - witnessBlockCount.put(witnessAdd, witnessBlockCount.getOrDefault(witnessAdd, 0) + 1); - List transList = PublicMethed.getBlock(k, - blockingStubFull).getTransactionsList(); - for (Transaction tem : transList) { - String txid = ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - tem.getRawData().toByteArray())); - logger.info("----ss txid:" + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long packingFee = infoById.get().getPackingFee(); - - witnessAllowance.put(witnessAdd, witnessAllowance.getOrDefault(witnessAdd, 0L) - + packingFee); - } - } + /** constructor. */ + public static Optional getMarketOrderById( + byte[] order, WalletGrpc.WalletBlockingStub blockingStubFull) { + ByteString orderBytes = ByteString.copyFrom(order); + BytesMessage request = BytesMessage.newBuilder().setValue(orderBytes).build(); + Protocol.MarketOrder orderPair = blockingStubFull.getMarketOrderById(request); + return Optional.ofNullable(orderPair); + } - logger.info("========totalCount:" + totalCount); - List chainParaList = - blockingStubFull.getChainParameters(EmptyMessage.newBuilder().build()) - .getChainParameterList(); - Long witness127PayPerBlock = 0L; - Long witnessPayPerBlock = 0L; - for (Protocol.ChainParameters.ChainParameter para : chainParaList) { - if ("getWitness127PayPerBlock".equals(para.getKey())) { - witness127PayPerBlock = para.getValue(); - } - if ("getWitnessPayPerBlock".equals(para.getKey())) { - witnessPayPerBlock = para.getValue(); - } - } - logger.info("witness127PayPerBlock:" + witness127PayPerBlock - + "\n witnessPayPerBlock:" + witnessPayPerBlock); + /** constructor. */ + public static Optional getMarketOrderByIdSolidity( + byte[] order, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + ByteString orderBytes = ByteString.copyFrom(order); + BytesMessage request = BytesMessage.newBuilder().setValue(orderBytes).build(); + Protocol.MarketOrder orderPair = blockingStubSolidity.getMarketOrderById(request); + return Optional.ofNullable(orderPair); + } - for (Map.Entry entry : witnessBrokerage.entrySet()) { - logger.info("-----witnessBrokerage " + entry.getKey() + " : " + entry.getValue()); - } - for (Map.Entry entry : witnessVoteCount.entrySet()) { - logger.info("-----witnessVoteCount " + entry.getKey() + " : " + entry.getValue()); - } - for (Map.Entry entry : witnessBlockCount.entrySet()) { - logger.info("-----witnessBlockCount " + entry.getKey() + " : " + entry.getValue()); - } + /** constructor. */ + public static Optional getMarketPriceByPair( + byte[] sellTokenId, byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { + Protocol.MarketOrderPair request = + Protocol.MarketOrderPair.newBuilder() + .setSellTokenId(ByteString.copyFrom(sellTokenId)) + .setBuyTokenId(ByteString.copyFrom(buyTokenId)) + .build(); + + Protocol.MarketPriceList marketPriceList = blockingStubFull.getMarketPriceByPair(request); + return Optional.ofNullable(marketPriceList); + } - for (Map.Entry entry : witnessVoteCount.entrySet()) { - String witnessAdd = entry.getKey(); - logger.info("----witnessAdd:" + witnessAdd + " block count:" - + witnessBlockCount.get(witnessAdd) - + " all: " + witnessAllowance.getOrDefault(witnessAdd, 0L)); - Long pay = (witnessBlockCount.get(witnessAdd) * witnessPayPerBlock - + (endNum - startNum) * witness127PayPerBlock * entry.getValue() / totalCount - + witnessAllowance.getOrDefault(witnessAdd, 0L)) - * witnessBrokerage.get(witnessAdd) / 100; - - witnessAllowance.put(witnessAdd, pay); - logger.info("****** " + witnessAdd + " : " + pay); - } - return witnessAllowance; - } + /** constructor. */ + public static Optional getMarketOrderListByPair( + byte[] sellTokenId, byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { + Protocol.MarketOrderPair request = + Protocol.MarketOrderPair.newBuilder() + .setSellTokenId(ByteString.copyFrom(sellTokenId)) + .setBuyTokenId(ByteString.copyFrom(buyTokenId)) + .build(); + + Protocol.MarketOrderList marketOrderList = blockingStubFull.getMarketOrderListByPair(request); + return Optional.ofNullable(marketOrderList); + } - public static String getContractStringMsg(byte[] contractMsgArray) { - int resultLenth = ByteArray.toInt(ByteArray.subArray(contractMsgArray, 32, 64)); - return ByteArray.toStr(ByteArray.subArray(contractMsgArray, 64, 64 + resultLenth)); - } + /** constructor. */ + public static Optional getMarketOrderListByPairSolidity( + byte[] sellTokenId, + byte[] buyTokenId, + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + Protocol.MarketOrderPair request = + Protocol.MarketOrderPair.newBuilder() + .setSellTokenId(ByteString.copyFrom(sellTokenId)) + .setBuyTokenId(ByteString.copyFrom(buyTokenId)) + .build(); + + Protocol.MarketOrderList marketOrderList = + blockingStubSolidity.getMarketOrderListByPair(request); + return Optional.ofNullable(marketOrderList); + } - /** - * constructor. - */ - public boolean updateBrokerage(byte[] owner, int brokerage, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** constructor. */ + public static Optional getMarketPairList( + WalletGrpc.WalletBlockingStub blockingStubFull) { + Protocol.MarketOrderPairList marketOrderList = + blockingStubFull.getMarketPairList(EmptyMessage.newBuilder().build()); + return Optional.ofNullable(marketOrderList); + } - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - UpdateBrokerageContract.Builder updateBrokerageContract = UpdateBrokerageContract.newBuilder(); - updateBrokerageContract.setOwnerAddress(ByteString.copyFrom(owner)).setBrokerage(brokerage); - TransactionExtention transactionExtention = blockingStubFull - .updateBrokerage(updateBrokerageContract.build()); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + /** constructor. */ + public static Optional getMarketPairListSolidity( + WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + Protocol.MarketOrderPairList marketOrderList = + blockingStubSolidity.getMarketPairList(EmptyMessage.newBuilder().build()); + return Optional.ofNullable(marketOrderList); + } - return response.getResult(); + /** constructor. */ + public static String stringToHexString(String s) { + String str = ""; + for (int i = 0; i < s.length(); i++) { + int ch = s.charAt(i); + String s4 = Integer.toHexString(ch); + str = str + s4; } + return str; + } - /** - * constructor. - */ - public static Long getAccountBalance(Protocol.Block block, byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - final Long blockNum = block.getBlockHeader().getRawData().getNumber(); - BlockId blockId = new BlockId( - org.tron.common.utils.Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - block.getBlockHeader().getRawData().toByteArray()), - block.getBlockHeader().getRawData().getNumber()); - + /** constructor. */ + public static String hexStringToString(String s) { + if (s == null || s.equals("")) { + return null; + } + s = s.replace(" ", ""); + byte[] baKeyword = new byte[s.length() / 2]; + for (int i = 0; i < baKeyword.length; i++) { + try { + baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16)); + } catch (Exception e) { + e.printStackTrace(); + } + } + try { + s = new String(baKeyword, "gbk"); + new String(); + } catch (Exception e1) { + e1.printStackTrace(); + } + return s; + } - BalanceContract.AccountIdentifier accountIdentifier = BalanceContract - .AccountIdentifier.newBuilder().setAddress(ByteString.copyFrom(address)).build(); - BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier - = BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() - .setHash(blockId.getByteString()).setNumber(blockNum).build(); + /** constructor. */ + public static String removeAll0sAtTheEndOfHexStr(String s) { + return s.replaceAll("(00)+$", ""); + } - BalanceContract.AccountBalanceRequest accountBalanceRequest - = BalanceContract.AccountBalanceRequest.newBuilder() - .setAccountIdentifier(accountIdentifier).setBlockIdentifier(blockIdentifier).build(); - return blockingStubFull.getAccountBalance(accountBalanceRequest).getBalance(); + /** constructor. */ + public static String replaceCode(String code, String address) { + if (code.indexOf("__$") == -1) { + return code; + } else { + int index = code.indexOf("_"); + String oldStr = code.substring(index - 1, index + 39); + Pattern p = Pattern.compile(oldStr); + Matcher m = p.matcher(code); + String result = m.replaceAll(address); + return result; } + } - /** - * constructor. - */ - public static BalanceContract.BlockBalanceTrace getBlockBalance(Protocol.Block block, - WalletGrpc.WalletBlockingStub blockingStubFull) { - final Long blockNum = block.getBlockHeader().getRawData().getNumber(); - BlockId blockId = new BlockId( - org.tron.common.utils.Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - block.getBlockHeader().getRawData().toByteArray()), - block.getBlockHeader().getRawData().getNumber()); - BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier - = BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() - .setHash(blockId.getByteString()).setNumber(blockNum).build(); - - return blockingStubFull.getBlockBalanceTrace(blockIdentifier); + /** constructor. */ + public static Map getAllowance2( + Long startNum, Long endNum, WalletGrpc.WalletBlockingStub blockingStubFull) { + final String blackHole = + Configuration.getByPath("testng.conf").getString("defaultParameter.blackHoleAddress"); + Long totalCount = 0L; + Map witnessBlockCount = new HashMap<>(); + Map witnessBrokerage = new HashMap<>(); + Map witnessVoteCount = new HashMap<>(); + Map witnessAllowance = new HashMap<>(); + List witnessList = + PublicMethed.listWitnesses(blockingStubFull).get().getWitnessesList(); + for (Protocol.Witness witness : witnessList) { + witnessVoteCount.put( + ByteArray.toHexString(witness.getAddress().toByteArray()), witness.getVoteCount()); + GrpcAPI.BytesMessage bytesMessage = + GrpcAPI.BytesMessage.newBuilder().setValue(witness.getAddress()).build(); + Long brokerager = blockingStubFull.getBrokerageInfo(bytesMessage).getNum(); + witnessBrokerage.put(ByteArray.toHexString(witness.getAddress().toByteArray()), brokerager); + totalCount += witness.getVoteCount(); + } + Optional infoById = null; + for (Long k = startNum; k < endNum; k++) { + String witnessAdd = + ByteArray.toHexString( + PublicMethed.getBlock(k, blockingStubFull) + .getBlockHeader() + .getRawData() + .getWitnessAddress() + .toByteArray()); + witnessBlockCount.put(witnessAdd, witnessBlockCount.getOrDefault(witnessAdd, 0) + 1); + List transList = + PublicMethed.getBlock(k, blockingStubFull).getTransactionsList(); + for (Transaction tem : transList) { + String txid = + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + tem.getRawData().toByteArray())); + logger.info("----ss txid:" + txid); + infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); + Long packingFee = infoById.get().getPackingFee(); + + witnessAllowance.put( + witnessAdd, witnessAllowance.getOrDefault(witnessAdd, 0L) + packingFee); + } + } + + logger.info("========totalCount:" + totalCount); + List chainParaList = + blockingStubFull + .getChainParameters(EmptyMessage.newBuilder().build()) + .getChainParameterList(); + Long witness127PayPerBlock = 0L; + Long witnessPayPerBlock = 0L; + for (Protocol.ChainParameters.ChainParameter para : chainParaList) { + if ("getWitness127PayPerBlock".equals(para.getKey())) { + witness127PayPerBlock = para.getValue(); + } + if ("getWitnessPayPerBlock".equals(para.getKey())) { + witnessPayPerBlock = para.getValue(); + } + } + logger.info( + "witness127PayPerBlock:" + + witness127PayPerBlock + + "\n witnessPayPerBlock:" + + witnessPayPerBlock); + + for (Map.Entry entry : witnessBrokerage.entrySet()) { + logger.info("-----witnessBrokerage " + entry.getKey() + " : " + entry.getValue()); + } + for (Map.Entry entry : witnessVoteCount.entrySet()) { + logger.info("-----witnessVoteCount " + entry.getKey() + " : " + entry.getValue()); + } + for (Map.Entry entry : witnessBlockCount.entrySet()) { + logger.info("-----witnessBlockCount " + entry.getKey() + " : " + entry.getValue()); + } + + for (Map.Entry entry : witnessVoteCount.entrySet()) { + String witnessAdd = entry.getKey(); + logger.info( + "----witnessAdd:" + + witnessAdd + + " block count:" + + witnessBlockCount.get(witnessAdd) + + " all: " + + witnessAllowance.getOrDefault(witnessAdd, 0L)); + Long pay = + (witnessBlockCount.get(witnessAdd) * witnessPayPerBlock + + (endNum - startNum) * witness127PayPerBlock * entry.getValue() / totalCount + + witnessAllowance.getOrDefault(witnessAdd, 0L)) + * witnessBrokerage.get(witnessAdd) + / 100; + + witnessAllowance.put(witnessAdd, pay); + logger.info("****** " + witnessAdd + " : " + pay); + } + return witnessAllowance; + } + public static String getContractStringMsg(byte[] contractMsgArray) { + int resultLenth = ByteArray.toInt(ByteArray.subArray(contractMsgArray, 32, 64)); + return ByteArray.toStr(ByteArray.subArray(contractMsgArray, 64, 64 + resultLenth)); + } + /** constructor. */ + public boolean updateBrokerage( + byte[] owner, int brokerage, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + ECKey ecKey = temKey; + + UpdateBrokerageContract.Builder updateBrokerageContract = UpdateBrokerageContract.newBuilder(); + updateBrokerageContract.setOwnerAddress(ByteString.copyFrom(owner)).setBrokerage(brokerage); + TransactionExtention transactionExtention = + blockingStubFull.updateBrokerage(updateBrokerageContract.build()); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + if (transactionExtention == null || !transactionExtention.getResult().getResult()) { + if (transactionExtention != null) { + System.out.println("Code = " + transactionExtention.getResult().getCode()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); + } + return false; } + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + + return response.getResult(); + } - /** - * 61 constructor. - */ + /** constructor. */ + public static Long getAccountBalance( + Protocol.Block block, byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { + final Long blockNum = block.getBlockHeader().getRawData().getNumber(); + BlockId blockId = + new BlockId( + org.tron.common.utils.Sha256Hash.of( + CommonParameter.getInstance().isECKeyCryptoEngine(), + block.getBlockHeader().getRawData().toByteArray()), + block.getBlockHeader().getRawData().getNumber()); + + BalanceContract.AccountIdentifier accountIdentifier = + BalanceContract.AccountIdentifier.newBuilder() + .setAddress(ByteString.copyFrom(address)) + .build(); + BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier = + BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() + .setHash(blockId.getByteString()) + .setNumber(blockNum) + .build(); + + BalanceContract.AccountBalanceRequest accountBalanceRequest = + BalanceContract.AccountBalanceRequest.newBuilder() + .setAccountIdentifier(accountIdentifier) + .setBlockIdentifier(blockIdentifier) + .build(); + return blockingStubFull.getAccountBalance(accountBalanceRequest).getBalance(); + } - public static Optional getTransactionFromPending(String txId, - WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction; - transaction = blockingStubFull.getTransactionFromPending(request); - return Optional.ofNullable(transaction); - } + /** constructor. */ + public static BalanceContract.BlockBalanceTrace getBlockBalance( + Protocol.Block block, WalletGrpc.WalletBlockingStub blockingStubFull) { + final Long blockNum = block.getBlockHeader().getRawData().getNumber(); + BlockId blockId = + new BlockId( + org.tron.common.utils.Sha256Hash.of( + CommonParameter.getInstance().isECKeyCryptoEngine(), + block.getBlockHeader().getRawData().toByteArray()), + block.getBlockHeader().getRawData().getNumber()); + BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier = + BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() + .setHash(blockId.getByteString()) + .setNumber(blockNum) + .build(); + + return blockingStubFull.getBlockBalanceTrace(blockIdentifier); + } + /** 61 constructor. */ + public static Optional getTransactionFromPending( + String txId, WalletGrpc.WalletBlockingStub blockingStubFull) { + ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); + BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); + Transaction transaction; + transaction = blockingStubFull.getTransactionFromPending(request); + return Optional.ofNullable(transaction); + } } diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java index c7b146a3b31..be300775e53 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java @@ -28,1222 +28,1218 @@ @Slf4j public class Accounts002 extends JsonRpcBase { - private JSONObject responseContent; - private HttpResponse response; - String realGasPrice; - String bid = null; - int indexNum = 0; - String indexHex = null; - JSONObject result = null; - String transacionHash = null; - String blockHash = null; - String blockNumHex = null; - String parentHash = null; - String txTrieRoot = null; - String witnessAddress = null; - String feeLimit = null; - String accountStateRoot = null; - String energyUsed = "0x135c6"; - - List transactionIdList = null; - long size = 0; - long gas = 0; - long blockTimeStamp = 0; - long gasPriceFromHttp = 0; - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); + private JSONObject responseContent; + private HttpResponse response; + String realGasPrice; + String bid = null; + int indexNum = 0; + String indexHex = null; + JSONObject result = null; + String transacionHash = null; + String blockHash = null; + String blockNumHex = null; + String parentHash = null; + String txTrieRoot = null; + String witnessAddress = null; + String feeLimit = null; + String accountStateRoot = null; + String energyUsed = "0x135c6"; + + List transactionIdList = null; + long size = 0; + long gas = 0; + long blockTimeStamp = 0; + long gasPriceFromHttp = 0; + + /** constructor. */ + @BeforeClass(enabled = true) + public void beforeClass() { + channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); + blockingStubFull = WalletGrpc.newBlockingStub(channelFull); + } + + @Test(enabled = true, description = "Json rpc api of eth_accounts") + public void test01JsonRpcApiTestForEthAccounts() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_accounts", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + List result = new ArrayList(); + logger.info(String.valueOf(result)); + Assert.assertEquals(responseContent.get("result"), result); + } + + @Test(enabled = true, description = "Json rpc api of eth_blockNumber") + public void test02JsonRpcApiTestForEthBlockNumber() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_blockNumber", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + responseContent.get("result"); + String blockNum = responseContent.getString("result").substring(2); + long blockNumFromjsonRpcNodeForSolidity = Long.parseLong(blockNum, 16); + response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + long blockNumFromHttp = + responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); + logger.info("blocknumFromjsonRpcNodeForSolidity:" + blockNumFromjsonRpcNodeForSolidity); + logger.info("blocknumFromHttp:" + blockNumFromHttp); + Assert.assertTrue(Math.abs(blockNumFromjsonRpcNodeForSolidity - blockNumFromHttp) <= 3); + } + + @Test(enabled = true, description = "Json rpc api of eth_call") + public void test03JsonRpcApiTestForEthCall() throws Exception { + JsonObject param = new JsonObject(); + HttpMethed.waitToProduceOneBlock(httpFullNode); + param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); + param.addProperty("to", trc20AddressHex); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x0"); + param.addProperty("data", "0x06fdde03"); + JsonArray params = new JsonArray(); + params.add(param); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_call", params); + logger.info("03params:" + params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + Assert.assertEquals( + "0x000000000000000000000000000000000000000000000000000" + + "00000000000200000000000000000000000000000000000000000" + + "00000000000000000000000a546f6b656e5452433230000000000" + + "00000000000000000000000000000000000", + dataResult); + } + + @Test(enabled = true, description = "Json rpc api of eth_chainId") + public void test04JsonRpcApiTestForEthChainId() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_chainId", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + responseContent.get("result"); + String blockIdFromjsonRpcNodeForSolidity = + responseContent.get("result").toString().substring(2); + response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, 0); + responseContent = HttpMethed.parseResponseContent(response); + String blockIdFromHttp = responseContent.getString("blockID").substring(56); + logger.info("blockIdFromjsonRpcNodeForSolidity:" + blockIdFromjsonRpcNodeForSolidity); + logger.info("blockIdFromHttp:" + blockIdFromHttp); + Assert.assertEquals(blockIdFromjsonRpcNodeForSolidity, blockIdFromHttp); + } + + @Test(enabled = true, description = "Json rpc api of eth_coinbase") + public void test05JsonRpcApiTestForEthCoinbase() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_coinbase", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + + Assert.assertEquals( + "0x410be88a918d74d0dfd71dc84bd4abf036d0562991", responseContent.getString("result")); + } + + @Test(enabled = true, description = "Json rpc api of eth_estimateGas") + public void test06JsonRpcApiTestForEthEstimateGas() throws Exception { + JsonObject param = new JsonObject(); + param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); + param.addProperty("to", trc20AddressHex); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x0"); + param.addProperty("data", "0x1249c58b"); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("test06requestBody:" + requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + Assert.assertEquals("0x147", dataResult); + } + + @Test(enabled = true, description = "Json rpc api of eth_estimateGasHasPayable") + public void test07JsonRpcApiTestForEthEstimateGasHasPayable() throws Exception { + response = HttpMethed.getTransactionInfoByIdFromSolidity(httpsolidityNode, txid); + responseContent = HttpMethed.parseResponseContent(response); + Long realEnergyUsed = responseContent.getJSONObject("receipt").getLong("energy_usage_total"); + logger.info("realEnergyUsed:" + realEnergyUsed); + JsonObject param = new JsonObject(); + param.addProperty("from", "0x" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2)); + param.addProperty("to", "0x" + contractAddressFrom58); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x1389"); + param.addProperty("data", data); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("test07requestBody:" + requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + Assert.assertEquals((long) realEnergyUsed, Long.parseLong(dataResult.substring(2), 16)); + } + + @Test(enabled = true, description = "Json rpc api of eth_estimateGasWithoutTo") + public void test08JsonRpcApiTestForEthEstimateGasWithoutTo() throws Exception { + JsonObject param = new JsonObject(); + param.addProperty("from", "0x6C0214C9995C6F3A61AB23F0EB84B0CDE7FD9C7C"); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x0"); + param.addProperty( + "data", + "0x6080604052d3600055d2600155346002556101418061001f6000396000f30060806040" + + "52600436106100565763ffffffff7c010000000000000000000000000000000000000000" + + "000000000000000060003504166305c24200811461005b5780633be9ece7146100815780" + + "6371dc08ce146100aa575b600080fd5b6100636100b2565b6040805193845260208401929" + + "0925282820152519081900360600190f35b6100a873ffffffffffffffffffffffffffffff" + + "ffffffffff600435166024356044356100c0565b005b61006361010d565b60005460015460" + + "0254909192565b60405173ffffffffffffffffffffffffffffffffffffffff841690821561" + + "08fc029083908590600081818185878a8ad0945050505050158015610107573d6000803e3d" + + "6000fd5b50505050565bd3d2349091925600a165627a7a72305820a2fb39541e90eda9a2f5" + + "f9e7905ef98e66e60dd4b38e00b05de418da3154e757002900000000000000000000000000" + + "00000000000000000000000000000090fa17bb"); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("test08requestBody:" + requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + logger.info("dataResult:" + dataResult); + Assert.assertEquals(energyUsed, dataResult); + } + + @Test(enabled = true, description = "Json rpc api of eth_estimateGasSendTrx") + public void test09JsonRpcApiTestForEthEstimateGasSendTrx() throws Exception { + JsonObject param = new JsonObject(); + param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); + param.addProperty("to", "0xC1A74CD01732542093F5A87910A398AD70F04BD7"); + param.addProperty("gas", "0x0"); + param.addProperty("gasPrice", "0x0"); + param.addProperty("value", "0x1"); + param.addProperty("data", "0x0"); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("test09requestBody:" + requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String dataResult = responseContent.getString("result"); + Assert.assertEquals("0x0", dataResult); + } + + @Test(enabled = true, description = "Json rpc api of eth_gasPrice") + public void test10JsonRpcApiTestForEthGasPrice() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_gasPrice", params); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + responseContent.get("result"); + String gasPrice = responseContent.get("result").toString().substring(2); + long gasPriceFromJsonrpc = Long.parseLong(gasPrice, 16); + logger.info(String.valueOf(gasPriceFromJsonrpc)); + response = HttpMethed.getChainParameters(httpFullNode); + responseContent = HttpMethed.parseResponseContent(response); + JSONArray temp; + temp = responseContent.getJSONArray("chainParameter"); + for (int i = 0; i < temp.size(); i++) { + if (temp.getJSONObject(i).get("key").equals("getEnergyFee")) { + gasPriceFromHttp = temp.getJSONObject(i).getLong("value"); + } } - - @Test(enabled = true, description = "Json rpc api of eth_accounts") - public void test01JsonRpcApiTestForEthAccounts() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_accounts", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - List result = new ArrayList(); - logger.info(String.valueOf(result)); - Assert.assertEquals(responseContent.get("result"), result); - } - - @Test(enabled = true, description = "Json rpc api of eth_blockNumber") - public void test02JsonRpcApiTestForEthBlockNumber() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_blockNumber", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String blockNum = responseContent.getString("result").substring(2); - long blockNumFromjsonRpcNodeForSolidity = Long.parseLong(blockNum, 16); - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - long blockNumFromHttp = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - logger.info("blocknumFromjsonRpcNodeForSolidity:" + blockNumFromjsonRpcNodeForSolidity); - logger.info("blocknumFromHttp:" + blockNumFromHttp); - Assert.assertTrue(Math.abs(blockNumFromjsonRpcNodeForSolidity - blockNumFromHttp) <= 3); - } - - @Test(enabled = true, description = "Json rpc api of eth_call") - public void test03JsonRpcApiTestForEthCall() throws Exception { - JsonObject param = new JsonObject(); - HttpMethed.waitToProduceOneBlock(httpFullNode); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x06fdde03"); - JsonArray params = new JsonArray(); - params.add(param); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_call", params); - logger.info("03params:" + params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals( - "0x000000000000000000000000000000000000000000000000000" - + "00000000000200000000000000000000000000000000000000000" - + "00000000000000000000000a546f6b656e5452433230000000000" - + "00000000000000000000000000000000000", - dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_chainId") - public void test04JsonRpcApiTestForEthChainId() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_chainId", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String blockIdFromjsonRpcNodeForSolidity = - responseContent.get("result").toString().substring(2); - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - String blockIdFromHttp = responseContent.getString("blockID").substring(56); - logger.info("blockIdFromjsonRpcNodeForSolidity:" + blockIdFromjsonRpcNodeForSolidity); - logger.info("blockIdFromHttp:" + blockIdFromHttp); - Assert.assertEquals(blockIdFromjsonRpcNodeForSolidity, blockIdFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_coinbase") - public void test05JsonRpcApiTestForEthCoinbase() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_coinbase", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - - Assert.assertEquals( - "0x410be88a918d74d0dfd71dc84bd4abf036d0562991", responseContent.getString("result")); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGas") - public void test06JsonRpcApiTestForEthEstimateGas() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x1249c58b"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test06requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals("0x147", dataResult); + logger.info("gasPriceFromHttp:" + gasPriceFromHttp); + Assert.assertEquals(gasPriceFromJsonrpc, gasPriceFromHttp); + } + + @Test(enabled = true, description = "Json rpc api of eth_getBalance") + public void test11JsonRpcApiTestForEthGetBalance() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x" + ByteArray.toHexString(foundationAccountAddress).substring(2)); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getBalance", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String balance = responseContent.getString("result").substring(2); + Long balance1 = Long.parseLong(balance, 16); + logger.info("balance1:" + balance1); + response = HttpMethed.getAccountFromSolidity(httpsolidityNode, foundationAccountAddress); + responseContent = HttpMethed.parseResponseContent(response); + Long balance2 = responseContent.getLong("balance"); + logger.info(balance1.toString()); + logger.info(balance2.toString()); + Assert.assertEquals(balance1, balance2); + } + + @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") + public void test12JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { + response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + JsonArray params = new JsonArray(); + params.add("earliest"); + JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String transactionNum = responseContent.getString("result").substring(2); + int transactionNum1 = Integer.parseInt(transactionNum, 16); + logger.info(String.valueOf(transactionNum1)); + response = HttpMethed.getTransactionCountByBlocknumFromSolidity(httpsolidityNode, 0); + responseContent = HttpMethed.parseResponseContent(response); + int transactionNum2 = responseContent.getInteger("count"); + logger.info(String.valueOf(transactionNum2)); + Assert.assertEquals(transactionNum1, transactionNum2); + } + + @Test(enabled = true, description = "Json rpc api of eth_getCode") + public void test13JsonRpcApiTestForEthGetCode() throws Exception { + + JsonArray params = new JsonArray(); + params.add(contractAddressFrom58); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getCode", params); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String codeFromJsonRpc = responseContent.getString("result").substring(2); + logger.info(codeFromJsonRpc); + response = HttpMethed.getContractInfo(httpFullNode, contractAddressFrom58); + logger.info("13contractAddressFrom58:" + contractAddressFrom58); + responseContent = HttpMethed.parseResponseContent(response); + String codeFromHttp = responseContent.getString("runtimecode"); + logger.info(codeFromHttp); + Assert.assertEquals(codeFromJsonRpc, codeFromHttp); + } + + @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") + public void test14JsonRpcApiTestForEthGetStorageAt01() throws Exception { + + JsonArray params = new JsonArray(); + params.add(contractAddressFrom58); + params.add("0x0"); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("14responseContent:" + responseContent); + String result = responseContent.getString("result").substring(2); + long resultExpect = Long.parseLong(result, 16); + logger.info("result:" + resultExpect); + Assert.assertEquals("1234", String.valueOf(resultExpect)); + } + + @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") + public void test15JsonRpcApiTestForEthGetStorageAt02() throws Exception { + + String address = + "000000000000000000000000" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2); + String str = address + "0000000000000000000000000000000000000000000000000000000000000001"; + logger.info("str:" + str); + JsonArray paramsForSha3 = new JsonArray(); + paramsForSha3.add(str); + JsonObject requestBodyForSha3 = getJsonRpcBody("web3_sha3", paramsForSha3); + logger.info("requestBodyForSha3:" + requestBodyForSha3); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForSha3); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + String resultForSha3 = responseContent.getString("result"); + logger.info("resultForSha3:" + resultForSha3); + JsonArray params = new JsonArray(); + params.add(contractAddressFrom58); + params.add(resultForSha3); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("15responseContent:" + responseContent); + String result = responseContent.getString("result").substring(2); + logger.info("15result:" + result); + logger.info("mapResult:" + Integer.parseInt(result, 16)); + Assert.assertEquals("5678", String.valueOf(Integer.parseInt(result, 16))); + } + + @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockNumberAndIndex") + public void test16JsonRpcApiTestForEthGetTransactionByBlockNumberAndIndex() throws Exception { + logger.info("16blockNum:" + blockNum); + blockNumHex = "0x" + Integer.toHexString(blockNum); + logger.info("blockNumHex:" + blockNumHex); + JsonArray params = new JsonArray(); + params.add(blockNumHex); + indexNum = 0; + response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNum); + responseContent = HttpMethed.parseResponseContent(response); + parentHash = + responseContent + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getString("parentHash"); + txTrieRoot = + responseContent + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getString("txTrieRoot"); + witnessAddress = + responseContent + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getString("witness_address"); + feeLimit = + responseContent + .getJSONArray("transactions") + .getJSONObject(0) + .getJSONObject("raw_data") + .getString("fee_limit"); + logger.info(feeLimit); + + JSONObject getBlockByNumFromSolidityResult = null; + for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { + if (txid.equals( + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { + indexNum = i; + getBlockByNumFromSolidityResult = + responseContent.getJSONArray("transactions").getJSONObject(i); + bid = responseContent.getString("blockID"); + break; + } } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasHasPayable") - public void test07JsonRpcApiTestForEthEstimateGasHasPayable() throws Exception { - response = HttpMethed.getTransactionInfoByIdFromSolidity(httpsolidityNode, txid); - responseContent = HttpMethed.parseResponseContent(response); - Long realEnergyUsed = responseContent.getJSONObject("receipt").getLong("energy_usage_total"); - logger.info("realEnergyUsed:" + realEnergyUsed); - JsonObject param = new JsonObject(); - param.addProperty("from", "0x" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2)); - param.addProperty("to", "0x" + contractAddressFrom58); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x1389"); - param.addProperty("data", data); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test07requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals((long) realEnergyUsed, Long.parseLong(dataResult.substring(2), 16)); + transactionIdList = new ArrayList<>(); + if (responseContent.getJSONArray("transactions").size() > 0) { + for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { + transactionIdList.add( + "0x" + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID")); + } } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasWithoutTo") - public void test08JsonRpcApiTestForEthEstimateGasWithoutTo() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", "0x6C0214C9995C6F3A61AB23F0EB84B0CDE7FD9C7C"); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty( - "data", - "0x6080604052d3600055d2600155346002556101418061001f6000396000f30060806040" - + "52600436106100565763ffffffff7c010000000000000000000000000000000000000000" - + "000000000000000060003504166305c24200811461005b5780633be9ece7146100815780" - + "6371dc08ce146100aa575b600080fd5b6100636100b2565b6040805193845260208401929" - + "0925282820152519081900360600190f35b6100a873ffffffffffffffffffffffffffffff" - + "ffffffffff600435166024356044356100c0565b005b61006361010d565b60005460015460" - + "0254909192565b60405173ffffffffffffffffffffffffffffffffffffffff841690821561" - + "08fc029083908590600081818185878a8ad0945050505050158015610107573d6000803e3d" - + "6000fd5b50505050565bd3d2349091925600a165627a7a72305820a2fb39541e90eda9a2f5" - + "f9e7905ef98e66e60dd4b38e00b05de418da3154e757002900000000000000000000000000" - + "00000000000000000000000000000090fa17bb"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test08requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - logger.info("dataResult:" + dataResult); - Assert.assertEquals(energyUsed, dataResult); + logger.info("16transactionIdList:" + transactionIdList); + logger.info(String.valueOf(indexNum)); + indexHex = "0x" + Integer.toHexString(indexNum); + logger.info("indexHex:" + indexHex); + params.add(indexHex); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockNumberAndIndex", params); + logger.info("13requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + result = responseContent.getJSONObject("result"); + logger.info("16 result" + result); + Map jsonrpcResult = new HashMap(); + for (Map.Entry entry : result.entrySet()) { + jsonrpcResult.put(entry.getKey(), entry.getValue()); } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasSendTrx") - public void test09JsonRpcApiTestForEthEstimateGasSendTrx() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", "0xC1A74CD01732542093F5A87910A398AD70F04BD7"); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x1"); - param.addProperty("data", "0x0"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test09requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals("0x0", dataResult); + transacionHash = jsonrpcResult.get("hash").toString(); + logger.info("transactionHash:" + transacionHash); + blockHash = jsonrpcResult.get("blockHash").toString(); + logger.info("jsonrpcResult:" + jsonrpcResult); + response = HttpMethed.getTransactionInfoByBlocknumFromSolidity(httpsolidityNode, blockNum); + logger.info("response:" + response); + List responseContent1 = HttpMethed.parseResponseContentArray(response); + logger.info("responseContent1:" + responseContent1); + blockTimeStamp = responseContent1.get(0).getLong("blockTimeStamp"); + + for (int i = 0; i < responseContent1.size(); i++) { + if (responseContent1.get(i).getString("id").equals(transactionIdList.get(0).substring(2))) { + gas = responseContent1.get(i).getJSONObject("receipt").getLong("energy_usage_total"); + logger.info("gas:" + gas); + break; + } } - @Test(enabled = true, description = "Json rpc api of eth_gasPrice") - public void test10JsonRpcApiTestForEthGasPrice() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_gasPrice", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String gasPrice = responseContent.get("result").toString().substring(2); - long gasPriceFromJsonrpc = Long.parseLong(gasPrice, 16); - logger.info(String.valueOf(gasPriceFromJsonrpc)); - response = HttpMethed.getChainParameters(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - JSONArray temp; - temp = responseContent.getJSONArray("chainParameter"); - for (int i = 0; i < temp.size(); i++) { - if (temp.getJSONObject(i).get("key").equals("getEnergyFee")) { - gasPriceFromHttp = temp.getJSONObject(i).getLong("value"); - } - } - logger.info("gasPriceFromHttp:" + gasPriceFromHttp); - Assert.assertEquals(gasPriceFromJsonrpc, gasPriceFromHttp); + Assert.assertEquals(jsonrpcResult.get("gas").toString(), "0x" + Long.toHexString(gas)); + Assert.assertNull(jsonrpcResult.get("nonce")); + Assert.assertEquals( + jsonrpcResult.get("hash").toString(), + "0x" + getBlockByNumFromSolidityResult.getString("txID")); + Assert.assertEquals(jsonrpcResult.get("blockHash").toString(), "0x" + bid); + Assert.assertEquals(jsonrpcResult.get("blockNumber").toString(), blockNumHex); + Assert.assertEquals(jsonrpcResult.get("transactionIndex").toString(), indexHex); + Assert.assertEquals( + jsonrpcResult.get("from").toString(), + "0x" + + getBlockByNumFromSolidityResult + .getJSONObject("raw_data") + .getJSONArray("contract") + .getJSONObject(0) + .getJSONObject("parameter") + .getJSONObject("value") + .getString("owner_address") + .substring(2)); + Assert.assertEquals( + jsonrpcResult.get("to").toString(), + "0x" + + getBlockByNumFromSolidityResult + .getJSONObject("raw_data") + .getJSONArray("contract") + .getJSONObject(0) + .getJSONObject("parameter") + .getJSONObject("value") + .getString("contract_address") + .substring(2)); + + Assert.assertEquals(jsonrpcResult.get("value").toString(), "0x1389"); + String data; + if (getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data") == null) { + data = "0x"; + } else { + data = + getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data").substring(2); } - - @Test(enabled = true, description = "Json rpc api of eth_getBalance") - public void test11JsonRpcApiTestForEthGetBalance() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x" + ByteArray.toHexString(foundationAccountAddress).substring(2)); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getBalance", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String balance = responseContent.getString("result").substring(2); - Long balance1 = Long.parseLong(balance, 16); - logger.info("balance1:" + balance1); - response = HttpMethed.getAccountFromSolidity(httpsolidityNode, foundationAccountAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long balance2 = responseContent.getLong("balance"); - logger.info(balance1.toString()); - logger.info(balance2.toString()); - Assert.assertEquals(balance1, balance2); + Assert.assertEquals(jsonrpcResult.get("input").toString(), data); + + long temp = + Long.parseLong( + getBlockByNumFromSolidityResult.getString("signature").substring(130, 131), 16); + long v = + Long.parseLong( + getBlockByNumFromSolidityResult.getString("signature").substring(130, 132), 16); + if (temp < 27) { + v += 27; } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") - public void test12JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - JsonArray params = new JsonArray(); - params.add("earliest"); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNum1 = Integer.parseInt(transactionNum, 16); - logger.info(String.valueOf(transactionNum1)); - response = HttpMethed.getTransactionCountByBlocknumFromSolidity(httpsolidityNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNum2 = responseContent.getInteger("count"); - logger.info(String.valueOf(transactionNum2)); - Assert.assertEquals(transactionNum1, transactionNum2); + Assert.assertEquals(Long.parseLong(jsonrpcResult.get("v").toString().substring(2), 16), v); + Assert.assertEquals( + jsonrpcResult.get("r").toString().substring(2), + getBlockByNumFromSolidityResult.getString("signature").substring(2, 66)); + Assert.assertEquals( + jsonrpcResult.get("s").toString().substring(2), + getBlockByNumFromSolidityResult.getString("signature").substring(66, 130)); + } + + @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByHash") + public void test17JsonRpcApiTestForEthGetBlockTransactionCountByHash() throws Exception { + logger.info("blockNum:" + blockNum); + JsonArray params = new JsonArray(); + params.add(blockHash); + logger.info("blockHash:" + blockHash); + JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByHash", params); + logger.info("requestBody:" + requestBody); + HttpMethed.waitToProduceOneBlock(httpFullNode); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + String transactionNum = responseContent.getString("result").substring(2); + int transactionNumFromjsonRpcNodeForSolidity = Integer.parseInt(transactionNum, 16); + logger.info( + "transactionNumFromjsonRpcNodeForSolidity:" + transactionNumFromjsonRpcNodeForSolidity); + response = HttpMethed.getTransactionCountByBlocknumFromSolidity(httpsolidityNode, blockNum); + responseContent = HttpMethed.parseResponseContent(response); + int transactionNumFromHttp = responseContent.getInteger("count"); + logger.info("transactionNumFromHttp:" + transactionNumFromHttp); + Assert.assertEquals(transactionNumFromHttp, transactionNumFromjsonRpcNodeForSolidity); + } + + @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") + public void test18JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { + JsonArray params = new JsonArray(); + params.add(blockNum); + logger.info(String.valueOf(blockNum)); + JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("response:" + response); + HttpMethed.waitToProduceOneBlock(httpFullNode); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + String transactionNum = responseContent.getString("result").substring(2); + int transactionNum1 = Integer.parseInt(transactionNum, 16); + logger.info(String.valueOf(transactionNum1)); + response = HttpMethed.getTransactionCountByBlocknumFromSolidity(httpsolidityNode, blockNum); + responseContent = HttpMethed.parseResponseContent(response); + int transactionNum2 = responseContent.getInteger("count"); + logger.info(String.valueOf(transactionNum2)); + Assert.assertEquals(transactionNum1, transactionNum2); + } + + @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockHashAndIndex") + public void test19JsonRpcApiTestForEthGetTransactionByBlockHashAndIndex() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x" + bid); + params.add(indexHex); + logger.info("indexHex:" + indexHex); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockHashAndIndex", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject resultForGetTransactionByBlockHashAndIndex = responseContent.getJSONObject("result"); + Assert.assertEquals(result, resultForGetTransactionByBlockHashAndIndex); + } + + @Test(enabled = true, description = "Json rpc api of eth_getTransactionByHash") + public void test20JsonRpcApiTestForEthGetTransactionByHash() throws Exception { + JsonArray params = new JsonArray(); + params.add(transacionHash); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionByHash", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject result1 = responseContent.getJSONObject("result"); + Assert.assertEquals(result, result1); + } + + @Test(enabled = true, description = "Json rpc api of eth_getTransactionReceipt") + public void test21JsonRpcApiTestForEthGetTransactionReceipt() throws Exception { + JsonArray params = new JsonArray(); + Thread.sleep(6000); + params.add(trc20Txid); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionReceipt", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + logger.info("response:" + response); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject resultFromTransactionReceipt = responseContent.getJSONObject("result"); + logger.info("resultFromTransactionReceipt:" + resultFromTransactionReceipt); + JSONArray logs = resultFromTransactionReceipt.getJSONArray("logs"); + logger.info("logs:" + logs); + logger.info("result:" + resultFromTransactionReceipt.toString()); + response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNumForTrc20); + responseContent = HttpMethed.parseResponseContent(response); + int index = 0; + for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { + if (trc20Txid.equals( + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { + index = i; + break; + } } - @Test(enabled = true, description = "Json rpc api of eth_getCode") - public void test13JsonRpcApiTestForEthGetCode() throws Exception { - - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getCode", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String codeFromJsonRpc = responseContent.getString("result").substring(2); - logger.info(codeFromJsonRpc); - response = HttpMethed.getContractInfo(httpFullNode, contractAddressFrom58); - logger.info("13contractAddressFrom58:" + contractAddressFrom58); - responseContent = HttpMethed.parseResponseContent(response); - String codeFromHttp = responseContent.getString("runtimecode"); - logger.info(codeFromHttp); - Assert.assertEquals(codeFromJsonRpc, codeFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") - public void test14JsonRpcApiTestForEthGetStorageAt01() throws Exception { - - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add("0x0"); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("14responseContent:" + responseContent); - String result = responseContent.getString("result").substring(2); - long resultExpect = Long.parseLong(result, 16); - logger.info("result:" + resultExpect); - Assert.assertEquals("1234", String.valueOf(resultExpect)); - } - - @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") - public void test15JsonRpcApiTestForEthGetStorageAt02() throws Exception { - - String address = - "000000000000000000000000" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2); - String str = address + "0000000000000000000000000000000000000000000000000000000000000001"; - logger.info("str:" + str); - JsonArray paramsForSha3 = new JsonArray(); - paramsForSha3.add(str); - JsonObject requestBodyForSha3 = getJsonRpcBody("web3_sha3", paramsForSha3); - logger.info("requestBodyForSha3:" + requestBodyForSha3); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForSha3); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String resultForSha3 = responseContent.getString("result"); - logger.info("resultForSha3:" + resultForSha3); - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add(resultForSha3); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("15responseContent:" + responseContent); - String result = responseContent.getString("result").substring(2); - logger.info("15result:" + result); - logger.info("mapResult:" + Integer.parseInt(result, 16)); - Assert.assertEquals("5678", String.valueOf(Integer.parseInt(result, 16))); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockNumberAndIndex") - public void test16JsonRpcApiTestForEthGetTransactionByBlockNumberAndIndex() throws Exception { - logger.info("16blockNum:" + blockNum); - blockNumHex = "0x" + Integer.toHexString(blockNum); - logger.info("blockNumHex:" + blockNumHex); - JsonArray params = new JsonArray(); - params.add(blockNumHex); - indexNum = 0; - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - parentHash = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("parentHash"); - txTrieRoot = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("txTrieRoot"); - witnessAddress = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("witness_address"); - feeLimit = - responseContent - .getJSONArray("transactions") - .getJSONObject(0) - .getJSONObject("raw_data") - .getString("fee_limit"); - logger.info(feeLimit); - - JSONObject getBlockByNumFromSolidityResult = null; - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - if (txid.equals( - responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { - indexNum = i; - getBlockByNumFromSolidityResult = - responseContent.getJSONArray("transactions").getJSONObject(i); - bid = responseContent.getString("blockID"); - break; - } - } - transactionIdList = new ArrayList<>(); - if (responseContent.getJSONArray("transactions").size() > 0) { - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - transactionIdList.add( - "0x" + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID")); - } - } - logger.info("16transactionIdList:" + transactionIdList); - logger.info(String.valueOf(indexNum)); - indexHex = "0x" + Integer.toHexString(indexNum); - logger.info("indexHex:" + indexHex); - params.add(indexHex); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockNumberAndIndex", params); - logger.info("13requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - result = responseContent.getJSONObject("result"); - logger.info("16 result" + result); - Map jsonrpcResult = new HashMap(); - for (Map.Entry entry : result.entrySet()) { - jsonrpcResult.put(entry.getKey(), entry.getValue()); - } - transacionHash = jsonrpcResult.get("hash").toString(); - logger.info("transactionHash:" + transacionHash); - blockHash = jsonrpcResult.get("blockHash").toString(); - logger.info("jsonrpcResult:" + jsonrpcResult); - response = HttpMethed.getTransactionInfoByBlocknumFromSolidity(httpsolidityNode, blockNum); - logger.info("response:" + response); - List responseContent1 = HttpMethed.parseResponseContentArray(response); - logger.info("responseContent1:" + responseContent1); - blockTimeStamp = responseContent1.get(0).getLong("blockTimeStamp"); - - for (int i = 0; i < responseContent1.size(); i++) { - if (responseContent1.get(i).getString("id").equals(transactionIdList.get(0).substring(2))) { - gas = responseContent1.get(i).getJSONObject("receipt").getLong("energy_usage_total"); - logger.info("gas:" + gas); - break; - } - } - - Assert.assertEquals(jsonrpcResult.get("gas").toString(), "0x" + Long.toHexString(gas)); - Assert.assertNull(jsonrpcResult.get("nonce")); - Assert.assertEquals( - jsonrpcResult.get("hash").toString(), - "0x" + getBlockByNumFromSolidityResult.getString("txID")); - Assert.assertEquals(jsonrpcResult.get("blockHash").toString(), "0x" + bid); - Assert.assertEquals(jsonrpcResult.get("blockNumber").toString(), blockNumHex); - Assert.assertEquals(jsonrpcResult.get("transactionIndex").toString(), indexHex); - Assert.assertEquals( - jsonrpcResult.get("from").toString(), - "0x" - + getBlockByNumFromSolidityResult - .getJSONObject("raw_data") - .getJSONArray("contract") - .getJSONObject(0) - .getJSONObject("parameter") - .getJSONObject("value") - .getString("owner_address") - .substring(2)); - Assert.assertEquals( - jsonrpcResult.get("to").toString(), - "0x" - + getBlockByNumFromSolidityResult - .getJSONObject("raw_data") - .getJSONArray("contract") - .getJSONObject(0) - .getJSONObject("parameter") - .getJSONObject("value") - .getString("contract_address") - .substring(2)); - - Assert.assertEquals(jsonrpcResult.get("value").toString(), "0x1389"); - String data; - if (getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data") == null) { - data = "0x"; - } else { - data = - getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data").substring(2); - } - Assert.assertEquals(jsonrpcResult.get("input").toString(), data); - - long temp = - Long.parseLong( - getBlockByNumFromSolidityResult.getString("signature").substring(130, 131), 16); - long v = - Long.parseLong( - getBlockByNumFromSolidityResult.getString("signature").substring(130, 132), 16); - if (temp < 27) { - v += 27; - } - Assert.assertEquals(Long.parseLong(jsonrpcResult.get("v").toString().substring(2), 16), v); - Assert.assertEquals( - jsonrpcResult.get("r").toString().substring(2), - getBlockByNumFromSolidityResult.getString("signature").substring(2, 66)); - Assert.assertEquals( - jsonrpcResult.get("s").toString().substring(2), - getBlockByNumFromSolidityResult.getString("signature").substring(66, 130)); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByHash") - public void test17JsonRpcApiTestForEthGetBlockTransactionCountByHash() throws Exception { - logger.info("blockNum:" + blockNum); - JsonArray params = new JsonArray(); - params.add(blockHash); - logger.info("blockHash:" + blockHash); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByHash", params); - logger.info("requestBody:" + requestBody); - HttpMethed.waitToProduceOneBlock(httpFullNode); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNumFromjsonRpcNodeForSolidity = Integer.parseInt(transactionNum, 16); - logger.info( - "transactionNumFromjsonRpcNodeForSolidity:" + transactionNumFromjsonRpcNodeForSolidity); - response = HttpMethed.getTransactionCountByBlocknumFromSolidity(httpsolidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNumFromHttp = responseContent.getInteger("count"); - logger.info("transactionNumFromHttp:" + transactionNumFromHttp); - Assert.assertEquals(transactionNumFromHttp, transactionNumFromjsonRpcNodeForSolidity); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") - public void test18JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { - JsonArray params = new JsonArray(); - params.add(blockNum); - logger.info(String.valueOf(blockNum)); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("response:" + response); - HttpMethed.waitToProduceOneBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNum1 = Integer.parseInt(transactionNum, 16); - logger.info(String.valueOf(transactionNum1)); - response = HttpMethed.getTransactionCountByBlocknumFromSolidity(httpsolidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNum2 = responseContent.getInteger("count"); - logger.info(String.valueOf(transactionNum2)); - Assert.assertEquals(transactionNum1, transactionNum2); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockHashAndIndex") - public void test19JsonRpcApiTestForEthGetTransactionByBlockHashAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x" + bid); - params.add(indexHex); - logger.info("indexHex:" + indexHex); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockHashAndIndex", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultForGetTransactionByBlockHashAndIndex = responseContent.getJSONObject("result"); - Assert.assertEquals(result, resultForGetTransactionByBlockHashAndIndex); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionByHash") - public void test20JsonRpcApiTestForEthGetTransactionByHash() throws Exception { - JsonArray params = new JsonArray(); - params.add(transacionHash); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByHash", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject result1 = responseContent.getJSONObject("result"); - Assert.assertEquals(result, result1); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionReceipt") - public void test21JsonRpcApiTestForEthGetTransactionReceipt() throws Exception { - JsonArray params = new JsonArray(); - Thread.sleep(6000); - params.add(trc20Txid); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionReceipt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("response:" + response); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultFromTransactionReceipt = responseContent.getJSONObject("result"); - logger.info("resultFromTransactionReceipt:" + resultFromTransactionReceipt); - JSONArray logs = resultFromTransactionReceipt.getJSONArray("logs"); - logger.info("logs:" + logs); - logger.info("result:" + resultFromTransactionReceipt.toString()); - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - int index = 0; - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - if (trc20Txid.equals( - responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { - index = i; - break; - } - } - - JsonArray paramsForTransactionByBlockNumberAndIndex = new JsonArray(); - paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(blockNumForTrc20)); - paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(index)); - JsonObject requestBody1 = - getJsonRpcBody( - "eth_getTransactionByBlockNumberAndIndex", paramsForTransactionByBlockNumberAndIndex); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); - logger.info("requestBody1:" + requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultFromTransactionByBlockNumberAndIndex = responseContent.getJSONObject("result"); - logger.info( - "resultFromTransactionByBlockNumberAndIndex:" + resultFromTransactionByBlockNumberAndIndex); - Assert.assertEquals( - resultFromTransactionReceipt.getString("blockHash"), - resultFromTransactionByBlockNumberAndIndex.getString("blockHash")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("blockNumber"), - resultFromTransactionByBlockNumberAndIndex.getString("blockNumber")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("transactionIndex"), - resultFromTransactionByBlockNumberAndIndex.getString("transactionIndex")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("transactionHash"), "0x" + trc20Txid); - Assert.assertEquals( - resultFromTransactionReceipt.getString("from"), - resultFromTransactionByBlockNumberAndIndex.getString("from")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("to"), - resultFromTransactionByBlockNumberAndIndex.getString("to")); - logger.info("effectiveGasPrice:" + resultFromTransactionReceipt.getString("effectiveGasPrice")); - logger.info("gasPriceFromHttp:" + Long.toHexString(gasPriceFromHttp)); - Assert.assertEquals( - resultFromTransactionReceipt.getString("effectiveGasPrice"), - "0x" + Long.toHexString(gasPriceFromHttp)); + JsonArray paramsForTransactionByBlockNumberAndIndex = new JsonArray(); + paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(blockNumForTrc20)); + paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(index)); + JsonObject requestBody1 = + getJsonRpcBody( + "eth_getTransactionByBlockNumberAndIndex", paramsForTransactionByBlockNumberAndIndex); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); + logger.info("requestBody1:" + requestBody1); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject resultFromTransactionByBlockNumberAndIndex = responseContent.getJSONObject("result"); + logger.info( + "resultFromTransactionByBlockNumberAndIndex:" + resultFromTransactionByBlockNumberAndIndex); + Assert.assertEquals( + resultFromTransactionReceipt.getString("blockHash"), + resultFromTransactionByBlockNumberAndIndex.getString("blockHash")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("blockNumber"), + resultFromTransactionByBlockNumberAndIndex.getString("blockNumber")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("transactionIndex"), + resultFromTransactionByBlockNumberAndIndex.getString("transactionIndex")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("transactionHash"), "0x" + trc20Txid); + Assert.assertEquals( + resultFromTransactionReceipt.getString("from"), + resultFromTransactionByBlockNumberAndIndex.getString("from")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("to"), + resultFromTransactionByBlockNumberAndIndex.getString("to")); + logger.info("effectiveGasPrice:" + resultFromTransactionReceipt.getString("effectiveGasPrice")); + logger.info("gasPriceFromHttp:" + Long.toHexString(gasPriceFromHttp)); + Assert.assertEquals( + resultFromTransactionReceipt.getString("effectiveGasPrice"), + "0x" + Long.toHexString(gasPriceFromHttp)); /* Assert.assertEquals( resultFromTransactionReceipt.getString("contractAddress").substring(2), trc20AddressHex.substring(2));*/ - Assert.assertNull(resultFromTransactionReceipt.getString("contractAddress")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("logsBloom"), - "0x000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000"); - Assert.assertEquals("0x1", resultFromTransactionReceipt.getString("status")); - Assert.assertEquals("0x0", resultFromTransactionReceipt.getString("type")); - logger.info("gas:" + resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("gasUsed"), - resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("cumulativeGasUsed"), - resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - logs.getJSONObject(0).getString("logIndex"), "0x" + Integer.toHexString(index)); - Assert.assertEquals(logs.getJSONObject(0).getString("removed"), "false"); - Assert.assertEquals( - logs.getJSONObject(0).getString("blockHash"), - resultFromTransactionReceipt.getString("blockHash")); - Assert.assertEquals( - logs.getJSONObject(0).getString("blockNumber"), - resultFromTransactionReceipt.getString("blockNumber")); - Assert.assertEquals( - logs.getJSONObject(0).getString("transactionIndex"), - resultFromTransactionReceipt.getString("transactionIndex")); - Assert.assertEquals( - logs.getJSONObject(0).getString("transactionHash"), - resultFromTransactionReceipt.getString("transactionHash")); - Assert.assertEquals( - logs.getJSONObject(0).getString("address"), resultFromTransactionReceipt.getString("to")); - response = - HttpMethed.getTransactionInfoByBlocknumFromSolidity(httpsolidityNode, blockNumForTrc20); - List responseContent1 = HttpMethed.parseResponseContentArray(response); - logger.info("responseContent1:" + responseContent1); - - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertEquals( - logs.getJSONObject(0).getString("data").substring(2), - responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("data")); - - Assert.assertEquals( - logs.getJSONObject(0).getString("topics").replace("0x", ""), - responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("topics")); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockHashAndIndex") - public void test22JsonRpcApiTestForEthGetUncleByBlockHashAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); - params.add("0x"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockHashAndIndex", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNull(result); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockNumberAndIndex") - public void test23JsonRpcApiTestForEthGetUncleByBlockNumberAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0xeb82f0"); - params.add("0x"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockNumberAndIndex", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNull(result); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockHash") - public void test24JsonRpcApiTestForEthGetUncleCountByBlockHash() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockHash", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "0x0"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockNumber") - public void test25JsonRpcApiTestForEthGetUncleCountByBlockNumber() throws Exception { - JsonArray params = new JsonArray(); - params.add("eth_getUncleCountByBlockNumber"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockNumber", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "0x0"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getWork") - public void test26JsonRpcApiTestForEthGetWork() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_getWork", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - int resultLen = result.length(); - String resultFromjsonRpcNodeForSolidity = result.substring(4, resultLen - 12); - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - String resultFromHttp = responseContent.getString("blockID"); - logger.info("resultFromjsonRpcNodeForSolidity:" + resultFromjsonRpcNodeForSolidity); - logger.info("resultFromHttp:" + resultFromHttp); - Assert.assertEquals(resultFromjsonRpcNodeForSolidity, resultFromHttp); + Assert.assertNull(resultFromTransactionReceipt.getString("contractAddress")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("logsBloom"), + "0x000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000"); + Assert.assertEquals("0x1", resultFromTransactionReceipt.getString("status")); + Assert.assertEquals("0x0", resultFromTransactionReceipt.getString("type")); + logger.info("gas:" + resultFromTransactionByBlockNumberAndIndex.getString("gas")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("gasUsed"), + resultFromTransactionByBlockNumberAndIndex.getString("gas")); + Assert.assertEquals( + resultFromTransactionReceipt.getString("cumulativeGasUsed"), + resultFromTransactionByBlockNumberAndIndex.getString("gas")); + Assert.assertEquals( + logs.getJSONObject(0).getString("logIndex"), "0x" + Integer.toHexString(index)); + Assert.assertEquals(logs.getJSONObject(0).getString("removed"), "false"); + Assert.assertEquals( + logs.getJSONObject(0).getString("blockHash"), + resultFromTransactionReceipt.getString("blockHash")); + Assert.assertEquals( + logs.getJSONObject(0).getString("blockNumber"), + resultFromTransactionReceipt.getString("blockNumber")); + Assert.assertEquals( + logs.getJSONObject(0).getString("transactionIndex"), + resultFromTransactionReceipt.getString("transactionIndex")); + Assert.assertEquals( + logs.getJSONObject(0).getString("transactionHash"), + resultFromTransactionReceipt.getString("transactionHash")); + Assert.assertEquals( + logs.getJSONObject(0).getString("address"), resultFromTransactionReceipt.getString("to")); + response = + HttpMethed.getTransactionInfoByBlocknumFromSolidity(httpsolidityNode, blockNumForTrc20); + List responseContent1 = HttpMethed.parseResponseContentArray(response); + logger.info("responseContent1:" + responseContent1); + + response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNumForTrc20); + responseContent = HttpMethed.parseResponseContent(response); + Assert.assertEquals( + logs.getJSONObject(0).getString("data").substring(2), + responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("data")); + + Assert.assertEquals( + logs.getJSONObject(0).getString("topics").replace("0x", ""), + responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("topics")); + } + + @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockHashAndIndex") + public void test22JsonRpcApiTestForEthGetUncleByBlockHashAndIndex() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); + params.add("0x"); + JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockHashAndIndex", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertNull(result); + } + + @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockNumberAndIndex") + public void test23JsonRpcApiTestForEthGetUncleByBlockNumberAndIndex() throws Exception { + JsonArray params = new JsonArray(); + params.add("0xeb82f0"); + params.add("0x"); + JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockNumberAndIndex", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertNull(result); + } + + @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockHash") + public void test24JsonRpcApiTestForEthGetUncleCountByBlockHash() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); + JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockHash", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertEquals(result, "0x0"); + } + + @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockNumber") + public void test25JsonRpcApiTestForEthGetUncleCountByBlockNumber() throws Exception { + JsonArray params = new JsonArray(); + params.add("eth_getUncleCountByBlockNumber"); + JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockNumber", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertEquals(result, "0x0"); + } + + @Test(enabled = true, description = "Json rpc api of eth_getWork") + public void test26JsonRpcApiTestForEthGetWork() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_getWork", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + int resultLen = result.length(); + String resultFromjsonRpcNodeForSolidity = result.substring(4, resultLen - 12); + response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + String resultFromHttp = responseContent.getString("blockID"); + logger.info("resultFromjsonRpcNodeForSolidity:" + resultFromjsonRpcNodeForSolidity); + logger.info("resultFromHttp:" + resultFromHttp); + Assert.assertEquals(resultFromjsonRpcNodeForSolidity, resultFromHttp); + } + + @Test(enabled = true, description = "Json rpc api of eth_hashrate") + public void test27JsonRpcApiTestForEthHashRate() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_hashrate", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertEquals("0x0", result); + } + + @Test(enabled = true, description = "Json rpc api of eth_mining") + public void test28JsonRpcApiTestForEthMining() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_mining", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertEquals(result, "true"); + } + + @Test(enabled = true, description = "Json rpc api of eth_protocolVersion") + public void test29JsonRpcApiTestForEthProtocolVersion() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_protocolVersion", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String protocolVersion = responseContent.getString("result").substring(2); + Long protocolVersion1 = Long.parseLong(protocolVersion, 16); + response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + Long protocolVersion2 = + responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("version"); + logger.info(protocolVersion1.toString()); + logger.info(protocolVersion2.toString()); + Assert.assertEquals(protocolVersion1, protocolVersion2); + } + + @Test(enabled = true, description = "Json rpc api of eth_syncing") + public void test30JsonRpcApiTestForEthSyncing() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_syncing", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject temp = responseContent.getJSONObject("result"); + String currentNumFromRpc = temp.getString("currentBlock"); + logger.info(currentNumFromRpc); + logger.info(temp.toString()); + response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + long currentNum = + responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); + logger.info("currentNum:" + currentNum); + logger.info("currentNumFromRpc:" + Long.parseLong(currentNumFromRpc.substring(2), 16)); + Assert.assertEquals(currentNum, Long.parseLong(currentNumFromRpc.substring(2), 16)); + Assert.assertTrue(temp.containsKey("startingBlock")); + Assert.assertTrue(temp.containsKey("currentBlock")); + Assert.assertTrue(temp.containsKey("highestBlock")); + } + + @Test(enabled = true, description = "Json rpc api of net_listening") + public void test31JsonRpcApiTestForNetListening() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("net_listening", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + Boolean temp = responseContent.getBoolean("result"); + logger.info(temp.toString()); + response = HttpMethed.getNodeInfo(httpsolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + boolean expect = false; + int num = responseContent.getInteger("activeConnectCount"); + if (num >= 1) { + expect = true; } - - @Test(enabled = true, description = "Json rpc api of eth_hashrate") - public void test27JsonRpcApiTestForEthHashRate() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_hashrate", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals("0x0", result); - } - - @Test(enabled = true, description = "Json rpc api of eth_mining") - public void test28JsonRpcApiTestForEthMining() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_mining", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "true"); - } - - @Test(enabled = true, description = "Json rpc api of eth_protocolVersion") - public void test29JsonRpcApiTestForEthProtocolVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_protocolVersion", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String protocolVersion = responseContent.getString("result").substring(2); - Long protocolVersion1 = Long.parseLong(protocolVersion, 16); - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - Long protocolVersion2 = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("version"); - logger.info(protocolVersion1.toString()); - logger.info(protocolVersion2.toString()); - Assert.assertEquals(protocolVersion1, protocolVersion2); - } - - @Test(enabled = true, description = "Json rpc api of eth_syncing") - public void test30JsonRpcApiTestForEthSyncing() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_syncing", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject temp = responseContent.getJSONObject("result"); - String currentNumFromRpc = temp.getString("currentBlock"); - logger.info(currentNumFromRpc); - logger.info(temp.toString()); - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - long currentNum = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - logger.info("currentNum:" + currentNum); - logger.info("currentNumFromRpc:" + Long.parseLong(currentNumFromRpc.substring(2), 16)); - Assert.assertEquals(currentNum, Long.parseLong(currentNumFromRpc.substring(2), 16)); - Assert.assertTrue(temp.containsKey("startingBlock")); - Assert.assertTrue(temp.containsKey("currentBlock")); - Assert.assertTrue(temp.containsKey("highestBlock")); - } - - @Test(enabled = true, description = "Json rpc api of net_listening") - public void test31JsonRpcApiTestForNetListening() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_listening", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - Boolean temp = responseContent.getBoolean("result"); - logger.info(temp.toString()); - response = HttpMethed.getNodeInfo(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - boolean expect = false; - int num = responseContent.getInteger("activeConnectCount"); - if (num >= 1) { - expect = true; - } - Assert.assertEquals(temp, expect); - } - - @Test(enabled = true, description = "Json rpc api of net_peerCount") - public void test32JsonRpcApiTestForNetPeerCount() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_peerCount", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNotNull(result); + Assert.assertEquals(temp, expect); + } + + @Test(enabled = true, description = "Json rpc api of net_peerCount") + public void test32JsonRpcApiTestForNetPeerCount() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("net_peerCount", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + logger.info(result); + Assert.assertNotNull(result); + } + + @Test(enabled = true, description = "Json rpc api of net_version") + public void test33JsonRpcApiTestForEthVersion() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("net_version", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String firstBlockHashFromJsonRpc = responseContent.getString("result").substring(2); + response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, 0); + responseContent = HttpMethed.parseResponseContent(response); + String firstBlockHashFromHttp = responseContent.getString("blockID").substring(56); + logger.info("firstBlockHashFromJsonRpc" + firstBlockHashFromJsonRpc); + logger.info("firstBlockHashFromHttp" + firstBlockHashFromHttp); + Assert.assertEquals(firstBlockHashFromJsonRpc, firstBlockHashFromHttp); + } + + @Test(enabled = true, description = "Json rpc api of web3_clientVersion") + public void test34JsonRpcApiTestForWeb3ClientVersion() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("web3_clientVersion", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String result = responseContent.getString("result"); + List resultList = new ArrayList<>(); + for (String str : result.split("/")) { + resultList.add(str); } - - @Test(enabled = true, description = "Json rpc api of net_version") - public void test33JsonRpcApiTestForEthVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_version", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String firstBlockHashFromJsonRpc = responseContent.getString("result").substring(2); - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - String firstBlockHashFromHttp = responseContent.getString("blockID").substring(56); - logger.info("firstBlockHashFromJsonRpc" + firstBlockHashFromJsonRpc); - logger.info("firstBlockHashFromHttp" + firstBlockHashFromHttp); - Assert.assertEquals(firstBlockHashFromJsonRpc, firstBlockHashFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of web3_clientVersion") - public void test34JsonRpcApiTestForWeb3ClientVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("web3_clientVersion", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - List resultList = new ArrayList<>(); - for (String str : result.split("/")) { - resultList.add(str); - } - Assert.assertEquals(resultList.size(), 5); - Assert.assertEquals(resultList.get(0), "TRON"); - Assert.assertEquals(resultList.get(1).substring(0, 1), "v"); - Assert.assertEquals(resultList.get(2), "Linux"); - Assert.assertEquals(resultList.get(3), "Java1.8"); - Assert.assertEquals(resultList.get(4).substring(0, 11), "GreatVoyage"); + Assert.assertEquals(resultList.size(), 5); + Assert.assertEquals(resultList.get(0), "TRON"); + Assert.assertEquals(resultList.get(1).substring(0, 1), "v"); + Assert.assertEquals(resultList.get(2), "Linux"); + Assert.assertEquals(resultList.get(3), "Java1.8"); + Assert.assertEquals(resultList.get(4).substring(0, 11), "GreatVoyage"); + } + + @Test(enabled = true, description = "Json rpc api of web3_sha3") + public void test35JsonRpcApiTestForWeb3Sha3() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x08"); + JsonObject requestBody1 = getJsonRpcBody("web3_sha3", params); + response = getEthHttps(ethHttpsNode, requestBody1); + responseContent = HttpMethed.parseResponseContent(response); + String result1 = responseContent.getString("result"); + JsonObject requestBody2 = getJsonRpcBody("web3_sha3", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody2); + responseContent = HttpMethed.parseResponseContent(response); + String result2 = responseContent.getString("result"); + Assert.assertEquals(result1, result2); + } + + @Test(enabled = true, description = "Json rpc api of eth_compileLLL") + public void test36JsonRpcApiTestForEthCompileLll() throws Exception { + JsonArray params = new JsonArray(); + params.add("(returnlll (suicide (caller)))"); + JsonObject requestBody1 = getJsonRpcBody("eth_compileLLL", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals(errorMessage, "the method eth_compileLLL does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_compileSerpent") + public void test37JsonRpcApiTestForEthCompileSerpent() throws Exception { + JsonArray params = new JsonArray(); + params.add("/* some serpent */"); + JsonObject requestBody = getJsonRpcBody("eth_compileSerpent", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_compileSerpent does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_compileSolidity") + public void test38JsonRpcApiTestForEthCompileSolidity() throws Exception { + JsonArray params = new JsonArray(); + params.add("contract test { function multiply(uint a) returns(uint d) { return a * 7; } }"); + JsonObject requestBody = getJsonRpcBody("eth_compileSolidity", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_compileSolidity does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_getCompilers") + public void test39JsonRpcApiTestForEthCompileSolidity() throws Exception { + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_getCompilers", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_getCompilers does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_getTransactionCount") + public void test40JsonRpcApiTestForEthGetTransactionCount() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x407d73d8a49eeb85d32cf465507dd71d507100c1"); + params.add("latest"); + JsonObject requestBody = getJsonRpcBody("eth_getTransactionCount", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_getTransactionCount does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_sendRawTransaction") + public void test41JsonRpcApiTestForEthSendRawTransaction() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x234"); + JsonObject requestBody = getJsonRpcBody("eth_sendRawTransaction", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_sendRawTransaction does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_sendTransaction") + public void test42JsonRpcApiTestForEthSendTransaction() throws Exception { + JsonArray params = new JsonArray(); + JsonObject temp = new JsonObject(); + params.add(temp); + temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); + temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); + temp.addProperty("gas", "0x76c0"); + temp.addProperty("gasPrice", "0x9184e72a000"); + temp.addProperty( + "data", + "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); + temp.addProperty("value", "0x9184e72a"); + + JsonObject requestBody = getJsonRpcBody("eth_sendTransaction", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_sendTransaction does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_sign") + public void test43JsonRpcApiTestForEthSign() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); + params.add("0xdeadbeaf"); + JsonObject requestBody = getJsonRpcBody("eth_sign", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals(errorMessage, "the method eth_sign does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_signTransaction") + public void test44JsonRpcApiTestForEthSignTransaction() throws Exception { + JsonArray params = new JsonArray(); + JsonObject temp = new JsonObject(); + params.add(temp); + temp.addProperty( + "data", + "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); + temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); + temp.addProperty("gas", "0x76c0"); + temp.addProperty("gasPrice", "0x9184e72a000"); + temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); + temp.addProperty("value", "0x9184e72a"); + + JsonObject requestBody = getJsonRpcBody("eth_signTransaction", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_signTransaction does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_submitWork") + public void test45JsonRpcApiTestForEthSubmitWork() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x0000000000000001"); + params.add("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"); + params.add("0xD1GE5700000000000000000000000000D1GE5700000000000000000000000000"); + JsonObject requestBody = getJsonRpcBody("eth_submitWork", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals(errorMessage, "the method eth_submitWork does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of parity_nextNonce") + public void test46JsonRpcApiTestForParityNextNonce() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); + JsonObject requestBody = getJsonRpcBody("parity_nextNonce", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method parity_nextNonce does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_submitHashrate") + public void test47JsonRpcApiTestForEthSubmitHashrate() throws Exception { + JsonArray params = new JsonArray(); + params.add("0x0000000000000000000000000000000000000000000000000000000000500000"); + params.add("0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c"); + JsonObject requestBody = getJsonRpcBody("eth_submitHashrate", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String errorMessage = responseContent.getJSONObject("error").getString("message"); + Assert.assertEquals( + errorMessage, "the method eth_submitHashrate does not exist/is not available"); + } + + @Test(enabled = true, description = "Json rpc api of eth_getBlockByHash params is false") + public void test48JsonRpcApiTestForEthGetBlockByHash() throws Exception { + response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNum); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("45getBlockByNumFromSolidityFromHttp:" + responseContent); + accountStateRoot = + responseContent + .getJSONObject("block_header") + .getJSONObject("raw_data") + .getString("accountStateRoot"); + JsonArray params = new JsonArray(); + params.add(blockHash); + params.add(false); + JsonObject requestBody = getJsonRpcBody("eth_getBlockByHash", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + JSONObject getBlockByHashResult = responseContent.getJSONObject("result"); + + Assert.assertNull(getBlockByHashResult.getString("nonce")); + Assert.assertNull(getBlockByHashResult.getString("sha3Uncles")); + Assert.assertNull(getBlockByHashResult.getString("receiptsRoot")); + Assert.assertNull(getBlockByHashResult.getString("difficulty")); + Assert.assertNull(getBlockByHashResult.getString("totalDifficulty")); + Assert.assertNull(getBlockByHashResult.getString("extraData")); + Assert.assertNull(getBlockByHashResult.getString("baseFeePerGas")); + Assert.assertNull(getBlockByHashResult.getString("mixHash")); + Assert.assertEquals(getBlockByHashResult.getString("uncles"), new ArrayList<>().toString()); + Assert.assertEquals(getBlockByHashResult.getString("stateRoot"), "0x" + accountStateRoot); + + Assert.assertEquals( + getBlockByHashResult.getString("logsBloom"), + "0x00000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000000000000000000000000" + + "000000000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000"); + Assert.assertEquals(getBlockByHashResult.getString("number"), blockNumHex); + Assert.assertEquals(getBlockByHashResult.getString("hash"), "0x" + bid); + Assert.assertEquals(getBlockByHashResult.getString("parentHash"), "0x" + parentHash); + Assert.assertEquals(getBlockByHashResult.getString("transactionsRoot"), "0x" + txTrieRoot); + Assert.assertEquals( + getBlockByHashResult.getString("miner"), "0x" + witnessAddress.substring(2)); + Assert.assertEquals(getBlockByHashResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); + Assert.assertEquals( + String.valueOf(Long.parseLong(getBlockByHashResult.getString("gasLimit").substring(2), 16)), + feeLimit); + Assert.assertEquals( + Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16), + blockTimeStamp); + final GrpcAPI.NumberMessage message = + GrpcAPI.NumberMessage.newBuilder().setNum(blockNum).build(); + HttpMethed.waitToProduceOneBlock(httpFullNode); + Block block = blockingStubFull.getBlockByNum(message); + logger.info("sizeFromJrpc:" + block.getSerializedSize()); + logger.info( + "sizeFromJsonRPc:" + + Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16)); + size = block.getSerializedSize(); + Assert.assertEquals( + Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16), + block.getSerializedSize()); + + Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16); + JSONArray transactionId = getBlockByHashResult.getJSONArray("transactions"); + List transactionIdListFromGetBlockByHash = new ArrayList<>(); + if (transactionId.size() > 0) { + for (int i = 0; i < transactionId.size(); i++) { + transactionIdListFromGetBlockByHash.add(transactionId.get(i).toString()); + } } - - @Test(enabled = true, description = "Json rpc api of web3_sha3") - public void test35JsonRpcApiTestForWeb3Sha3() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x08"); - JsonObject requestBody1 = getJsonRpcBody("web3_sha3", params); - response = getEthHttps(ethHttpsNode, requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - String result1 = responseContent.getString("result"); - JsonObject requestBody2 = getJsonRpcBody("web3_sha3", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody2); - responseContent = HttpMethed.parseResponseContent(response); - String result2 = responseContent.getString("result"); - Assert.assertEquals(result1, result2); - } - - @Test(enabled = true, description = "Json rpc api of eth_compileLLL") - public void test36JsonRpcApiTestForEthCompileLll() throws Exception { - JsonArray params = new JsonArray(); - params.add("(returnlll (suicide (caller)))"); - JsonObject requestBody1 = getJsonRpcBody("eth_compileLLL", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_compileLLL does not exist/is not available"); + Assert.assertEquals(transactionIdListFromGetBlockByHash, transactionIdList); + } + + @Test( + enabled = true, + description = "Json rpc api of eth_getBlockByNumFromSolidityber params is true") + public void test49JsonRpcApiTestForEthgetBlockByNumFromSolidityber() throws Exception { + + JsonArray params = new JsonArray(); + params.add(blockNumHex); + logger.info("46blockNumHex:" + blockNumHex); + params.add(true); + JsonObject requestBody = getJsonRpcBody("eth_getBlockByNumber", params); + logger.info("requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + JSONObject getBlockByNumFromSolidityberResult = responseContent.getJSONObject("result"); + logger.info("getBlockByHashResult:" + getBlockByNumFromSolidityberResult); + + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("nonce")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("sha3Uncles")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("receiptsRoot")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("difficulty")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("totalDifficulty")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("extraData")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("baseFeePerGas")); + Assert.assertNull(getBlockByNumFromSolidityberResult.getString("mixHash")); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("uncles"), new ArrayList<>().toString()); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("stateRoot"), "0x" + accountStateRoot); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("logsBloom"), + "0x00000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000000000000000" + + "000000000000000000000000000000000000000000000000000000000000000000000000" + + "000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000"); + Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("number"), blockNumHex); + Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("hash"), "0x" + bid); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("parentHash"), "0x" + parentHash); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("transactionsRoot"), "0x" + txTrieRoot); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("miner"), "0x" + witnessAddress.substring(2)); + Assert.assertEquals( + getBlockByNumFromSolidityberResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); + Assert.assertEquals( + String.valueOf( + Long.parseLong( + getBlockByNumFromSolidityberResult.getString("gasLimit").substring(2), 16)), + feeLimit); + Assert.assertEquals( + Long.parseLong(getBlockByNumFromSolidityberResult.getString("timestamp").substring(2), 16), + blockTimeStamp); + logger.info("size:" + size); + Assert.assertEquals( + Long.parseLong(getBlockByNumFromSolidityberResult.getString("size").substring(2), 16), + size); + + JSONArray transactionsList = getBlockByNumFromSolidityberResult.getJSONArray("transactions"); + logger.info("transactionsList:" + transactionsList); + List transactionInfoListFromGetBlockByHash = new ArrayList<>(); + if (transactionsList.size() > 0) { + for (int i = 0; i < transactionsList.size(); i++) { + transactionInfoListFromGetBlockByHash.add(transactionsList.get(i).toString()); + } } - - @Test(enabled = true, description = "Json rpc api of eth_compileSerpent") - public void test37JsonRpcApiTestForEthCompileSerpent() throws Exception { - JsonArray params = new JsonArray(); - params.add("/* some serpent */"); - JsonObject requestBody = getJsonRpcBody("eth_compileSerpent", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_compileSerpent does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_compileSolidity") - public void test38JsonRpcApiTestForEthCompileSolidity() throws Exception { - JsonArray params = new JsonArray(); - params.add("contract test { function multiply(uint a) returns(uint d) { return a * 7; } }"); - JsonObject requestBody = getJsonRpcBody("eth_compileSolidity", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_compileSolidity does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getCompilers") - public void test39JsonRpcApiTestForEthCompileSolidity() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_getCompilers", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_getCompilers does not exist/is not available"); + List transactionInfoListFromTransactionByBlockNumberAndIndex = new ArrayList<>(); + for (int i = 0; i < transactionsList.size(); i++) { + JsonArray paramsForEthGetTransactionByBlockNumberAndIndex = new JsonArray(); + paramsForEthGetTransactionByBlockNumberAndIndex.add(blockNumHex); + String index = "0x" + Integer.toHexString(i); + logger.info("index:" + index); + paramsForEthGetTransactionByBlockNumberAndIndex.add(index); + logger.info( + "paramsForEthGetTransactionByBlockNumberAndIndex:" + + paramsForEthGetTransactionByBlockNumberAndIndex); + JsonObject requestBodyForTransactionByBlockNumberAndIndex = + getJsonRpcBody( + "eth_getTransactionByBlockNumberAndIndex", + paramsForEthGetTransactionByBlockNumberAndIndex); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForTransactionByBlockNumberAndIndex); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + result = responseContent.getJSONObject("result"); + logger.info("result:" + result); + transactionInfoListFromTransactionByBlockNumberAndIndex.add(result.toString()); } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionCount") - public void test40JsonRpcApiTestForEthGetTransactionCount() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x407d73d8a49eeb85d32cf465507dd71d507100c1"); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionCount", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_getTransactionCount does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sendRawTransaction") - public void test41JsonRpcApiTestForEthSendRawTransaction() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x234"); - JsonObject requestBody = getJsonRpcBody("eth_sendRawTransaction", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_sendRawTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sendTransaction") - public void test42JsonRpcApiTestForEthSendTransaction() throws Exception { - JsonArray params = new JsonArray(); - JsonObject temp = new JsonObject(); - params.add(temp); - temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); - temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); - temp.addProperty("gas", "0x76c0"); - temp.addProperty("gasPrice", "0x9184e72a000"); - temp.addProperty( - "data", - "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); - temp.addProperty("value", "0x9184e72a"); - - JsonObject requestBody = getJsonRpcBody("eth_sendTransaction", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_sendTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sign") - public void test43JsonRpcApiTestForEthSign() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); - params.add("0xdeadbeaf"); - JsonObject requestBody = getJsonRpcBody("eth_sign", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_sign does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_signTransaction") - public void test44JsonRpcApiTestForEthSignTransaction() throws Exception { - JsonArray params = new JsonArray(); - JsonObject temp = new JsonObject(); - params.add(temp); - temp.addProperty( - "data", - "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); - temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); - temp.addProperty("gas", "0x76c0"); - temp.addProperty("gasPrice", "0x9184e72a000"); - temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); - temp.addProperty("value", "0x9184e72a"); - - JsonObject requestBody = getJsonRpcBody("eth_signTransaction", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_signTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_submitWork") - public void test45JsonRpcApiTestForEthSubmitWork() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000000001"); - params.add("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"); - params.add("0xD1GE5700000000000000000000000000D1GE5700000000000000000000000000"); - JsonObject requestBody = getJsonRpcBody("eth_submitWork", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_submitWork does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of parity_nextNonce") - public void test46JsonRpcApiTestForParityNextNonce() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); - JsonObject requestBody = getJsonRpcBody("parity_nextNonce", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method parity_nextNonce does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_submitHashrate") - public void test47JsonRpcApiTestForEthSubmitHashrate() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000000000000000000000000000000000000000000000000000500000"); - params.add("0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c"); - JsonObject requestBody = getJsonRpcBody("eth_submitHashrate", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_submitHashrate does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockByHash params is false") - public void test48JsonRpcApiTestForEthGetBlockByHash() throws Exception { - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("45getBlockByNumFromSolidityFromHttp:" + responseContent); - accountStateRoot = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("accountStateRoot"); - JsonArray params = new JsonArray(); - params.add(blockHash); - params.add(false); - JsonObject requestBody = getJsonRpcBody("eth_getBlockByHash", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject getBlockByHashResult = responseContent.getJSONObject("result"); - - Assert.assertNull(getBlockByHashResult.getString("nonce")); - Assert.assertNull(getBlockByHashResult.getString("sha3Uncles")); - Assert.assertNull(getBlockByHashResult.getString("receiptsRoot")); - Assert.assertNull(getBlockByHashResult.getString("difficulty")); - Assert.assertNull(getBlockByHashResult.getString("totalDifficulty")); - Assert.assertNull(getBlockByHashResult.getString("extraData")); - Assert.assertNull(getBlockByHashResult.getString("baseFeePerGas")); - Assert.assertNull(getBlockByHashResult.getString("mixHash")); - Assert.assertEquals(getBlockByHashResult.getString("uncles"), new ArrayList<>().toString()); - Assert.assertEquals(getBlockByHashResult.getString("stateRoot"), "0x" + accountStateRoot); - - Assert.assertEquals( - getBlockByHashResult.getString("logsBloom"), - "0x00000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000"); - Assert.assertEquals(getBlockByHashResult.getString("number"), blockNumHex); - Assert.assertEquals(getBlockByHashResult.getString("hash"), "0x" + bid); - Assert.assertEquals(getBlockByHashResult.getString("parentHash"), "0x" + parentHash); - Assert.assertEquals(getBlockByHashResult.getString("transactionsRoot"), "0x" + txTrieRoot); - Assert.assertEquals( - getBlockByHashResult.getString("miner"), "0x" + witnessAddress.substring(2)); - Assert.assertEquals(getBlockByHashResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); - Assert.assertEquals( - String.valueOf(Long.parseLong(getBlockByHashResult.getString("gasLimit").substring(2), 16)), - feeLimit); - Assert.assertEquals( - Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16), - blockTimeStamp); - final GrpcAPI.NumberMessage message = - GrpcAPI.NumberMessage.newBuilder().setNum(blockNum).build(); - HttpMethed.waitToProduceOneBlock(httpFullNode); - Block block = blockingStubFull.getBlockByNum(message); - logger.info("sizeFromJrpc:" + block.getSerializedSize()); - logger.info( - "sizeFromJsonRPc:" - + Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16)); - size = block.getSerializedSize(); - Assert.assertEquals( - Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16), - block.getSerializedSize()); - - Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16); - JSONArray transactionId = getBlockByHashResult.getJSONArray("transactions"); - List transactionIdListFromGetBlockByHash = new ArrayList<>(); - if (transactionId.size() > 0) { - for (int i = 0; i < transactionId.size(); i++) { - transactionIdListFromGetBlockByHash.add(transactionId.get(i).toString()); - } - } - Assert.assertEquals(transactionIdListFromGetBlockByHash, transactionIdList); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getBlockByNumFromSolidityber params is true") - public void test49JsonRpcApiTestForEthgetBlockByNumFromSolidityber() throws Exception { - - JsonArray params = new JsonArray(); - params.add(blockNumHex); - logger.info("46blockNumHex:" + blockNumHex); - params.add(true); - JsonObject requestBody = getJsonRpcBody("eth_getBlockByNumber", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - JSONObject getBlockByNumFromSolidityberResult = responseContent.getJSONObject("result"); - logger.info("getBlockByHashResult:" + getBlockByNumFromSolidityberResult); - - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("nonce")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("sha3Uncles")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("receiptsRoot")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("difficulty")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("totalDifficulty")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("extraData")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("baseFeePerGas")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("mixHash")); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("uncles"), new ArrayList<>().toString()); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("stateRoot"), "0x" + accountStateRoot); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("logsBloom"), - "0x00000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000"); - Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("number"), blockNumHex); - Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("hash"), "0x" + bid); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("parentHash"), "0x" + parentHash); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("transactionsRoot"), "0x" + txTrieRoot); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("miner"), "0x" + witnessAddress.substring(2)); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); - Assert.assertEquals( - String.valueOf( - Long.parseLong( - getBlockByNumFromSolidityberResult.getString("gasLimit").substring(2), 16)), - feeLimit); - Assert.assertEquals( - Long.parseLong(getBlockByNumFromSolidityberResult.getString("timestamp").substring(2), 16), - blockTimeStamp); - logger.info("size:" + size); - Assert.assertEquals( - Long.parseLong(getBlockByNumFromSolidityberResult.getString("size").substring(2), 16), - size); - - JSONArray transactionsList = getBlockByNumFromSolidityberResult.getJSONArray("transactions"); - logger.info("transactionsList:" + transactionsList); - List transactionInfoListFromGetBlockByHash = new ArrayList<>(); - if (transactionsList.size() > 0) { - for (int i = 0; i < transactionsList.size(); i++) { - transactionInfoListFromGetBlockByHash.add(transactionsList.get(i).toString()); - } - } - List transactionInfoListFromTransactionByBlockNumberAndIndex = new ArrayList<>(); - for (int i = 0; i < transactionsList.size(); i++) { - JsonArray paramsForEthGetTransactionByBlockNumberAndIndex = new JsonArray(); - paramsForEthGetTransactionByBlockNumberAndIndex.add(blockNumHex); - String index = "0x" + Integer.toHexString(i); - logger.info("index:" + index); - paramsForEthGetTransactionByBlockNumberAndIndex.add(index); - logger.info( - "paramsForEthGetTransactionByBlockNumberAndIndex:" - + paramsForEthGetTransactionByBlockNumberAndIndex); - JsonObject requestBodyForTransactionByBlockNumberAndIndex = - getJsonRpcBody( - "eth_getTransactionByBlockNumberAndIndex", - paramsForEthGetTransactionByBlockNumberAndIndex); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForTransactionByBlockNumberAndIndex); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - result = responseContent.getJSONObject("result"); - logger.info("result:" + result); - transactionInfoListFromTransactionByBlockNumberAndIndex.add(result.toString()); - } - Assert.assertEquals( - transactionInfoListFromGetBlockByHash, - transactionInfoListFromTransactionByBlockNumberAndIndex); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } + Assert.assertEquals( + transactionInfoListFromGetBlockByHash, + transactionInfoListFromTransactionByBlockNumberAndIndex); + } + + /** constructor. */ + @AfterClass + public void shutdown() throws InterruptedException { + if (channelFull != null) { + channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); } + } } diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java index e5d5b4c22fa..be42416ccbb 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java @@ -12,363 +12,363 @@ @Slf4j public class Accounts004 extends JsonRpcBase { - JSONObject responseContent; - HttpResponse response; - String topic0 = null; - String topic1 = null; - String fromBlock = null; - String toBlock = null; - String newFilterResultIdfrom01 = null; - String newFilterResultIdfrom02 = null; - String blockHash = null; + JSONObject responseContent; + HttpResponse response; + String topic0 = null; + String topic1 = null; + String fromBlock = null; + String toBlock = null; + String newFilterResultIdfrom01 = null; + String newFilterResultIdfrom02 = null; + String blockHash = null; - @Test(enabled = true, description = "Eth api of eth_newFilter contains nothing.") - public void test01GetNewFilterContainNothing() { - JsonObject paramBody = new JsonObject(); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test01GetNewFilterContainNothing_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test01GetNewFilterContainNothing_responseContent" + responseContent); - logger.info("result:" + responseContent.getString("result")); - Assert.assertNotNull(responseContent.getString("result")); - } + @Test(enabled = true, description = "Eth api of eth_newFilter contains nothing.") + public void test01GetNewFilterContainNothing() { + JsonObject paramBody = new JsonObject(); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test01GetNewFilterContainNothing_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test01GetNewFilterContainNothing_responseContent" + responseContent); + logger.info("result:" + responseContent.getString("result")); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test( - enabled = true, - description = "Eth api of eth_newFilter contains address,fromBlock and toBlock.") - public void test02GetNewFilterContainAddress() { - if (blockNumForTrc20 - 10 < 0) { - fromBlock = "0"; - } else { - fromBlock = "0x" + Integer.toHexString(blockNumForTrc20 - 10); - } - toBlock = "0x" + Integer.toHexString(blockNumForTrc20 + 10); - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test02GetNewFilterContainAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test02GetNewFilterContainAddress_responseContent" + responseContent); - newFilterResultIdfrom01 = responseContent.getString("result"); - logger.info("test02GetNewFilterContainAddress_id:" + responseContent.getString("result")); + @Test( + enabled = true, + description = "Eth api of eth_newFilter contains address,fromBlock and toBlock.") + public void test02GetNewFilterContainAddress() { + if (blockNumForTrc20 - 10 < 0) { + fromBlock = "0"; + } else { + fromBlock = "0x" + Integer.toHexString(blockNumForTrc20 - 10); } + toBlock = "0x" + Integer.toHexString(blockNumForTrc20 + 10); + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test02GetNewFilterContainAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test02GetNewFilterContainAddress_responseContent" + responseContent); + newFilterResultIdfrom01 = responseContent.getString("result"); + logger.info("test02GetNewFilterContainAddress_id:" + responseContent.getString("result")); + } - @Test( - enabled = true, - description = "Eth api of eth_newFilter contains topic fromBlock and toBlock.") - public void test03GetNewFilterContainTopic() { - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - logger.info("blockHash:" + responseContent.getString("blockID")); - blockHash = responseContent.getString("blockID"); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - JsonObject paramBody = new JsonObject(); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test03GetNewFilterContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test03GetNewFilterContainTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - newFilterResultIdfrom02 = responseContent.getString("result"); - logger.info("test03GetNewFilterContainTopic_id:" + newFilterResultIdfrom02); - } + @Test( + enabled = true, + description = "Eth api of eth_newFilter contains topic fromBlock and toBlock.") + public void test03GetNewFilterContainTopic() { + response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNumForTrc20); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + logger.info("blockHash:" + responseContent.getString("blockID")); + blockHash = responseContent.getString("blockID"); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + JsonObject paramBody = new JsonObject(); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test03GetNewFilterContainTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test03GetNewFilterContainTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + newFilterResultIdfrom02 = responseContent.getString("result"); + logger.info("test03GetNewFilterContainTopic_id:" + newFilterResultIdfrom02); + } - @Test(enabled = true, description = "Eth api of eth_newFilter contains topic and address.") - public void test04GetNewFilterContainsTopicAndAddress() { + @Test(enabled = true, description = "Eth api of eth_newFilter contains topic and address.") + public void test04GetNewFilterContainsTopicAndAddress() { - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test04GetNewFilterContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test04GetNewFilterContainsTopicAndAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test04GetNewFilterContainsTopicAndAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test04GetNewFilterContainsTopicAndAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_newFilter only contain topic and blockHash.") - public void test05GetNewFilterOnlyContainTopic() throws InterruptedException { - JsonObject paramBody = new JsonObject(); - paramBody.addProperty("blockHash", blockHash); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - paramBody.add("topics", topicArray); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test05GetNewFilterOnlyContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test05GetNewFilterOnlyContainTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + @Test(enabled = true, description = "Eth api of eth_newFilter only contain topic and blockHash.") + public void test05GetNewFilterOnlyContainTopic() throws InterruptedException { + JsonObject paramBody = new JsonObject(); + paramBody.addProperty("blockHash", blockHash); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + paramBody.add("topics", topicArray); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test05GetNewFilterOnlyContainTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test05GetNewFilterOnlyContainTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_newFilter which only contains blockHash.") - public void test06GetNewFilterHasOnlyBlockHash() throws InterruptedException { - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - String blockHash = responseContent.getString("blockID"); - Thread.sleep(30000); - JsonObject paramBody = new JsonObject(); - paramBody.addProperty("blockHash", blockHash); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test06GetNewFilterHasOnlyBlockHash_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test06GetNewFilterHasOnlyBlockHash_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + @Test(enabled = true, description = "Eth api of eth_newFilter which only contains blockHash.") + public void test06GetNewFilterHasOnlyBlockHash() throws InterruptedException { + response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); + responseContent = HttpMethed.parseResponseContent(response); + String blockHash = responseContent.getString("blockID"); + Thread.sleep(30000); + JsonObject paramBody = new JsonObject(); + paramBody.addProperty("blockHash", blockHash); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test06GetNewFilterHasOnlyBlockHash_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test06GetNewFilterHasOnlyBlockHash_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_newFilter check new and after block.") - public void test07GetNewFilterCheckNewBlock() { - JsonObject paramBody = new JsonObject(); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - paramBody.add("topics", topicArray); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test07GetNewFilterCheckNewBlock_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test07GetNewFilterCheckNewBlock_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + @Test(enabled = true, description = "Eth api of eth_newFilter check new and after block.") + public void test07GetNewFilterCheckNewBlock() { + JsonObject paramBody = new JsonObject(); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + paramBody.add("topics", topicArray); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test07GetNewFilterCheckNewBlock_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test07GetNewFilterCheckNewBlock_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_newBlockFilter") - public void test08GetEthNewBlockFilter() { + @Test(enabled = true, description = "Eth api of eth_newBlockFilter") + public void test08GetEthNewBlockFilter() { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test08GetEthNewBlockFilter_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test08GetEthNewBlockFilter_responseContent:" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test08GetEthNewBlockFilter_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test08GetEthNewBlockFilter_responseContent:" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_getFilterChanges has less 20 elements.") - public void test09GetFilterChanges() { + @Test(enabled = true, description = "Eth api of eth_getFilterChanges has less 20 elements.") + public void test09GetFilterChanges() { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); - String ethNewBlockFilterResult = responseContent.get("result").toString(); - logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); - String newFilterId = responseContent.getString("result"); - logger.info("newFilterId:" + newFilterId); - params = new JsonArray(); - params.add(newFilterId); - requestBody = getJsonRpcBody("eth_getFilterChanges", params); - logger.info("test09GetFilterChanges_requestBody: " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test09GetFilterChanges_responseContent:" + responseContent); - Assert.assertEquals("[]", responseContent.getString("result")); - } + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); + String ethNewBlockFilterResult = responseContent.get("result").toString(); + logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); + String newFilterId = responseContent.getString("result"); + logger.info("newFilterId:" + newFilterId); + params = new JsonArray(); + params.add(newFilterId); + requestBody = getJsonRpcBody("eth_getFilterChanges", params); + logger.info("test09GetFilterChanges_requestBody: " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test09GetFilterChanges_responseContent:" + responseContent); + Assert.assertEquals("[]", responseContent.getString("result")); + } - @Test( - enabled = true, - description = "Eth api of eth_getLogs contains address ,fromBlock and toBlock.") - public void test10GetLogsOnlyContainAddress() { - JsonArray addressArray = new JsonArray(); - logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); - addressArray.add(contractTrc20AddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - logger.info("blockNumForTrc20:" + blockNumForTrc20); - paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 20))); - paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 20))); - JsonArray params = new JsonArray(); - params.add(paramBody); - HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode, httpsolidityNode); - JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); - logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test10GetLogsOnlyContainAddress_responseContent:" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - String address = - responseContent.getJSONArray("result").getJSONObject(0).getString("address").substring(2); - Assert.assertEquals(address, contractTrc20AddressFrom58.substring(2)); - topic0 = responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); - } + @Test( + enabled = true, + description = "Eth api of eth_getLogs contains address ,fromBlock and toBlock.") + public void test10GetLogsOnlyContainAddress() { + JsonArray addressArray = new JsonArray(); + logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); + addressArray.add(contractTrc20AddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + logger.info("blockNumForTrc20:" + blockNumForTrc20); + paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 20))); + paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 20))); + JsonArray params = new JsonArray(); + params.add(paramBody); + HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode, httpsolidityNode); + JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); + logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test10GetLogsOnlyContainAddress_responseContent:" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + String address = + responseContent.getJSONArray("result").getJSONObject(0).getString("address").substring(2); + Assert.assertEquals(address, contractTrc20AddressFrom58.substring(2)); + topic0 = responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); + } - @Test(enabled = true, description = "Eth api of eth_getLogs both contains topic and address.") - public void test11GetLogsContainsTopicAndAddress() { - JsonArray topicArray = new JsonArray(); - topicArray.add(topic0); - JsonObject paramBody = new JsonObject(); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 10))); - paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 10))); - JsonArray params = new JsonArray(); - params.add(paramBody); - HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode, httpsolidityNode); - JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); - logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test11GetLogsContainsTopicAndAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - String topicFromResult = - responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); - Assert.assertEquals(topicFromResult, topic0); - } + @Test(enabled = true, description = "Eth api of eth_getLogs both contains topic and address.") + public void test11GetLogsContainsTopicAndAddress() { + JsonArray topicArray = new JsonArray(); + topicArray.add(topic0); + JsonObject paramBody = new JsonObject(); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 10))); + paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 10))); + JsonArray params = new JsonArray(); + params.add(paramBody); + HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode, httpsolidityNode); + JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); + logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test11GetLogsContainsTopicAndAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + String topicFromResult = + responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); + Assert.assertEquals(topicFromResult, topic0); + } - @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") - public void test12GetFilterLogsContainsAddress() { + @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") + public void test12GetFilterLogsContainsAddress() { - JsonArray params = new JsonArray(); - params.add(newFilterResultIdfrom01); - JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); - logger.info("test12GetFilterLogsContainsAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test12GetFilterLogsContainsAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + JsonArray params = new JsonArray(); + params.add(newFilterResultIdfrom01); + JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); + logger.info("test12GetFilterLogsContainsAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test12GetFilterLogsContainsAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") - public void test13GetFilterLogsContainsTopic() { + @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") + public void test13GetFilterLogsContainsTopic() { - JsonArray params = new JsonArray(); - params.add(newFilterResultIdfrom02); - JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); - logger.info("test13GetFilterLogsContainsTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test13GetFilterLogsContainsTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } + JsonArray params = new JsonArray(); + params.add(newFilterResultIdfrom02); + JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); + logger.info("test13GetFilterLogsContainsTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test13GetFilterLogsContainsTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } - @Test( - enabled = true, - description = - "Eth api of eth_uninstallFilter which method is eth_newFilter" - + " and params has one element ") - public void test14EthUninstallFilter() { - // create ID - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.addProperty("fromBlock", "0x1f8b6a7"); - paramBody.addProperty("toBlock", "0x1f8b6a7"); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test14_newfilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_newfilter_responseContentr" + responseContent); - String ethNewFilterResult = responseContent.get("result").toString(); - logger.info("EthNewFilterResult:" + ethNewFilterResult); - Assert.assertNotNull(responseContent.getString("result")); + @Test( + enabled = true, + description = + "Eth api of eth_uninstallFilter which method is eth_newFilter" + + " and params has one element ") + public void test14EthUninstallFilter() { + // create ID + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.addProperty("fromBlock", "0x1f8b6a7"); + paramBody.addProperty("toBlock", "0x1f8b6a7"); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test14_newfilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_newfilter_responseContentr" + responseContent); + String ethNewFilterResult = responseContent.get("result").toString(); + logger.info("EthNewFilterResult:" + ethNewFilterResult); + Assert.assertNotNull(responseContent.getString("result")); - // verify ID invalid + // verify ID invalid - // first time - params = new JsonArray(); - params.add(responseContent.get("result").toString()); - requestBody = getJsonRpcBody("eth_uninstallFilter", params); - logger.info("test14_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_eth_uninstallFilter_responseContentr_first" + responseContent); - Assert.assertEquals(responseContent.get("result"), true); - // second time - logger.info("test14_eth_uninstallFilter_second " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_eth_uninstallFilter_responseContentr_second " + responseContent); - Assert.assertEquals( - responseContent.getJSONObject("error").getString("message"), "filter not found"); + // first time + params = new JsonArray(); + params.add(responseContent.get("result").toString()); + requestBody = getJsonRpcBody("eth_uninstallFilter", params); + logger.info("test14_eth_uninstallFilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_eth_uninstallFilter_responseContentr_first" + responseContent); + Assert.assertEquals(responseContent.get("result"), true); + // second time + logger.info("test14_eth_uninstallFilter_second " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_eth_uninstallFilter_responseContentr_second " + responseContent); + Assert.assertEquals( + responseContent.getJSONObject("error").getString("message"), "filter not found"); - // query getFilterChanges to verify ID has invalid - params = new JsonArray(); - params.add(ethNewFilterResult); - requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14EthUninstallFilter_responseContent" + responseContent); - String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; - Assert.assertEquals(responseContent.get("error").toString(), expectResult); - } + // query getFilterChanges to verify ID has invalid + params = new JsonArray(); + params.add(ethNewFilterResult); + requestBody = getJsonRpcBody("getFilterChanges", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14EthUninstallFilter_responseContent" + responseContent); + String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; + Assert.assertEquals(responseContent.get("error").toString(), expectResult); + } - @Test( - enabled = true, - description = - "Eth api of eth_uninstallFilter which method is eth_newBlockFilter" - + " and params has one element ") - public void test15EthUninstallFilter() { - // create ID + @Test( + enabled = true, + description = + "Eth api of eth_uninstallFilter which method is eth_newBlockFilter" + + " and params has one element ") + public void test15EthUninstallFilter() { + // create ID - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); - String ethNewBlockFilterResult = responseContent.get("result").toString(); - logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); - Assert.assertNotNull(responseContent.getString("result")); + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); + String ethNewBlockFilterResult = responseContent.get("result").toString(); + logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); + Assert.assertNotNull(responseContent.getString("result")); - // verify ID invalid - // first time - params = new JsonArray(); - params.add(responseContent.get("result").toString()); - requestBody = getJsonRpcBody("eth_uninstallFilter", params); - logger.info("test15_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15_eth_uninstallFilter_responseContentr_first" + responseContent); - Assert.assertEquals(responseContent.get("result"), true); - // second time - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15_eth_uninstallFilter_responseContentr_second" + responseContent); - Assert.assertEquals( - responseContent.getJSONObject("error").getString("message"), "filter not found"); - // query getFilterChanges to verify ID has invalid - params = new JsonArray(); - params.add(ethNewBlockFilterResult); - requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_responseContent" + responseContent); - String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; - Assert.assertEquals(responseContent.get("error").toString(), expectResult); - } + // verify ID invalid + // first time + params = new JsonArray(); + params.add(responseContent.get("result").toString()); + requestBody = getJsonRpcBody("eth_uninstallFilter", params); + logger.info("test15_eth_uninstallFilter " + requestBody); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15_eth_uninstallFilter_responseContentr_first" + responseContent); + Assert.assertEquals(responseContent.get("result"), true); + // second time + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15_eth_uninstallFilter_responseContentr_second" + responseContent); + Assert.assertEquals( + responseContent.getJSONObject("error").getString("message"), "filter not found"); + // query getFilterChanges to verify ID has invalid + params = new JsonArray(); + params.add(ethNewBlockFilterResult); + requestBody = getJsonRpcBody("getFilterChanges", params); + response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_responseContent" + responseContent); + String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; + Assert.assertEquals(responseContent.get("error").toString(), expectResult); + } } From 2dd95e85ced503493c7bcf6b901c4aac4986f693 Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Tue, 14 Dec 2021 18:13:54 +0800 Subject: [PATCH 22/24] fix --- .../common/client/utils/JsonRpcBase.java | 724 +++++++++--------- 1 file changed, 353 insertions(+), 371 deletions(-) diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java index f017feb7478..9d5be26802f 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java @@ -45,379 +45,361 @@ @Slf4j public class JsonRpcBase { - public final String foundationAccountKey = - Configuration.getByPath("testng.conf").getString("foundationAccount.key1"); - public final byte[] foundationAccountAddress = PublicMethed.getFinalAddress(foundationAccountKey); - - public static final String jsonRpcOwnerKey = - Configuration.getByPath("testng.conf").getString("defaultParameter.jsonRpcOwnerKey"); - public static final byte[] jsonRpcOwnerAddress = PublicMethed.getFinalAddress(jsonRpcOwnerKey); - public static final String jsonRpcOwnerAddressString = - PublicMethed.getAddressString(jsonRpcOwnerKey); - public static String jsonRpcNode = - Configuration.getByPath("testng.conf").getStringList("jsonRpcNode.ip.list").get(0); - public static String jsonRpcNodeForSolidity = - Configuration.getByPath("testng.conf").getStringList("jsonRpcNode.ip.list").get(1); - public static String httpFullNode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(0); - public static String httpsolidityNode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(2); - public static String ethHttpsNode = - Configuration.getByPath("testng.conf").getStringList("ethHttpsNode.host.list").get(0); - - public ManagedChannel channelFull = null; - public WalletGrpc.WalletBlockingStub blockingStubFull = null; - public ManagedChannel channelSolidity = null; - public ManagedChannel channelPbft = null; - public static String data = null; - public String paramString = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - public String fullnode = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(0); - - public static long maxFeeLimit = - Configuration.getByPath("testng.conf").getLong("defaultParameter.maxFeeLimit"); - public static String trc20AddressByteString; - public static String trc20AddressHex; - public static String contractAddressFrom58; - public static String contractTrc20AddressFrom58; - public static String contractAddressFromHex; - public static ByteString shieldAddressByteString; - public static byte[] shieldAddressByte; - public static String shieldAddress; - public static String deployTrc20Txid; - public static String deployShieldTxid; - public static String mint = "mint(uint256,bytes32[9],bytes32[2],bytes32[21])"; - public static String transfer = - "transfer(bytes32[10][],bytes32[2][],bytes32[9][],bytes32[2],bytes32[21][])"; - public static String burn = - "burn(bytes32[10],bytes32[2],uint256,bytes32[2],address," - + "bytes32[3],bytes32[9][],bytes32[21][])"; - public Wallet wallet = new Wallet(); - static HttpResponse response; - static HttpPost httppost; - static JSONObject responseContent; - public static Integer scalingFactorLogarithm = 0; - public static Long totalSupply = 1000000000000L; - public static String name = "jsonrpc-test"; - public static String jsonRpcAssetId; - public static Integer blockNum; - public static Integer blockNumForTrc20; - public static String blockNumHex; - public static String blockId; - public static String txid; - public static String trc20Txid; - - /** - * constructor. - */ - @BeforeSuite(enabled = true, description = "Deploy json rpc test case resource") - public void deployJsonRpcUseResource() throws Exception { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue( - PublicMethed.sendcoin( - jsonRpcOwnerAddress, - 2048000000L, - foundationAccountAddress, - foundationAccountKey, - blockingStubFull)); - if (PublicMethed.queryAccount(jsonRpcOwnerAddress, blockingStubFull).getAssetV2Count() == 0L) { - Assert.assertTrue( - PublicMethed.sendcoin( - jsonRpcOwnerAddress, - 2048000000L, - foundationAccountAddress, - foundationAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // Create a new Asset Issue - Assert.assertTrue( - PublicMethed.createAssetIssue( - jsonRpcOwnerAddress, - name, - totalSupply, - 1, - 1, - System.currentTimeMillis() + 5000, - System.currentTimeMillis() + 1000000000, - 1, - "description", - "urlurlurl", - 2000L, - 2000L, - 1L, - 1L, - jsonRpcOwnerKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - response = HttpMethed.getAccount(httpFullNode, jsonRpcOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - jsonRpcAssetId = responseContent.getString("asset_issued_ID"); - - deployContract(); - triggerContract(); - deployTrc20Contract(); + public final String foundationAccountKey = + Configuration.getByPath("testng.conf").getString("foundationAccount.key1"); + public final byte[] foundationAccountAddress = PublicMethed.getFinalAddress(foundationAccountKey); + + public static final String jsonRpcOwnerKey = + Configuration.getByPath("testng.conf").getString("defaultParameter.jsonRpcOwnerKey"); + public static final byte[] jsonRpcOwnerAddress = PublicMethed.getFinalAddress(jsonRpcOwnerKey); + public static final String jsonRpcOwnerAddressString = + PublicMethed.getAddressString(jsonRpcOwnerKey); + public static String jsonRpcNode = + Configuration.getByPath("testng.conf").getStringList("jsonRpcNode.ip.list").get(0); + public static String jsonRpcNodeForSolidity = + Configuration.getByPath("testng.conf").getStringList("jsonRpcNode.ip.list").get(1); + public static String httpFullNode = + Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(0); + public static String httpsolidityNode = + Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(2); + public static String ethHttpsNode = + Configuration.getByPath("testng.conf").getStringList("ethHttpsNode.host.list").get(0); + + public ManagedChannel channelFull = null; + public WalletGrpc.WalletBlockingStub blockingStubFull = null; + public ManagedChannel channelSolidity = null; + public ManagedChannel channelPbft = null; + public static String data = null; + public String paramString = null; + public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; + public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; + public String fullnode = + Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(0); + + public static long maxFeeLimit = + Configuration.getByPath("testng.conf").getLong("defaultParameter.maxFeeLimit"); + public static String trc20AddressByteString; + public static String trc20AddressHex; + public static String contractAddressFrom58; + public static String contractTrc20AddressFrom58; + public static String contractAddressFromHex; + public static ByteString shieldAddressByteString; + public static byte[] shieldAddressByte; + public static String shieldAddress; + public static String deployTrc20Txid; + public static String deployShieldTxid; + public static String mint = "mint(uint256,bytes32[9],bytes32[2],bytes32[21])"; + public static String transfer = + "transfer(bytes32[10][],bytes32[2][],bytes32[9][],bytes32[2],bytes32[21][])"; + public static String burn = + "burn(bytes32[10],bytes32[2],uint256,bytes32[2],address," + + "bytes32[3],bytes32[9][],bytes32[21][])"; + public Wallet wallet = new Wallet(); + static HttpResponse response; + static HttpPost httppost; + static JSONObject responseContent; + public static Integer scalingFactorLogarithm = 0; + public static Long totalSupply = 1000000000000L; + public static String name = "jsonrpc-test"; + public static String jsonRpcAssetId; + public static Integer blockNum; + public static Integer blockNumForTrc20; + public static String blockNumHex; + public static String blockId; + public static String txid; + public static String trc20Txid; + + /** constructor. */ + @BeforeSuite(enabled = true, description = "Deploy json rpc test case resource") + public void deployJsonRpcUseResource() throws Exception { + Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); + blockingStubFull = WalletGrpc.newBlockingStub(channelFull); + Assert.assertTrue( + PublicMethed.sendcoin( + jsonRpcOwnerAddress, + 2048000000L, + foundationAccountAddress, + foundationAccountKey, + blockingStubFull)); + if (PublicMethed.queryAccount(jsonRpcOwnerAddress, blockingStubFull).getAssetV2Count() == 0L) { + Assert.assertTrue( + PublicMethed.sendcoin( + jsonRpcOwnerAddress, + 2048000000L, + foundationAccountAddress, + foundationAccountKey, + blockingStubFull)); + PublicMethed.waitProduceNextBlock(blockingStubFull); + + // Create a new Asset Issue + Assert.assertTrue( + PublicMethed.createAssetIssue( + jsonRpcOwnerAddress, + name, + totalSupply, + 1, + 1, + System.currentTimeMillis() + 5000, + System.currentTimeMillis() + 1000000000, + 1, + "description", + "urlurlurl", + 2000L, + 2000L, + 1L, + 1L, + jsonRpcOwnerKey, + blockingStubFull)); + + PublicMethed.waitProduceNextBlock(blockingStubFull); } - /** - * constructor. - */ - public void deployContract() throws Exception { - final Long beforeTokenBalance = - PublicMethed.getAssetBalanceByAssetId( - ByteString.copyFromUtf8(jsonRpcAssetId), jsonRpcOwnerKey, blockingStubFull); - - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("name", "transferTokenContract"); - param.addProperty("gas", "0x245498"); - String filePath = "./src/test/resources/soliditycode/contractTrcToken001.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - System.out.println("CODE:" + code); - String abi = retMap.get("abI").toString(); - System.out.println("abi:" + abi); - - param.addProperty("abi", abi); - param.addProperty("data", code); - param.addProperty("consumeUserResourcePercent", 100); - param.addProperty("originEnergyLimit", 11111111111111L); - param.addProperty("value", "0x1f4"); - param.addProperty("tokenId", Long.valueOf(jsonRpcAssetId)); - param.addProperty("tokenValue", 1); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("buildTransaction", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String transactionString = responseContent.getJSONObject("result").getString("transaction"); - String transactionSignString = - HttpMethed.gettransactionsign(httpFullNode, transactionString, jsonRpcOwnerKey); - - responseContent = HttpMethed.parseStringContent(transactionString); - final String txid = responseContent.getString("txID"); - response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); - org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpFullNode); - Long afterTokenBalance = - PublicMethed.getAssetBalanceByAssetId( - ByteString.copyFromUtf8(jsonRpcAssetId), jsonRpcOwnerKey, blockingStubFull); - - org.junit.Assert.assertEquals(beforeTokenBalance - afterTokenBalance, 1L); - - response = HttpMethed.getTransactionById(httpFullNode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - org.junit.Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); - contractAddressFrom58 = responseContent.getString("contract_address"); - logger.info("contractAddressFrom58:" + contractAddressFrom58); + response = HttpMethed.getAccount(httpFullNode, jsonRpcOwnerAddress); + responseContent = HttpMethed.parseResponseContent(response); + jsonRpcAssetId = responseContent.getString("asset_issued_ID"); + + deployContract(); + triggerContract(); + deployTrc20Contract(); + } + + /** constructor. */ + public void deployContract() throws Exception { + final Long beforeTokenBalance = + PublicMethed.getAssetBalanceByAssetId( + ByteString.copyFromUtf8(jsonRpcAssetId), jsonRpcOwnerKey, blockingStubFull); + + JsonObject param = new JsonObject(); + param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); + param.addProperty("name", "transferTokenContract"); + param.addProperty("gas", "0x245498"); + String filePath = "./src/test/resources/soliditycode/contractTrcToken001.sol"; + String contractName = "tokenTest"; + HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); + + String code = retMap.get("byteCode").toString(); + System.out.println("CODE:" + code); + String abi = retMap.get("abI").toString(); + System.out.println("abi:" + abi); + + param.addProperty("abi", abi); + param.addProperty("data", code); + param.addProperty("consumeUserResourcePercent", 100); + param.addProperty("originEnergyLimit", 11111111111111L); + param.addProperty("value", "0x1f4"); + param.addProperty("tokenId", Long.valueOf(jsonRpcAssetId)); + param.addProperty("tokenValue", 1); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("buildTransaction", params); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String transactionString = responseContent.getJSONObject("result").getString("transaction"); + String transactionSignString = + HttpMethed.gettransactionsign(httpFullNode, transactionString, jsonRpcOwnerKey); + + responseContent = HttpMethed.parseStringContent(transactionString); + final String txid = responseContent.getString("txID"); + response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); + org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); + + HttpMethed.waitToProduceOneBlock(httpFullNode); + Long afterTokenBalance = + PublicMethed.getAssetBalanceByAssetId( + ByteString.copyFromUtf8(jsonRpcAssetId), jsonRpcOwnerKey, blockingStubFull); + + org.junit.Assert.assertEquals(beforeTokenBalance - afterTokenBalance, 1L); + + response = HttpMethed.getTransactionById(httpFullNode, txid); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + org.junit.Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); + contractAddressFrom58 = responseContent.getString("contract_address"); + logger.info("contractAddressFrom58:" + contractAddressFrom58); + } + + /** constructor. */ + public void triggerContract() throws Exception { + final Long beforeTokenBalance = + PublicMethed.getAssetBalanceByAssetId( + ByteString.copyFromUtf8(jsonRpcAssetId), foundationAccountKey, blockingStubFull); + final Long beforeBalance = HttpMethed.getBalance(httpFullNode, jsonRpcOwnerAddress); + JsonObject param = new JsonObject(); + param.addProperty("from", "0x" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2)); + param.addProperty("to", "0x" + contractAddressFrom58); + + String addressParam = + "000000000000000000000000" + + ByteArray.toHexString(foundationAccountAddress).substring(2); // [0,3) + + String tokenIdParam = + "00000000000000000000000000000000000000000000000000000000000" + + Integer.toHexString(Integer.valueOf(jsonRpcAssetId)); + + String tokenValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; + paramString = addressParam + tokenIdParam + tokenValueParam; + logger.info("paramString:" + paramString); + + String selector = "TransferTokenTo(address,trcToken,uint256)"; + // exit(1); + param.addProperty("data", "0x" + Util.parseMethod(selector, paramString)); + data = "0x" + Util.parseMethod(selector, paramString); + param.addProperty("gas", "0x245498"); + param.addProperty("value", "0x1389"); + param.addProperty("tokenId", Long.valueOf(jsonRpcAssetId)); + param.addProperty("tokenValue", 1); + JsonArray params = new JsonArray(); + params.add(param); + JsonObject requestBody = getJsonRpcBody("buildTransaction", params); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + String transactionString = responseContent.getJSONObject("result").getString("transaction"); + logger.info("transactionString : " + transactionString); + String transactionSignString = + HttpMethed.gettransactionsign(httpFullNode, transactionString, jsonRpcOwnerKey); + logger.info("transactionSignString:" + transactionSignString); + responseContent = HttpMethed.parseStringContent(transactionString); + txid = responseContent.getString("txID"); + logger.info("triggerTxid:" + txid); + + response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); + logger.info("response:" + response); + HttpMethed.verificationResult(response); + org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); + + HttpMethed.waitToProduceOneBlock(httpFullNode); + Long afterTokenBalance = + PublicMethed.getAssetBalanceByAssetId( + ByteString.copyFromUtf8(jsonRpcAssetId), foundationAccountKey, blockingStubFull); + Long afterBalance = HttpMethed.getBalance(httpFullNode, jsonRpcOwnerAddress); + + org.junit.Assert.assertEquals(beforeTokenBalance - afterTokenBalance, -1L); + org.junit.Assert.assertTrue(beforeBalance - afterBalance >= 5000); + + blockNum = + (int) (PublicMethed.getTransactionInfoById(txid, blockingStubFull).get().getBlockNumber()); + PublicMethed.waitProduceNextBlock(blockingStubFull); + response = HttpMethed.getBlockByNum(httpFullNode, blockNum); + org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + blockId = responseContent.get("blockID").toString(); + } + + /** constructor. */ + public void deployTrc20Contract() throws InterruptedException { + String contractName = "shieldTrc20Token"; + + String abi = Configuration.getByPath("testng.conf").getString("abi.abi_shieldTrc20Token"); + String code = Configuration.getByPath("testng.conf").getString("code.code_shieldTrc20Token"); + String constructorStr = "constructor(uint256,string,string)"; + String data = totalSupply.toString() + "," + "\"TokenTRC20\"" + "," + "\"zen20\""; + logger.info("data:" + data); + deployTrc20Txid = + PublicMethed.deployContractWithConstantParame( + contractName, + abi, + code, + constructorStr, + data, + "", + maxFeeLimit, + 0L, + 100, + null, + jsonRpcOwnerKey, + jsonRpcOwnerAddress, + blockingStubFull); + + PublicMethed.waitProduceNextBlock(blockingStubFull); + logger.info("deployTrc20Txid:" + deployTrc20Txid); + response = HttpMethed.getTransactionById(httpFullNode, deployTrc20Txid); + responseContent = HttpMethed.parseResponseContent(response); + HttpMethed.printJsonContent(responseContent); + org.junit.Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); + contractTrc20AddressFrom58 = responseContent.getString("contract_address"); + logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); + + // NewFilterId = createNewFilterId(); + + Optional infoById = + PublicMethed.getTransactionInfoById(deployTrc20Txid, blockingStubFull); + + trc20AddressHex = ByteArray.toHexString(infoById.get().getContractAddress().toByteArray()); + byte[] trc20Address = infoById.get().getContractAddress().toByteArray(); + + String selector = "transfer(address,uint256)"; + String addressParam = + "000000000000000000000000" + + ByteArray.toHexString(foundationAccountAddress).substring(2); // [0,3) + String transferValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; + String paramString = addressParam + transferValueParam; + trc20Txid = + PublicMethed.triggerContract( + trc20Address, + selector, + paramString, + true, + 0, + maxFeeLimit, + "0", + 0, + jsonRpcOwnerAddress, + jsonRpcOwnerKey, + blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + blockNumForTrc20 = + (int) + (PublicMethed.getTransactionInfoById(trc20Txid, blockingStubFull) + .get() + .getBlockNumber()); + } + + /** constructor. */ + public static HttpResponse getEthHttps(String ethHttpsNode, JsonObject jsonRpcObject) { + try { + String requestUrl = "https://" + ethHttpsNode + "/v3/dfb752dd45204b8daae74249f4653584"; + response = HttpMethed.createConnect(requestUrl, jsonRpcObject); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; } - - /** - * constructor. - */ - public void triggerContract() throws Exception { - final Long beforeTokenBalance = - PublicMethed.getAssetBalanceByAssetId( - ByteString.copyFromUtf8(jsonRpcAssetId), foundationAccountKey, blockingStubFull); - final Long beforeBalance = HttpMethed.getBalance(httpFullNode, jsonRpcOwnerAddress); - JsonObject param = new JsonObject(); - param.addProperty("from", "0x" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2)); - param.addProperty("to", "0x" + contractAddressFrom58); - - String addressParam = - "000000000000000000000000" - + ByteArray.toHexString(foundationAccountAddress).substring(2); // [0,3) - - String tokenIdParam = - "00000000000000000000000000000000000000000000000000000000000" - + Integer.toHexString(Integer.valueOf(jsonRpcAssetId)); - - String tokenValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; - paramString = addressParam + tokenIdParam + tokenValueParam; - logger.info("paramString:" + paramString); - - String selector = "TransferTokenTo(address,trcToken,uint256)"; - // exit(1); - param.addProperty("data", "0x" + Util.parseMethod(selector, paramString)); - data = "0x" + Util.parseMethod(selector, paramString); - param.addProperty("gas", "0x245498"); - param.addProperty("value", "0x1389"); - param.addProperty("tokenId", Long.valueOf(jsonRpcAssetId)); - param.addProperty("tokenValue", 1); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("buildTransaction", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String transactionString = responseContent.getJSONObject("result").getString("transaction"); - logger.info("transactionString : " + transactionString); - String transactionSignString = - HttpMethed.gettransactionsign(httpFullNode, transactionString, jsonRpcOwnerKey); - logger.info("transactionSignString:" + transactionSignString); - responseContent = HttpMethed.parseStringContent(transactionString); - txid = responseContent.getString("txID"); - logger.info("triggerTxid:" + txid); - - response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); - logger.info("response:" + response); - HttpMethed.verificationResult(response); - org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpFullNode); - Long afterTokenBalance = - PublicMethed.getAssetBalanceByAssetId( - ByteString.copyFromUtf8(jsonRpcAssetId), foundationAccountKey, blockingStubFull); - Long afterBalance = HttpMethed.getBalance(httpFullNode, jsonRpcOwnerAddress); - - org.junit.Assert.assertEquals(beforeTokenBalance - afterTokenBalance, -1L); - org.junit.Assert.assertTrue(beforeBalance - afterBalance >= 5000); - - blockNum = - (int) (PublicMethed.getTransactionInfoById(txid, blockingStubFull).get().getBlockNumber()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - response = HttpMethed.getBlockByNum(httpFullNode, blockNum); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - blockId = responseContent.get("blockID").toString(); - } - - /** - * constructor. - */ - public void deployTrc20Contract() throws InterruptedException { - String contractName = "shieldTrc20Token"; - - String abi = Configuration.getByPath("testng.conf").getString("abi.abi_shieldTrc20Token"); - String code = Configuration.getByPath("testng.conf").getString("code.code_shieldTrc20Token"); - String constructorStr = "constructor(uint256,string,string)"; - String data = totalSupply.toString() + "," + "\"TokenTRC20\"" + "," + "\"zen20\""; - logger.info("data:" + data); - deployTrc20Txid = - PublicMethed.deployContractWithConstantParame( - contractName, - abi, - code, - constructorStr, - data, - "", - maxFeeLimit, - 0L, - 100, - null, - jsonRpcOwnerKey, - jsonRpcOwnerAddress, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("deployTrc20Txid:" + deployTrc20Txid); - response = HttpMethed.getTransactionById(httpFullNode, deployTrc20Txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - org.junit.Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); - contractTrc20AddressFrom58 = responseContent.getString("contract_address"); - logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); - - // NewFilterId = createNewFilterId(); - - Optional infoById = - PublicMethed.getTransactionInfoById(deployTrc20Txid, blockingStubFull); - - trc20AddressHex = ByteArray.toHexString(infoById.get().getContractAddress().toByteArray()); - byte[] trc20Address = infoById.get().getContractAddress().toByteArray(); - - String selector = "transfer(address,uint256)"; - String addressParam = - "000000000000000000000000" - + ByteArray.toHexString(foundationAccountAddress).substring(2); // [0,3) - String transferValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; - String paramString = addressParam + transferValueParam; - trc20Txid = - PublicMethed.triggerContract( - trc20Address, - selector, - paramString, - true, - 0, - maxFeeLimit, - "0", - 0, - jsonRpcOwnerAddress, - jsonRpcOwnerKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - blockNumForTrc20 = - (int) - (PublicMethed.getTransactionInfoById(trc20Txid, blockingStubFull) - .get() - .getBlockNumber()); - } - - /** - * constructor. - */ - public static HttpResponse getEthHttps(String ethHttpsNode, JsonObject jsonRpcObject) { - try { - String requestUrl = "https://" + ethHttpsNode + "/v3/dfb752dd45204b8daae74249f4653584"; - response = HttpMethed.createConnect(requestUrl, jsonRpcObject); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getJsonRpc(String jsonRpcNode, JsonObject jsonRpcObject) { - try { - String requestUrl = "http://" + jsonRpcNode + "/jsonrpc"; - response = HttpMethed.createConnect(requestUrl, jsonRpcObject); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static JsonObject getJsonRpcBody(String method) { - return getJsonRpcBody(method, new JsonArray(), 1); - } - - /** - * constructor. - */ - public static JsonObject getJsonRpcBody(String method, JsonArray params) { - return getJsonRpcBody(method, params, 1); - } - - /** - * constructor. - */ - public static JsonObject getJsonRpcBody(String method, JsonArray params, Integer id) { - JsonObject jsonObject = new JsonObject(); - jsonObject.addProperty("jsonrpc", "2.0"); - jsonObject.addProperty("method", method); - jsonObject.add("params", params); - jsonObject.addProperty("id", id); - - return jsonObject; + return response; + } + + /** constructor. */ + public static HttpResponse getJsonRpc(String jsonRpcNode, JsonObject jsonRpcObject) { + try { + String requestUrl = "http://" + jsonRpcNode + "/jsonrpc"; + response = HttpMethed.createConnect(requestUrl, jsonRpcObject); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; } + return response; + } + + /** constructor. */ + public static JsonObject getJsonRpcBody(String method) { + return getJsonRpcBody(method, new JsonArray(), 1); + } + + /** constructor. */ + public static JsonObject getJsonRpcBody(String method, JsonArray params) { + return getJsonRpcBody(method, params, 1); + } + + /** constructor. */ + public static JsonObject getJsonRpcBody(String method, JsonArray params, Integer id) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("jsonrpc", "2.0"); + jsonObject.addProperty("method", method); + jsonObject.add("params", params); + jsonObject.addProperty("id", id); + + return jsonObject; + } } From c498c3b3f36799b060c4d4d6c070bc9bff9f9da8 Mon Sep 17 00:00:00 2001 From: liqi <1242201319@qq.com> Date: Tue, 14 Dec 2021 18:21:03 +0800 Subject: [PATCH 23/24] add --- .../wallet/onlinestress/ContractEvent001.java | 45 ++++++++++++------- 1 file changed, 29 insertions(+), 16 deletions(-) diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java b/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java index 3013039904b..1b1ca3ab2e9 100644 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java +++ b/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java @@ -3,10 +3,9 @@ import com.alibaba.fastjson.JSONObject; import com.google.gson.JsonArray; import com.google.gson.JsonObject; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.client.HttpClient; import com.google.protobuf.ByteString; import io.grpc.ManagedChannel; +import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import java.io.BufferedReader; import java.io.File; @@ -21,8 +20,10 @@ import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; +import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.util.EntityUtils; @@ -50,8 +51,6 @@ import stest.tron.wallet.common.client.utils.PublicMethed; import zmq.ZMQ.Event; -import static java.lang.Thread.sleep; - @Slf4j public class ContractEvent001 extends JsonRpcBase { @@ -454,9 +453,11 @@ public void test1ContractEventAndLog() { public void testEthGetFilterChanges() throws InterruptedException { ECKey ecKey1 = new ECKey(Utils.getRandom()); byte[] event001Address = ecKey1.getAddress(); + logger.info("event001Address:" + event001Address); String event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); ECKey ecKey2 = new ECKey(Utils.getRandom()); byte[] event002Address = ecKey2.getAddress(); + logger.info("event002Address:" + event002Address); String event002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); PublicMethed.printAddress(event001Key); PublicMethed.printAddress(testKey002); @@ -499,6 +500,7 @@ public void testEthGetFilterChanges() throws InterruptedException { JSONObject responseContent = parseResponseContent(response); long blockBefore = responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); + logger.info("blockBefore:" + blockBefore); Thread.sleep(180000); for (int i = 0; i < 5000; i++) { String txid = @@ -536,10 +538,21 @@ public void testEthGetFilterChanges() throws InterruptedException { totalTransactionsSize += transactionsSize; } - logger.info((int)(Thread.currentThread().getId())+"sumLogs:" + totalTransactionsSize * Long.parseLong(param)); + logger.info( + (int) (Thread.currentThread().getId()) + + "sumLogs:" + + totalTransactionsSize * Long.parseLong(param)); } - public static String[] arr = new String[] {"00", "0x6b5c9c34aae469576dfcde3655c9036d", "0x450de4565abf4434d66948fb2a568608", "0x02a65b2cc37d2d34808a63b50b86e0cd", "0x7474d244cecf3a943bf8ac6dbd7d60fa", "0x4ab110c02b04d7781f774eeffa6432a3"}; + public static String[] arr = + new String[] { + "00", + "0x6b5c9c34aae469576dfcde3655c9036d", + "0x450de4565abf4434d66948fb2a568608", + "0x02a65b2cc37d2d34808a63b50b86e0cd", + "0x7474d244cecf3a943bf8ac6dbd7d60fa", + "0x4ab110c02b04d7781f774eeffa6432a3" + }; @Test( enabled = true, @@ -667,6 +680,7 @@ public static HttpResponse createConnect(String url, JsonObject requestBody) { return response; } + /** constructor. */ public static HttpResponse getJsonRpc(String jsonRpcNode, JsonObject jsonRpcObject) { HttpResponse response; try { @@ -691,16 +705,15 @@ public void testEnergyCostDetail() { req.monitor("inproc://reqmoniter", ZMQ.EVENT_CONNECTED | ZMQ.EVENT_DISCONNECTED); final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); moniter.connect("inproc://reqmoniter"); - new Thread( - new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - }) - .start(); + new Thread(new Runnable() { + public void run() { + while (true) { + Event event = Event.read(moniter.base()); + System.out.println(event.event + " " + event.addr); + } + } + + }).start(); req.connect("tcp://47.94.197.215:55555"); req.setReceiveTimeOut(10000); From 84ba3b39f46543bee443943f934b262c162f328f Mon Sep 17 00:00:00 2001 From: daxinzang1 <280474930@qq.com> Date: Wed, 15 Dec 2021 08:34:32 +0800 Subject: [PATCH 24/24] Turn solidity rpc case to false --- .../stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java index be300775e53..733fe939e7d 100644 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java @@ -742,7 +742,7 @@ public void test25JsonRpcApiTestForEthGetUncleCountByBlockNumber() throws Except Assert.assertEquals(result, "0x0"); } - @Test(enabled = true, description = "Json rpc api of eth_getWork") + @Test(enabled = false, description = "Json rpc api of eth_getWork") public void test26JsonRpcApiTestForEthGetWork() throws Exception { JsonArray params = new JsonArray(); JsonObject requestBody = getJsonRpcBody("eth_getWork", params); @@ -798,7 +798,7 @@ public void test29JsonRpcApiTestForEthProtocolVersion() throws Exception { Assert.assertEquals(protocolVersion1, protocolVersion2); } - @Test(enabled = true, description = "Json rpc api of eth_syncing") + @Test(enabled = false, description = "Json rpc api of eth_syncing") public void test30JsonRpcApiTestForEthSyncing() throws Exception { JsonArray params = new JsonArray(); JsonObject requestBody = getJsonRpcBody("eth_syncing", params); @@ -820,7 +820,7 @@ public void test30JsonRpcApiTestForEthSyncing() throws Exception { Assert.assertTrue(temp.containsKey("highestBlock")); } - @Test(enabled = true, description = "Json rpc api of net_listening") + @Test(enabled = false, description = "Json rpc api of net_listening") public void test31JsonRpcApiTestForNetListening() throws Exception { JsonArray params = new JsonArray(); JsonObject requestBody = getJsonRpcBody("net_listening", params);