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..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 @@ -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; @@ -38,15 +40,29 @@ 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 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(); @@ -56,11 +72,9 @@ public class HttpMethed { httpClient = new DefaultHttpClient(pccm); } - /** - * constructor. - */ - public static HttpResponse updateAccount(String httpNode, byte[] updateAccountAddress, - String accountName, String fromKey) { + /** 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(); @@ -80,17 +94,19 @@ public static HttpResponse updateAccount(String httpNode, byte[] updateAccountAd return response; } - /** - * constructor. - */ - public static HttpResponse setAccountId(String httpNode, byte[] setAccountIdAddress, - String accountId, Boolean visable, String fromKey) { + /** 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( + "owner_address", Base58.encode58Check(PublicMethed.getFinalAddress(fromKey))); userBaseObj2.addProperty("visible", visable); response = createConnect(requestUrl, userBaseObj2); transactionString = EntityUtils.toString(response.getEntity()); @@ -106,12 +122,9 @@ public static HttpResponse setAccountId(String httpNode, byte[] setAccountIdAddr return response; } - - /** - * constructor. - */ - public static HttpResponse updateWitness(String httpNode, byte[] witnessAddress, String updateUrl, - String fromKey) { + /** 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(); @@ -131,12 +144,9 @@ public static HttpResponse updateWitness(String httpNode, byte[] witnessAddress, return response; } - - /** - * constructor. - */ - public static HttpResponse voteWitnessAccount(String httpNode, byte[] ownerAddress, - JsonArray voteArray, String fromKey) { + /** 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(); @@ -157,11 +167,9 @@ public static HttpResponse voteWitnessAccount(String httpNode, byte[] ownerAddre return response; } - /** - * constructor. - */ - public static HttpResponse createAccount(String httpNode, byte[] ownerAddress, - byte[] accountAddress, String fromKey) { + /** 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(); @@ -179,9 +187,7 @@ public static HttpResponse createAccount(String httpNode, byte[] ownerAddress, return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse createWitness(String httpNode, byte[] ownerAddress, String url) { try { final String requestUrl = "http://" + httpNode + "/wallet/createwitness"; @@ -190,9 +196,9 @@ public static HttpResponse createWitness(String httpNode, byte[] ownerAddress, S 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); + // transactionString = EntityUtils.toString(response.getEntity()); + // transactionSignString = gettransactionsign(httpNode,transactionString,fromKey); + // response = broadcastTransaction(httpNode,transactionSignString); } catch (Exception e) { e.printStackTrace(); httppost.releaseConnection(); @@ -201,9 +207,7 @@ public static HttpResponse createWitness(String httpNode, byte[] ownerAddress, S return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse withdrawBalance(String httpNode, byte[] witnessAddress) { try { final String requestUrl = "http://" + httpNode + "/wallet/withdrawbalance"; @@ -211,9 +215,9 @@ public static HttpResponse withdrawBalance(String httpNode, byte[] witnessAddres 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); + // transactionString = EntityUtils.toString(response.getEntity()); + // transactionSignString = gettransactionsign(httpNode,transactionString,fromKey); + // response = broadcastTransaction(httpNode,transactionSignString); } catch (Exception e) { e.printStackTrace(); httppost.releaseConnection(); @@ -222,12 +226,9 @@ public static HttpResponse withdrawBalance(String httpNode, byte[] witnessAddres return response; } - - /** - * constructor. - */ - public static HttpResponse sendCoin(String httpNode, byte[] fromAddress, byte[] toAddress, - Long amount, String fromKey) { + /** 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(); @@ -246,11 +247,14 @@ public static HttpResponse sendCoin(String httpNode, byte[] fromAddress, byte[] return response; } - /** - * constructor. - */ - public static HttpResponse sendCoin(String httpNode, byte[] fromAddress, byte[] toAddress, - Long amount, Integer permissionId, String[] managerKeys) { + /** 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(); @@ -273,8 +277,6 @@ public static HttpResponse sendCoin(String httpNode, byte[] fromAddress, byte[] signResponseContent = parseResponseContent(getSignWeightResponse); logger.info("-----------get Transaction Approved List-----------------"); printJsonContent(signResponseContent); - - } response = broadcastTransaction(httpNode, transactionSignString); } catch (Exception e) { @@ -285,11 +287,14 @@ public static HttpResponse sendCoin(String httpNode, byte[] fromAddress, byte[] return response; } - /** - * constructor. - */ - public static String sendCoin(String httpNode, byte[] fromAddress, byte[] toAddress, Long amount, - String notes, String fromKey) { + /** 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(); @@ -310,11 +315,9 @@ public static String sendCoin(String httpNode, byte[] fromAddress, byte[] toAddr return responseContent.getString("txID"); } - /** - * constructor. - */ - public static String sendCoinGetTxid(String httpNode, byte[] fromAddress, byte[] toAddress, - Long amount, String fromKey) { + /** 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(); @@ -337,11 +340,9 @@ public static String sendCoinGetTxid(String httpNode, byte[] fromAddress, byte[] return responseContent.getString("txID"); } - /** - * constructor. - */ - public static HttpResponse createProposal(String httpNode, byte[] ownerAddress, Long proposalKey, - Long proposalValue, String fromKey) { + /** 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(); @@ -365,11 +366,13 @@ public static HttpResponse createProposal(String httpNode, byte[] ownerAddress, return response; } - /** - * constructor. - */ - public static HttpResponse approvalProposal(String httpNode, byte[] ownerAddress, - Integer proposalId, Boolean isAddApproval, String fromKey) { + /** 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(); @@ -390,11 +393,9 @@ public static HttpResponse approvalProposal(String httpNode, byte[] ownerAddress return response; } - /** - * constructor. - */ - public static HttpResponse deleteProposal(String httpNode, byte[] ownerAddress, - Integer proposalId, String fromKey) { + /** 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(); @@ -414,10 +415,7 @@ public static HttpResponse deleteProposal(String httpNode, byte[] ownerAddress, return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getEnergyPric(String httpNode) { try { final String requestUrl = "http://" + httpNode + "/wallet/getenergyprices"; @@ -429,10 +427,8 @@ public static HttpResponse getEnergyPric(String httpNode) { } return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getChainParameters(String httpNode) { try { final String requestUrl = "http://" + httpNode + "/wallet/getchainparameters"; @@ -445,17 +441,20 @@ public static HttpResponse getChainParameters(String httpNode) { return response; } - /** - * constructor. - */ - public static HttpResponse accountPermissionUpdate(String httpNode, byte[] ownerAddress, - JsonObject ownerObject, JsonObject witnessObject, JsonObject activesObject, String fromKey) { + /** 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("witness", witnessObject); userBaseObj2.add("actives", activesObject); logger.info(userBaseObj2.toString()); response = createConnect(requestUrl, userBaseObj2); @@ -473,12 +472,14 @@ public static HttpResponse accountPermissionUpdate(String httpNode, byte[] owner return response; } - - /** - * constructor. - */ - public static HttpResponse exchangeCreate(String httpNode, byte[] ownerAddress, - String firstTokenId, Long firstTokenBalance, String secondTokenId, Long secondTokenBalance, + /** 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"; @@ -500,11 +501,14 @@ public static HttpResponse exchangeCreate(String httpNode, byte[] ownerAddress, return response; } - /** - * constructor. - */ - public static HttpResponse exchangeInject(String httpNode, byte[] ownerAddress, - Integer exchangeId, String tokenId, Long quant, String fromKey) { + /** 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(); @@ -524,11 +528,14 @@ public static HttpResponse exchangeInject(String httpNode, byte[] ownerAddress, return response; } - /** - * constructor. - */ - public static HttpResponse exchangeWithdraw(String httpNode, byte[] ownerAddress, - Integer exchangeId, String tokenId, Long quant, String fromKey) { + /** 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(); @@ -548,11 +555,15 @@ public static HttpResponse exchangeWithdraw(String httpNode, byte[] ownerAddress return response; } - /** - * constructor. - */ - public static HttpResponse exchangeTransaction(String httpNode, byte[] ownerAddress, - Integer exchangeId, String tokenId, Long quant, Long expected, String fromKey) { + /** 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(); @@ -573,14 +584,24 @@ public static HttpResponse exchangeTransaction(String httpNode, byte[] ownerAddr 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) { + /** 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(); @@ -610,11 +631,14 @@ public static HttpResponse assetIssue(String httpNode, byte[] ownerAddress, Stri return response; } - /** - * constructor. - */ - public static HttpResponse transferAsset(String httpNode, byte[] ownerAddress, byte[] toAddress, - String assetIssueById, Long amount, String fromKey) { + /** 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(); @@ -634,17 +658,25 @@ public static HttpResponse transferAsset(String httpNode, byte[] ownerAddress, b 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, + /** 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", str2hex(name)); userBaseObj2.addProperty("name", name); userBaseObj2.addProperty("abi", abi); userBaseObj2.addProperty("bytecode", bytecode); @@ -670,17 +702,25 @@ public static HttpResponse deployContract(String httpNode, String name, String a 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, + /** 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", str2hex(name)); userBaseObj2.addProperty("name", name); userBaseObj2.addProperty("abi", abi); userBaseObj2.addProperty("bytecode", bytecode); @@ -709,13 +749,21 @@ public static String deployContractGetTxid(String httpNode, String name, String 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) { + /** 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"; @@ -748,13 +796,18 @@ public static HttpResponse deployContractGetTxidWithTooBigLong(String httpNode, 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) { + /** 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(); @@ -770,8 +823,9 @@ public static String triggerContractGetTxid(String httpNode, byte[] ownerAddress transactionString = EntityUtils.toString(response.getEntity()); logger.info(transactionString); - transactionSignString = gettransactionsign(httpNode, - parseStringContent(transactionString).getString("transaction"), fromKey); + transactionSignString = + gettransactionsign( + httpNode, parseStringContent(transactionString).getString("transaction"), fromKey); logger.info(transactionSignString); response = broadcastTransaction(httpNode, transactionSignString); } catch (Exception e) { @@ -783,27 +837,45 @@ public static String triggerContractGetTxid(String httpNode, byte[] ownerAddress 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, + /** 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, + /** 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 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(); @@ -820,8 +892,9 @@ public static String triggerContractGetTxidWithVisibleTrue(String httpNode, transactionString = EntityUtils.toString(response.getEntity()); logger.info(transactionString); - transactionSignString = gettransactionsign(httpNode, - parseStringContent(transactionString).getString("transaction"), fromKey); + transactionSignString = + gettransactionsign( + httpNode, parseStringContent(transactionString).getString("transaction"), fromKey); logger.info(transactionSignString); response = broadcastTransaction(httpNode, transactionSignString); if (!anotherHttpNode.isEmpty()) { @@ -836,12 +909,14 @@ public static String triggerContractGetTxidWithVisibleTrue(String httpNode, return responseContent.getString("txID"); } - - /** - * constructor. - */ - public static HttpResponse triggerConstantContract(String httpNode, byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter, Long feeLimit, + /** 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"; @@ -862,11 +937,13 @@ public static HttpResponse triggerConstantContract(String httpNode, byte[] owner return response; } - /** - * constructor. - */ - public static HttpResponse triggerConstantContract(String httpNode, byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter) { + /** 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(); @@ -883,12 +960,13 @@ public static HttpResponse triggerConstantContract(String httpNode, byte[] owner } } - /** - * constructor. - */ - public static HttpResponse triggerConstantContractFromSolidity(String httSoliditypNode, + /** constructor. */ + public static HttpResponse triggerConstantContractFromSolidity( + String httSoliditypNode, byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter) { + String contractAddress, + String functionSelector, + String parameter) { try { final String requestUrl = "http://" + httSoliditypNode + "/walletsolidity/triggerconstantcontract"; @@ -906,12 +984,13 @@ public static HttpResponse triggerConstantContractFromSolidity(String httSolidit } } - /** - * constructor. - */ - public static HttpResponse triggerConstantContractFromPbft(String httpPbftNode, + /** constructor. */ + public static HttpResponse triggerConstantContractFromPbft( + String httpPbftNode, byte[] ownerAddress, - String contractAddress, String functionSelector, String parameter) { + String contractAddress, + String functionSelector, + String parameter) { try { final String requestUrl = "http://" + httpPbftNode + "/walletpbft/triggerconstantcontract"; JsonObject userBaseObj2 = new JsonObject(); @@ -928,11 +1007,14 @@ public static HttpResponse triggerConstantContractFromPbft(String httpPbftNode, } } - /** - * constructor. - */ - public static HttpResponse participateAssetIssue(String httpNode, byte[] toAddress, - byte[] ownerAddress, String assetIssueById, Long amount, String fromKey) { + /** 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(); @@ -954,11 +1036,15 @@ public static HttpResponse participateAssetIssue(String httpNode, byte[] toAddre return response; } - /** - * constructor. - */ - public static HttpResponse updateAssetIssue(String httpNode, byte[] ownerAddress, - String description, String url, Long newLimit, Long newPublicLimit, String fromKey) { + /** 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(); @@ -981,34 +1067,38 @@ public static HttpResponse updateAssetIssue(String httpNode, byte[] ownerAddress return response; } - - /** - * constructor. - */ + /** 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); + // 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, + 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) { + /** 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(); @@ -1039,19 +1129,19 @@ public static HttpResponse freezeBalance(String httpNode, byte[] ownerAddress, L return response; } - /** - * constructor. - */ - public static HttpResponse unFreezeBalance(String httpNode, byte[] ownerAddress, - Integer resourceCode, String fromKey) { + /** 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) { + /** 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(); @@ -1080,11 +1170,9 @@ public static HttpResponse unFreezeBalance(String httpNode, byte[] ownerAddress, return response; } - /** - * constructor. - */ - public static String gettransactionsign(String httpNode, String transactionString, - String privateKey) { + /** constructor. */ + public static String gettransactionsign( + String httpNode, String transactionString, String privateKey) { try { String requestUrl = "http://" + httpNode + "/wallet/gettransactionsign"; JsonObject userBaseObj2 = new JsonObject(); @@ -1100,13 +1188,12 @@ public static String gettransactionsign(String httpNode, String transactionStrin return transactionSignString; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse broadcastTransaction(String httpNode, String transactionSignString) { try { String requestUrl = "http://" + httpNode + "/wallet/broadcasttransaction"; - httpClient.getParams() + httpClient + .getParams() .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); httppost = new HttpPost(requestUrl); @@ -1128,8 +1215,9 @@ public static HttpResponse broadcastTransaction(String httpNode, String transact responseContent = HttpMethed.parseResponseContent(response); Integer times = 0; - while (times++ <= 10 && responseContent.getString("code") != null && responseContent - .getString("code").equalsIgnoreCase("SERVER_BUSY")) { + while (times++ <= 10 + && responseContent.getString("code") != null + && responseContent.getString("code").equalsIgnoreCase("SERVER_BUSY")) { logger.info("retry num are " + times); try { response = httpClient.execute(httppost); @@ -1149,9 +1237,7 @@ public static HttpResponse broadcastTransaction(String httpNode, String transact return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse broadcasthex(String httpNode, String transactionHex) { try { String requestUrl = "http://" + httpNode + "/wallet/broadcasthex"; @@ -1166,10 +1252,7 @@ public static HttpResponse broadcasthex(String httpNode, String transactionHex) return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getAccountById(String httpNode, String accountId, Boolean visable) { try { String requestUrl = "http://" + httpNode + "/wallet/getaccountbyid"; @@ -1185,11 +1268,9 @@ public static HttpResponse getAccountById(String httpNode, String accountId, Boo return response; } - /** - * constructor. - */ - public static HttpResponse getAccountByIdFromSolidity(String httpSolidityNode, String accountId, - Boolean visable) { + /** constructor. */ + public static HttpResponse getAccountByIdFromSolidity( + String httpSolidityNode, String accountId, Boolean visable) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getaccountbyid"; JsonObject userBaseObj2 = new JsonObject(); @@ -1204,11 +1285,9 @@ public static HttpResponse getAccountByIdFromSolidity(String httpSolidityNode, S return response; } - /** - * constructor. - */ - public static HttpResponse getAccountByIdFromPbft(String httpSolidityNode, String accountId, - Boolean visable) { + /** constructor. */ + public static HttpResponse getAccountByIdFromPbft( + String httpSolidityNode, String accountId, Boolean visable) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getaccountbyid"; JsonObject userBaseObj2 = new JsonObject(); @@ -1223,9 +1302,7 @@ public static HttpResponse getAccountByIdFromPbft(String httpSolidityNode, Strin return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getAccount(String httpNode, byte[] queryAddress) { try { String requestUrl = "http://" + httpNode + "/wallet/getaccount"; @@ -1240,9 +1317,7 @@ public static HttpResponse getAccount(String httpNode, byte[] queryAddress) { return response; } - /** - * constructor. - */ + /** constructor. */ public static Long getAccountForResponse(String httpNode, byte[] queryAddress, Integer times) { try { String requestUrl = "http://" + httpNode + "/wallet/getaccount"; @@ -1257,10 +1332,7 @@ public static Long getAccountForResponse(String httpNode, byte[] queryAddress, I } } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getAccountFromSolidity(String httpSolidityNode, byte[] queryAddress) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getaccount"; @@ -1277,9 +1349,7 @@ public static HttpResponse getAccountFromSolidity(String httpSolidityNode, byte[ return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getAccountFromPbft(String httpSolidityNode, byte[] queryAddress) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getaccount"; @@ -1293,9 +1363,7 @@ public static HttpResponse getAccountFromPbft(String httpSolidityNode, byte[] qu return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getContract(String httpNode, String contractAddress) { try { String requestUrl = "http://" + httpNode + "/wallet/getcontract"; @@ -1310,13 +1378,12 @@ public static HttpResponse getContract(String httpNode, String contractAddress) return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getSignWeight(String httpNode, String transactionSignString) { try { String requestUrl = "http://" + httpNode + "/wallet/getsignweight"; - httpClient.getParams() + httpClient + .getParams() .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); httppost = new HttpPost(requestUrl); @@ -1334,18 +1401,17 @@ public static HttpResponse getSignWeight(String httpNode, String transactionSign httppost.releaseConnection(); return null; } - //httppost.releaseConnection(); + // httppost.releaseConnection(); return response; } - /** - * constructor. - */ - public static HttpResponse getTransactionApprovedList(String httpNode, - String transactionSignString) { + /** constructor. */ + public static HttpResponse getTransactionApprovedList( + String httpNode, String transactionSignString) { try { String requestUrl = "http://" + httpNode + "/wallet/getapprovedlist"; - httpClient.getParams() + httpClient + .getParams() .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); httppost = new HttpPost(requestUrl); @@ -1363,14 +1429,11 @@ public static HttpResponse getTransactionApprovedList(String httpNode, httppost.releaseConnection(); return null; } - //httppost.releaseConnection(); + // httppost.releaseConnection(); return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse listExchanges(String httpNode) { try { String requestUrl = "http://" + httpNode + "/wallet/listexchanges"; @@ -1383,9 +1446,7 @@ public static HttpResponse listExchanges(String httpNode) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse listExchangesFromSolidity(String httpSolidityNode) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/listexchanges"; @@ -1398,10 +1459,7 @@ public static HttpResponse listExchangesFromSolidity(String httpSolidityNode) { return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse listExchangesFromPbft(String httpSolidityNode) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/listexchanges"; @@ -1414,10 +1472,7 @@ public static HttpResponse listExchangesFromPbft(String httpSolidityNode) { return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse listNodes(String httpNode) { try { String requestUrl = "http://" + httpNode + "/wallet/listnodes"; @@ -1430,10 +1485,7 @@ public static HttpResponse listNodes(String httpNode) { return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getStatsInfo(String httpNode) { try { String requestUrl = "http://" + httpNode + "/monitor/getstatsinfo"; @@ -1446,9 +1498,7 @@ public static HttpResponse getStatsInfo(String httpNode) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getNextmaintenanceTime(String httpNode) { try { String requestUrl = "http://" + httpNode + "/wallet/getnextmaintenancetime"; @@ -1461,9 +1511,7 @@ public static HttpResponse getNextmaintenanceTime(String httpNode) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getChainParameter(String httpNode) { try { String requestUrl = "http://" + httpNode + "/wallet/getchainparameters"; @@ -1476,9 +1524,7 @@ public static HttpResponse getChainParameter(String httpNode) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getNodeInfo(String httpNode) { try { String requestUrl = "http://" + httpNode + "/wallet/getnodeinfo"; @@ -1491,9 +1537,7 @@ public static HttpResponse getNodeInfo(String httpNode) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse listwitnesses(String httpNode) { try { String requestUrl = "http://" + httpNode + "/wallet/listwitnesses"; @@ -1506,9 +1550,7 @@ public static HttpResponse listwitnesses(String httpNode) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse listwitnessesFromSolidity(String httpSolidityNode) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/listwitnesses"; @@ -1521,9 +1563,7 @@ public static HttpResponse listwitnessesFromSolidity(String httpSolidityNode) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse listwitnessesFromPbft(String httpSolidityNode) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/listwitnesses"; @@ -1536,10 +1576,7 @@ public static HttpResponse listwitnessesFromPbft(String httpSolidityNode) { return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse listProposals(String httpNode) { try { String requestUrl = "http://" + httpNode + "/wallet/listproposals"; @@ -1552,9 +1589,7 @@ public static HttpResponse listProposals(String httpNode) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getExchangeById(String httpNode, Integer exchangeId) { try { String requestUrl = "http://" + httpNode + "/wallet/getexchangebyid"; @@ -1569,11 +1604,9 @@ public static HttpResponse getExchangeById(String httpNode, Integer exchangeId) return response; } - /** - * constructor. - */ - public static HttpResponse getExchangeByIdFromSolidity(String httpSolidityNode, - Integer exchangeId) { + /** constructor. */ + public static HttpResponse getExchangeByIdFromSolidity( + String httpSolidityNode, Integer exchangeId) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getexchangebyid"; JsonObject userBaseObj2 = new JsonObject(); @@ -1587,9 +1620,7 @@ public static HttpResponse getExchangeByIdFromSolidity(String httpSolidityNode, return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getExchangeByIdFromPbft(String httpSolidityNode, Integer exchangeId) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getexchangebyid"; @@ -1604,10 +1635,7 @@ public static HttpResponse getExchangeByIdFromPbft(String httpSolidityNode, Inte return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getProposalById(String httpNode, Integer proposalId) { try { String requestUrl = "http://" + httpNode + "/wallet/getproposalbyid"; @@ -1622,9 +1650,7 @@ public static HttpResponse getProposalById(String httpNode, Integer proposalId) return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getAssetIssueListByName(String httpNode, String name) { try { String requestUrl = "http://" + httpNode + "/wallet/getassetissuelistbyname"; @@ -1639,11 +1665,9 @@ public static HttpResponse getAssetIssueListByName(String httpNode, String name) return response; } - /** - * constructor. - */ - public static HttpResponse getAssetIssueListByNameFromSolidity(String httpSolidityNode, - String name) { + /** constructor. */ + public static HttpResponse getAssetIssueListByNameFromSolidity( + String httpSolidityNode, String name) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuelistbyname"; JsonObject userBaseObj2 = new JsonObject(); @@ -1657,11 +1681,8 @@ public static HttpResponse getAssetIssueListByNameFromSolidity(String httpSolidi return response; } - /** - * constructor. - */ - public static HttpResponse getAssetIssueListByNameFromPbft(String httpPbftNode, - String name) { + /** constructor. */ + public static HttpResponse getAssetIssueListByNameFromPbft(String httpPbftNode, String name) { try { String requestUrl = "http://" + httpPbftNode + "/walletpbft/getassetissuelistbyname"; JsonObject userBaseObj2 = new JsonObject(); @@ -1675,9 +1696,7 @@ public static HttpResponse getAssetIssueListByNameFromPbft(String httpPbftNode, return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getAssetIssueById(String httpNode, String assetIssueId) { try { String requestUrl = "http://" + httpNode + "/wallet/getassetissuebyid"; @@ -1692,11 +1711,9 @@ public static HttpResponse getAssetIssueById(String httpNode, String assetIssueI return response; } - /** - * constructor. - */ - public static HttpResponse getAssetIssueByIdFromSolidity(String httpSolidityNode, - String assetIssueId) { + /** constructor. */ + public static HttpResponse getAssetIssueByIdFromSolidity( + String httpSolidityNode, String assetIssueId) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuebyid"; JsonObject userBaseObj2 = new JsonObject(); @@ -1710,11 +1727,9 @@ public static HttpResponse getAssetIssueByIdFromSolidity(String httpSolidityNode return response; } - /** - * constructor. - */ - public static HttpResponse getAssetIssueByIdFromPbft(String httpSolidityNode, - String assetIssueId) { + /** constructor. */ + public static HttpResponse getAssetIssueByIdFromPbft( + String httpSolidityNode, String assetIssueId) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getassetissuebyid"; JsonObject userBaseObj2 = new JsonObject(); @@ -1728,10 +1743,7 @@ public static HttpResponse getAssetIssueByIdFromPbft(String httpSolidityNode, return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getTransactionById(String httpNode, String txid) { try { String requestUrl = "http://" + httpNode + "/wallet/gettransactionbyid"; @@ -1746,9 +1758,7 @@ public static HttpResponse getTransactionById(String httpNode, String txid) { return response; } - /** - * constructor. - */ + /** constructor. */ public static Long getTransactionByIdForResponse(String httpNode, String txid, Integer times) { try { String requestUrl = "http://" + httpNode + "/wallet/gettransactionbyid"; @@ -1763,10 +1773,7 @@ public static Long getTransactionByIdForResponse(String httpNode, String txid, I } } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getTransactionByIdFromSolidity(String httpSolidityNode, String txid) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/gettransactionbyid"; @@ -1781,9 +1788,7 @@ public static HttpResponse getTransactionByIdFromSolidity(String httpSolidityNod return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getTransactionByIdFromPbft(String httpSolidityNode, String txid) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/gettransactionbyid"; @@ -1798,17 +1803,12 @@ public static HttpResponse getTransactionByIdFromPbft(String httpSolidityNode, S return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getTransactionInfoById(String httpNode, String txid) { return getTransactionInfoById(httpNode, txid, false); } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getTransactionInfoById(String httpNode, String txid, Boolean visible) { try { String requestUrl = "http://" + httpNode + "/wallet/gettransactioninfobyid"; @@ -1824,12 +1824,9 @@ public static HttpResponse getTransactionInfoById(String httpNode, String txid, return response; } - - /** - * constructor. - */ - public static HttpResponse getTransactionInfoByIdFromSolidity(String httpSolidityNode, - String txid) { + /** constructor. */ + public static HttpResponse getTransactionInfoByIdFromSolidity( + String httpSolidityNode, String txid) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/gettransactioninfobyid"; JsonObject userBaseObj2 = new JsonObject(); @@ -1843,9 +1840,7 @@ public static HttpResponse getTransactionInfoByIdFromSolidity(String httpSolidit return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getTransactionInfoByIdFromPbft(String httpSolidityNode, String txid) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/gettransactioninfobyid"; @@ -1860,9 +1855,7 @@ public static HttpResponse getTransactionInfoByIdFromPbft(String httpSolidityNod return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getTransactionInfoByBlocknum(String httpNode, long blocknum) { try { String requestUrl = "http://" + httpNode + "/wallet/gettransactioninfobyblocknum"; @@ -1877,11 +1870,9 @@ public static HttpResponse getTransactionInfoByBlocknum(String httpNode, long bl return response; } - /** - * constructor. - */ - public static HttpResponse getTransactionInfoByBlocknumFromSolidity(String httpSolidityNode, - long blocknum) { + /** constructor. */ + public static HttpResponse getTransactionInfoByBlocknumFromSolidity( + String httpSolidityNode, long blocknum) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/gettransactioninfobyblocknum"; @@ -1896,11 +1887,9 @@ public static HttpResponse getTransactionInfoByBlocknumFromSolidity(String httpS return response; } - /** - * constructor. - */ - public static HttpResponse getTransactionCountByBlocknumFromSolidity(String httpSolidityNode, - long blocknum) { + /** constructor. */ + public static HttpResponse getTransactionCountByBlocknumFromSolidity( + String httpSolidityNode, long blocknum) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/gettransactioncountbyblocknum"; @@ -1915,11 +1904,9 @@ public static HttpResponse getTransactionCountByBlocknumFromSolidity(String http return response; } - /** - * constructor. - */ - public static HttpResponse getTransactionCountByBlocknumFromPbft(String httpSolidityNode, - long blocknum) { + /** constructor. */ + public static HttpResponse getTransactionCountByBlocknumFromPbft( + String httpSolidityNode, long blocknum) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/gettransactioncountbyblocknum"; @@ -1934,12 +1921,9 @@ public static HttpResponse getTransactionCountByBlocknumFromPbft(String httpSoli return response; } - - /** - * constructor. - */ - public static HttpResponse getTransactionsFromThisFromSolidity(String httpSolidityNode, - byte[] fromAddress, long offset, long limit) { + /** constructor. */ + public static HttpResponse getTransactionsFromThisFromSolidity( + String httpSolidityNode, byte[] fromAddress, long offset, long limit) { try { Map map1 = new HashMap(); Map map = new HashMap(); @@ -1959,11 +1943,9 @@ public static HttpResponse getTransactionsFromThisFromSolidity(String httpSolidi return response; } - /** - * constructor. - */ - public static HttpResponse getTransactionsToThisFromSolidity(String httpSolidityNode, - byte[] toAddress, long offset, long limit) { + /** constructor. */ + public static HttpResponse getTransactionsToThisFromSolidity( + String httpSolidityNode, byte[] toAddress, long offset, long limit) { try { Map map1 = new HashMap(); Map map = new HashMap(); @@ -1983,9 +1965,7 @@ public static HttpResponse getTransactionsToThisFromSolidity(String httpSolidity return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getAssetIssueByName(String httpNode, String name) { try { String requestUrl = "http://" + httpNode + "/wallet/getassetissuebyname"; @@ -2000,10 +1980,7 @@ public static HttpResponse getAssetIssueByName(String httpNode, String name) { return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getAssetIssueByNameFromSolidity(String httpSolidityNode, String name) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuebyname"; @@ -2018,9 +1995,7 @@ public static HttpResponse getAssetIssueByNameFromSolidity(String httpSolidityNo return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getAssetIssueByNameFromPbft(String httpSolidityNode, String name) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getassetissuebyname"; @@ -2035,10 +2010,7 @@ public static HttpResponse getAssetIssueByNameFromPbft(String httpSolidityNode, return response; } - - /** - * constructor. - */ + /** constructor. */ public static Long getBalance(String httpNode, byte[] queryAddress) { try { String requestUrl = "http://" + httpNode + "/wallet/getaccount"; @@ -2051,18 +2023,15 @@ public static Long getBalance(String httpNode, byte[] queryAddress) { return null; } responseContent = HttpMethed.parseResponseContent(response); - //HttpMethed.printJsonContent(responseContent); - //httppost.releaseConnection(); + // HttpMethed.printJsonContent(responseContent); + // httppost.releaseConnection(); if (!responseContent.containsKey("balance")) { return 0L; } return Long.parseLong(responseContent.get("balance").toString()); } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getAccountNet(String httpNode, byte[] queryAddress) { try { String requestUrl = "http://" + httpNode + "/wallet/getaccountnet"; @@ -2077,9 +2046,7 @@ public static HttpResponse getAccountNet(String httpNode, byte[] queryAddress) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getAccountReource(String httpNode, byte[] queryAddress) { try { String requestUrl = "http://" + httpNode + "/wallet/getaccountresource"; @@ -2094,11 +2061,9 @@ public static HttpResponse getAccountReource(String httpNode, byte[] queryAddres return response; } - /** - * constructor. - */ - public static HttpResponse getAccountBalance(String httpNode, - byte[] queryAddress, Integer blockNum, String blockHash) { + /** 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(); @@ -2120,9 +2085,7 @@ public static HttpResponse getAccountBalance(String httpNode, return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getBlockBalance(String httpNode, Integer blockNum, String blockHash) { try { final String requestUrl = "http://" + httpNode + "/wallet/getblockbalance"; @@ -2139,9 +2102,7 @@ public static HttpResponse getBlockBalance(String httpNode, Integer blockNum, St return response; } - /** - * constructor. - */ + /** constructor. */ public static Long getBurnTrx(String httpNode) { try { final String requestUrl = "http://" + httpNode + "/wallet/getburntrx"; @@ -2156,9 +2117,7 @@ public static Long getBurnTrx(String httpNode) { return responseContent.getLong("burnTrxAmount"); } - /** - * constructor. - */ + /** constructor. */ public static Long getBurnTrxFromSolidity(String httpNode) { try { final String requestUrl = "http://" + httpNode + "/walletsolidity/getburntrx"; @@ -2173,9 +2132,7 @@ public static Long getBurnTrxFromSolidity(String httpNode) { return responseContent.getLong("burnTrxAmount"); } - /** - * constructor. - */ + /** constructor. */ public static Long getBurnTrxFromPbft(String httpNode) { try { final String requestUrl = "http://" + httpNode + "/walletpbft/getburntrx"; @@ -2190,19 +2147,12 @@ public static Long getBurnTrxFromPbft(String httpNode) { return responseContent.getLong("burnTrxAmount"); } - - - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getNowBlock(String httpNode) { return getNowBlock(httpNode, false); } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getNowBlock(String httpNode, Boolean visible) { try { String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; @@ -2217,9 +2167,7 @@ public static HttpResponse getNowBlock(String httpNode, Boolean visible) { return response; } - /** - * constructor. - */ + /** constructor. */ public static Long getNowBlockNum(String httpNode) { try { String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; @@ -2229,13 +2177,13 @@ public static Long getNowBlockNum(String httpNode) { httppost.releaseConnection(); return null; } - return parseResponseContent(response).getJSONObject("block_header").getJSONObject("raw_data") + return parseResponseContent(response) + .getJSONObject("block_header") + .getJSONObject("raw_data") .getLong("number"); } - /** - * constructor. - */ + /** constructor. */ public static Long getNowBlockNumOnSolidity(String httpNode) { try { String requestUrl = "http://" + httpNode + "/walletsolidity/getnowblock"; @@ -2245,14 +2193,13 @@ public static Long getNowBlockNumOnSolidity(String httpNode) { httppost.releaseConnection(); return null; } - return parseResponseContent(response).getJSONObject("block_header").getJSONObject("raw_data") + return parseResponseContent(response) + .getJSONObject("block_header") + .getJSONObject("raw_data") .getLong("number"); } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getNowBlockFromSolidity(String httpSolidityNode) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getnowblock"; @@ -2265,9 +2212,7 @@ public static HttpResponse getNowBlockFromSolidity(String httpSolidityNode) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getNowBlockFromPbft(String httpSolidityNode) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getnowblock"; @@ -2280,10 +2225,7 @@ public static HttpResponse getNowBlockFromPbft(String httpSolidityNode) { return response; } - - /** - * constructor. - */ + /** constructor. */ public static void waitToProduceOneBlock(String httpNode) { response = HttpMethed.getNowBlock(httpNode); responseContent = HttpMethed.parseResponseContent(response); @@ -2295,8 +2237,8 @@ public static void waitToProduceOneBlock(String httpNode) { 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("block_header").toString()); responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); try { @@ -2307,9 +2249,7 @@ public static void waitToProduceOneBlock(String httpNode) { } } - /** - * constructor. - */ + /** constructor. */ public static void waitToProduceOneBlockFromSolidity(String httpNode, String httpSolidityNode) { response = HttpMethed.getNowBlock(httpNode); responseContent = HttpMethed.parseResponseContent(response); @@ -2318,11 +2258,12 @@ 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 + && 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("block_header").toString()); responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); try { @@ -2331,11 +2272,11 @@ public static void waitToProduceOneBlockFromSolidity(String httpNode, String htt e.printStackTrace(); } } + logger.info("currentBlockNum2:" + currentBlockNum); + logger.info("nextBlockNum2:" + nextBlockNum); } - /** - * constructor. - */ + /** constructor. */ public static void waitToProduceOneBlockFromPbft(String httpNode, String httpSolidityNode) { response = HttpMethed.getNowBlock(httpNode); responseContent = HttpMethed.parseResponseContent(response); @@ -2347,8 +2288,8 @@ public static void waitToProduceOneBlockFromPbft(String httpNode, String httpSol 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("block_header").toString()); responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); try { @@ -2359,17 +2300,12 @@ public static void waitToProduceOneBlockFromPbft(String httpNode, String httpSol } } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getBlockByNum(String httpNode, Integer blockNUm) { return getBlockByNum(httpNode, blockNUm, false); } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getBlockByNum(String httpNode, Integer blockNUm, Boolean visible) { try { String requestUrl = "http://" + httpNode + "/wallet/getblockbynum"; @@ -2385,9 +2321,7 @@ public static HttpResponse getBlockByNum(String httpNode, Integer blockNUm, Bool return response; } - /** - * constructor. - */ + /** constructor. */ public static Long getBlockByNumForResponse(String httpNode, Integer blockNUm, Integer times) { try { String requestUrl = "http://" + httpNode + "/wallet/getblockbynum"; @@ -2402,10 +2336,7 @@ public static Long getBlockByNumForResponse(String httpNode, Integer blockNUm, I } } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getBlockByNumFromSolidity(String httpSolidityNode, Integer blockNum) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getblockbynum"; @@ -2420,9 +2351,7 @@ public static HttpResponse getBlockByNumFromSolidity(String httpSolidityNode, In return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getBlockByNumFromPbft(String httpSolidityNode, Integer blockNum) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getblockbynum"; @@ -2437,12 +2366,9 @@ public static HttpResponse getBlockByNumFromPbft(String httpSolidityNode, Intege return response; } - - /** - * constructor. - */ - public static HttpResponse getBlockByLimitNext(String httpNode, Integer startNum, - Integer endNum) { + /** constructor. */ + public static HttpResponse getBlockByLimitNext( + String httpNode, Integer startNum, Integer endNum) { try { String requestUrl = "http://" + httpNode + "/wallet/getblockbylimitnext"; JsonObject userBaseObj2 = new JsonObject(); @@ -2457,11 +2383,9 @@ public static HttpResponse getBlockByLimitNext(String httpNode, Integer startNum return response; } - /** - * constructor. - */ - public static HttpResponse getBlockByLimitNextFromSolidity(String httpNode, Integer startNum, - Integer endNum) { + /** constructor. */ + public static HttpResponse getBlockByLimitNextFromSolidity( + String httpNode, Integer startNum, Integer endNum) { try { String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbylimitnext"; JsonObject userBaseObj2 = new JsonObject(); @@ -2476,11 +2400,9 @@ public static HttpResponse getBlockByLimitNextFromSolidity(String httpNode, Inte return response; } - /** - * constructor. - */ - public static HttpResponse getBlockByLimitNextFromPbft(String httpNode, Integer startNum, - Integer endNum) { + /** constructor. */ + public static HttpResponse getBlockByLimitNextFromPbft( + String httpNode, Integer startNum, Integer endNum) { try { String requestUrl = "http://" + httpNode + "/walletpbft/getblockbylimitnext"; JsonObject userBaseObj2 = new JsonObject(); @@ -2495,10 +2417,7 @@ public static HttpResponse getBlockByLimitNextFromPbft(String httpNode, Integer return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getBlockByLastNum(String httpNode, Integer num) { try { String requestUrl = "http://" + httpNode + "/wallet/getblockbylatestnum"; @@ -2513,9 +2432,7 @@ public static HttpResponse getBlockByLastNum(String httpNode, Integer num) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getBlockByLastNum2(String httpNode, Integer num) { try { String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbylatestnum2"; @@ -2530,10 +2447,7 @@ public static HttpResponse getBlockByLastNum2(String httpNode, Integer num) { return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getBlockByLastNumFromSolidity(String httpNode, Integer num) { try { String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbylatestnum"; @@ -2548,9 +2462,7 @@ public static HttpResponse getBlockByLastNumFromSolidity(String httpNode, Intege return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getBlockByLastNumFromPbft(String httpNode, Integer num) { try { String requestUrl = "http://" + httpNode + "/walletpbft/getblockbylatestnum"; @@ -2563,10 +2475,7 @@ public static HttpResponse getBlockByLastNumFromPbft(String httpNode, Integer nu return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getBlockById(String httpNode, String blockId) { try { String requestUrl = "http://" + httpNode + "/wallet/getblockbyid"; @@ -2581,9 +2490,7 @@ public static HttpResponse getBlockById(String httpNode, String blockId) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getBlockByIdFromSolidity(String httpNode, String blockId) { try { String requestUrl = "http://" + httpNode + "/walletsolidity/getblockbyid"; @@ -2598,9 +2505,7 @@ public static HttpResponse getBlockByIdFromSolidity(String httpNode, String bloc return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getBlockByIdFromPbft(String httpNode, String blockId) { try { String requestUrl = "http://" + httpNode + "/walletpbft/getblockbyid"; @@ -2615,12 +2520,9 @@ public static HttpResponse getBlockByIdFromPbft(String httpNode, String blockId) return response; } - - /** - * constructor. - */ - public static HttpResponse getDelegatedResource(String httpNode, byte[] fromAddress, - byte[] toAddress) { + /** constructor. */ + public static HttpResponse getDelegatedResource( + String httpNode, byte[] fromAddress, byte[] toAddress) { try { String requestUrl = "http://" + httpNode + "/wallet/getdelegatedresource"; JsonObject userBaseObj2 = new JsonObject(); @@ -2635,11 +2537,9 @@ public static HttpResponse getDelegatedResource(String httpNode, byte[] fromAddr return response; } - /** - * constructor. - */ - public static HttpResponse getDelegatedResourceFromSolidity(String httpSolidityNode, - byte[] fromAddress, byte[] toAddress) { + /** constructor. */ + public static HttpResponse getDelegatedResourceFromSolidity( + String httpSolidityNode, byte[] fromAddress, byte[] toAddress) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getdelegatedresource"; JsonObject userBaseObj2 = new JsonObject(); @@ -2654,11 +2554,9 @@ public static HttpResponse getDelegatedResourceFromSolidity(String httpSolidityN return response; } - /** - * constructor. - */ - public static HttpResponse getDelegatedResourceFromPbft(String httpSolidityNode, - byte[] fromAddress, byte[] toAddress) { + /** constructor. */ + public static HttpResponse getDelegatedResourceFromPbft( + String httpSolidityNode, byte[] fromAddress, byte[] toAddress) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getdelegatedresource"; JsonObject userBaseObj2 = new JsonObject(); @@ -2673,12 +2571,9 @@ public static HttpResponse getDelegatedResourceFromPbft(String httpSolidityNode, return response; } - - /** - * constructor. - */ - public static HttpResponse getDelegatedResourceAccountIndex(String httpNode, - byte[] queryAddress) { + /** constructor. */ + public static HttpResponse getDelegatedResourceAccountIndex( + String httpNode, byte[] queryAddress) { try { String requestUrl = "http://" + httpNode + "/wallet/getdelegatedresourceaccountindex"; JsonObject userBaseObj2 = new JsonObject(); @@ -2692,11 +2587,9 @@ public static HttpResponse getDelegatedResourceAccountIndex(String httpNode, return response; } - /** - * constructor. - */ - public static HttpResponse getDelegatedResourceAccountIndexFromSolidity(String httpSolidityNode, - byte[] queryAddress) { + /** constructor. */ + public static HttpResponse getDelegatedResourceAccountIndexFromSolidity( + String httpSolidityNode, byte[] queryAddress) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getdelegatedresourceaccountindex"; @@ -2711,11 +2604,9 @@ public static HttpResponse getDelegatedResourceAccountIndexFromSolidity(String h return response; } - /** - * constructor. - */ - public static HttpResponse getDelegatedResourceAccountIndexFromPbft(String httpSolidityNode, - byte[] queryAddress) { + /** constructor. */ + public static HttpResponse getDelegatedResourceAccountIndexFromPbft( + String httpSolidityNode, byte[] queryAddress) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getdelegatedresourceaccountindex"; @@ -2730,20 +2621,16 @@ public static HttpResponse getDelegatedResourceAccountIndexFromPbft(String httpS return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse createConnect(String url) { return createConnect(url, null); } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse createConnect(String url, JsonObject requestBody) { try { - httpClient.getParams() + httpClient + .getParams() .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); httppost = new HttpPost(url); @@ -2766,14 +2653,12 @@ public static HttpResponse createConnect(String url, JsonObject requestBody) { return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse createConnectForGet(String url) { try { - httpClient.getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient + .getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); HttpGet httppost; httppost = new HttpGet(url); @@ -2790,12 +2675,11 @@ public static HttpResponse createConnectForGet(String url) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse createConnectForShieldTrc20(String url, JSONObject requestBody) { try { - httpClient.getParams() + httpClient + .getParams() .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); httppost = new HttpPost(url); @@ -2816,10 +2700,7 @@ public static HttpResponse createConnectForShieldTrc20(String url, JSONObject re return response; } - - /** - * constructor. - */ + /** constructor. */ public static Long createConnectForResponse(String url, JsonObject requestBody, Integer times) { try { @@ -2827,7 +2708,8 @@ public static Long createConnectForResponse(String url, JsonObject requestBody, Long end = 0L; Long duration = 0L; while (times-- > 0) { - httpClient.getParams() + httpClient + .getParams() .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); httppost = new HttpPost(url); @@ -2856,16 +2738,15 @@ public static Long createConnectForResponse(String url, JsonObject requestBody, } } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse createConnect1(String url, JSONObject requestBody) { try { - httpClient.getParams() + httpClient + .getParams() .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httpClient.getParams() + httpClient + .getParams() .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout * 10000); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout * 10000); httppost = new HttpPost(url); @@ -2886,10 +2767,7 @@ public static HttpResponse createConnect1(String url, JSONObject requestBody) { return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getAssetissueList(String httpNode) { try { String requestUrl = "http://" + httpNode + "/wallet/getassetissuelist"; @@ -2902,11 +2780,9 @@ public static HttpResponse getAssetissueList(String httpNode) { return response; } - /** - * constructor. - */ - public static Long getAssetIssueValue(String httpNode, byte[] accountAddress, - String assetIssueId) { + /** 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"); @@ -2923,9 +2799,7 @@ public static Long getAssetIssueValue(String httpNode, byte[] accountAddress, return 0L; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getAssetIssueListFromSolidity(String httpSolidityNode) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getassetissuelist"; @@ -2938,9 +2812,7 @@ public static HttpResponse getAssetIssueListFromSolidity(String httpSolidityNode return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getAssetIssueListFromPbft(String httpSolidityNode) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getassetissuelist"; @@ -2953,12 +2825,9 @@ public static HttpResponse getAssetIssueListFromPbft(String httpSolidityNode) { return response; } - - /** - * constructor. - */ - public static HttpResponse getPaginatedAssetissueList(String httpNode, Integer offset, - Integer limit) { + /** constructor. */ + public static HttpResponse getPaginatedAssetissueList( + String httpNode, Integer offset, Integer limit) { try { final String requestUrl = "http://" + httpNode + "/wallet/getpaginatedassetissuelist"; JsonObject userBaseObj2 = new JsonObject(); @@ -2974,11 +2843,9 @@ public static HttpResponse getPaginatedAssetissueList(String httpNode, Integer o return response; } - /** - * constructor. - */ - public static HttpResponse getPaginatedAssetissueListFromSolidity(String httpSolidityNode, - Integer offset, Integer limit) { + /** constructor. */ + public static HttpResponse getPaginatedAssetissueListFromSolidity( + String httpSolidityNode, Integer offset, Integer limit) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getpaginatedassetissuelist"; @@ -2994,11 +2861,9 @@ public static HttpResponse getPaginatedAssetissueListFromSolidity(String httpSol return response; } - /** - * constructor. - */ - public static HttpResponse getPaginatedAssetissueListFromPbft(String httpSolidityNode, - Integer offset, Integer limit) { + /** constructor. */ + public static HttpResponse getPaginatedAssetissueListFromPbft( + String httpSolidityNode, Integer offset, Integer limit) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getpaginatedassetissuelist"; JsonObject userBaseObj2 = new JsonObject(); @@ -3013,12 +2878,9 @@ public static HttpResponse getPaginatedAssetissueListFromPbft(String httpSolidit return response; } - - /** - * constructor. - */ - public static HttpResponse getPaginatedProposalList(String httpNode, Integer offset, - Integer limit) { + /** constructor. */ + public static HttpResponse getPaginatedProposalList( + String httpNode, Integer offset, Integer limit) { try { String requestUrl = "http://" + httpNode + "/wallet/getpaginatedproposallist"; JsonObject userBaseObj2 = new JsonObject(); @@ -3033,12 +2895,9 @@ public static HttpResponse getPaginatedProposalList(String httpNode, Integer off return response; } - - /** - * constructor. - */ - public static HttpResponse getPaginatedExchangeList(String httpNode, Integer offset, - Integer limit) { + /** constructor. */ + public static HttpResponse getPaginatedExchangeList( + String httpNode, Integer offset, Integer limit) { try { String requestUrl = "http://" + httpNode + "/wallet/getpaginatedexchangelist"; JsonObject userBaseObj2 = new JsonObject(); @@ -3053,12 +2912,13 @@ public static HttpResponse getPaginatedExchangeList(String httpNode, Integer off return response; } - - /** - * constructor. - */ - public static HttpResponse updateSetting(String httpNode, byte[] ownerAddress, - String contractAddress, Integer consumeUserResourcePercent, String fromKey) { + /** 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(); @@ -3080,12 +2940,13 @@ public static HttpResponse updateSetting(String httpNode, byte[] ownerAddress, return response; } - - /** - * constructor. - */ - public static HttpResponse updateEnergyLimit(String httpNode, byte[] ownerAddress, - String contractAddress, Integer originEnergyLimit, String fromKey) { + /** 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(); @@ -3107,9 +2968,7 @@ public static HttpResponse updateEnergyLimit(String httpNode, byte[] ownerAddres return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse createAddress(String httpNode, String value) { try { final String requestUrl = "http://" + httpNode + "/wallet/createaddress"; @@ -3125,9 +2984,7 @@ public static HttpResponse createAddress(String httpNode, String value) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse generateAddress(String httpNode) { try { final String requestUrl = "http://" + httpNode + "/wallet/generateaddress"; @@ -3141,13 +2998,10 @@ public static HttpResponse generateAddress(String httpNode) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getTransactionCountByBlocknum(String httpNode, long blocknum) { try { - String requestUrl = - "http://" + httpNode + "/wallet/gettransactioncountbyblocknum"; + String requestUrl = "http://" + httpNode + "/wallet/gettransactioncountbyblocknum"; JsonObject userBaseObj2 = new JsonObject(); userBaseObj2.addProperty("num", blocknum); response = createConnect(requestUrl, userBaseObj2); @@ -3159,10 +3013,7 @@ public static HttpResponse getTransactionCountByBlocknum(String httpNode, long b return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse validateAddress(String httpNode, String address) { try { final String requestUrl = "http://" + httpNode + "/wallet/validateaddress"; @@ -3178,11 +3029,9 @@ public static HttpResponse validateAddress(String httpNode, String address) { return response; } - /** - * constructor. - */ - public static HttpResponse easyTransfer(String httpNode, String value, byte[] toAddress, - Long amount) { + /** 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(); @@ -3201,11 +3050,9 @@ public static HttpResponse easyTransfer(String httpNode, String value, byte[] to return response; } - /** - * constructor. - */ - public static HttpResponse easyTransferByPrivate(String httpNode, String privateKey, - byte[] toAddress, Long amount) { + /** 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(); @@ -3224,11 +3071,9 @@ public static HttpResponse easyTransferByPrivate(String httpNode, String private return response; } - /** - * constructor. - */ - public static HttpResponse easyTransferAsset(String httpNode, String value, byte[] toAddress, - Long amount, String assetId) { + /** 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(); @@ -3248,11 +3093,9 @@ public static HttpResponse easyTransferAsset(String httpNode, String value, byte return response; } - /** - * constructor. - */ - public static HttpResponse easyTransferAssetByPrivate(String httpNode, String privateKey, - byte[] toAddress, Long amount, String assetId) { + /** 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(); @@ -3272,10 +3115,7 @@ public static HttpResponse easyTransferAssetByPrivate(String httpNode, String pr return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getContractInfo(String httpNode, String contractAddress) { try { String requestUrl = "http://" + httpNode + "/wallet/getcontractinfo"; @@ -3290,17 +3130,12 @@ public static HttpResponse getContractInfo(String httpNode, String contractAddre return response; } - - /** - * constructor. - */ + /** constructor. */ public static void disConnect() { httppost.releaseConnection(); } - /** - * constructor. - */ + /** constructor. */ public static JSONObject parseResponseContent(HttpResponse response) { try { String result = EntityUtils.toString(response.getEntity()); @@ -3314,9 +3149,7 @@ public static JSONObject parseResponseContent(HttpResponse response) { } } - /** - * constructor. - */ + /** constructor. */ public static List parseResponseContentArray(HttpResponse response) { try { String result = EntityUtils.toString(response.getEntity()); @@ -3334,9 +3167,7 @@ public static List parseResponseContentArray(HttpResponse response) } } - /** - * constructor. - */ + /** constructor. */ public static JSONObject parseStringContent(String content) { try { JSONObject obj = JSONObject.parseObject(content); @@ -3347,9 +3178,7 @@ public static JSONObject parseStringContent(String content) { } } - /** - * constructor. - */ + /** constructor. */ public static void printJsonContent(JSONObject responseContent) { logger.info("----------------------------Print JSON Start---------------------------"); for (String str : responseContent.keySet()) { @@ -3359,9 +3188,7 @@ public static void printJsonContent(JSONObject responseContent) { logger.info("----------------------------Print JSON End-----------------------------"); } - /** - * constructor. - */ + /** constructor. */ public static String str2hex(String str) { char[] chars = "0123456789ABCDEF".toCharArray(); StringBuilder sb = new StringBuilder(); @@ -3377,12 +3204,9 @@ public static String str2hex(String str) { return sb.toString().trim(); } - - /** - * constructor. - */ - public static HttpResponse clearABiGetTxid(String httpNode, byte[] ownerAddress, - String contractAddress, String fromKey) { + /** 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(); @@ -3397,7 +3221,6 @@ public static HttpResponse clearABiGetTxid(String httpNode, byte[] ownerAddress, logger.info(transactionSignString); response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { e.printStackTrace(); httppost.releaseConnection(); @@ -3406,9 +3229,7 @@ public static HttpResponse clearABiGetTxid(String httpNode, byte[] ownerAddress, return response; } - /** - * constructor. - */ + /** constructor. */ public static Optional generateShieldAddress(String httpnode) { ShieldAddressInfo addressInfo = new ShieldAddressInfo(); String sk; @@ -3468,11 +3289,12 @@ public static Optional generateShieldAddress(String httpnode) return Optional.empty(); } - /** - * constructor. - */ - public static List addShieldOutputList(String httpNode, - List shieldOutList, String shieldToAddress, String toAmountString, + /** constructor. */ + public static List addShieldOutputList( + String httpNode, + List shieldOutList, + String shieldToAddress, + String toAmountString, String menoString) { String shieldAddress = shieldToAddress; String amountString = toAmountString; @@ -3499,9 +3321,7 @@ public static List addShieldOutputList(String httpNode, return shieldOutList; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getSpendingKey(String httpNode) { try { String requestUrl = "http://" + httpNode + "/wallet/getspendingkey"; @@ -3514,9 +3334,7 @@ public static HttpResponse getSpendingKey(String httpNode) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getDiversifier(String httpNode) { try { String requestUrl = "http://" + httpNode + "/wallet/getdiversifier"; @@ -3529,9 +3347,7 @@ public static HttpResponse getDiversifier(String httpNode) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getRcm(String httpNode) { try { String requestUrl = "http://" + httpNode + "/wallet/getrcm"; @@ -3544,9 +3360,7 @@ public static HttpResponse getRcm(String httpNode) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getExpandedSpendingKey(String httpNode, String spendingKey) { try { String requestUrl = "http://" + httpNode + "/wallet/getexpandedspendingkey"; @@ -3561,9 +3375,7 @@ public static HttpResponse getExpandedSpendingKey(String httpNode, String spendi return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getAkFromAsk(String httpNode, String ask) { try { String requestUrl = "http://" + httpNode + "/wallet/getakfromask"; @@ -3578,9 +3390,7 @@ public static HttpResponse getAkFromAsk(String httpNode, String ask) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getNkFromNsk(String httpNode, String nsk) { try { String requestUrl = "http://" + httpNode + "/wallet/getnkfromnsk"; @@ -3595,9 +3405,7 @@ public static HttpResponse getNkFromNsk(String httpNode, String nsk) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getIncomingViewingKey(String httpNode, String ak, String nk) { try { String requestUrl = "http://" + httpNode + "/wallet/getincomingviewingkey"; @@ -3613,9 +3421,7 @@ public static HttpResponse getIncomingViewingKey(String httpNode, String ak, Str return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getNewShieldedAddress(String httpNode) { try { String requestUrl = "http://" + httpNode + "/wallet/getnewshieldedaddress"; @@ -3628,10 +3434,7 @@ public static HttpResponse getNewShieldedAddress(String httpNode) { return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getZenPaymentAddress(String httpNode, String ivk, String d) { try { String requestUrl = "http://" + httpNode + "/wallet/getzenpaymentaddress"; @@ -3647,16 +3450,16 @@ public static HttpResponse getZenPaymentAddress(String httpNode, String ivk, Str return response; } - /** - * constructor. - */ - public static HttpResponse getMerkleTreeVoucherInfo(String httpNode, String hash, Integer index, - int blockNum) { + /** 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))) + 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(); @@ -3670,16 +3473,16 @@ public static HttpResponse getMerkleTreeVoucherInfo(String httpNode, String hash return response; } - /** - * constructor. - */ - public static HttpResponse getMerkleTreeVoucherInfoFromSolidity(String httpSolidityNode, - String hash, Integer index, int blockNum) { + /** 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))) + 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(); @@ -3693,16 +3496,16 @@ public static HttpResponse getMerkleTreeVoucherInfoFromSolidity(String httpSolid return response; } - /** - * constructor. - */ - public static HttpResponse getMerkleTreeVoucherInfoFromPbft(String httpSolidityNode, String hash, - Integer index, int blockNum) { + /** 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))) + 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(); @@ -3716,13 +3519,16 @@ public static HttpResponse getMerkleTreeVoucherInfoFromPbft(String httpSolidityN return response; } - - /** - * constructor. - */ - public static HttpResponse sendShieldCoin(String httpNode, byte[] publicZenTokenOwnerAddress, - long fromAmount, ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx, - List shieldOutputList, byte[] publicZenTokenToAddress, long toAmount, + /** 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"; @@ -3733,8 +3539,9 @@ public static HttpResponse sendShieldCoin(String httpNode, byte[] publicZenToken map.put("from_amount", fromAmount); } if (shieldAddressInfo != null) { - HttpResponse expandedSpendingKey = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.getSk())); + HttpResponse expandedSpendingKey = + HttpMethed.getExpandedSpendingKey( + httpNode, ByteArray.toHexString(shieldAddressInfo.getSk())); responseContent = HttpMethed.parseResponseContent(expandedSpendingKey); HttpMethed.printJsonContent(responseContent); String ovk = responseContent.getString("ovk"); @@ -3742,19 +3549,25 @@ public static HttpResponse sendShieldCoin(String httpNode, byte[] publicZenToken map.put("nsk", responseContent.getString("nsk")); map.put("ovk", ovk); - response = HttpMethed - .getMerkleTreeVoucherInfo(httpNode, noteTx.getTrxId(), noteTx.getIndex(), 1); + 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))); + 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 { @@ -3774,7 +3587,8 @@ public static HttpResponse sendShieldCoin(String httpNode, byte[] publicZenToken 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", + noteInfo.put( + "memo", ByteArray.toHexString(shieldOutputList.get(i).getMemo().toStringUtf8().getBytes())); final Map note = new HashMap(); note.put("note", noteInfo); @@ -3804,16 +3618,14 @@ public static HttpResponse sendShieldCoin(String httpNode, byte[] publicZenToken return response; } - /** - * constructor. - */ - public static Boolean getSpendResult(String httpNode, ShieldAddressInfo shieldAddressInfo, - ShieldNoteInfo noteTx) { + /** 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)); + response = + HttpMethed.getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); responseContent = HttpMethed.parseResponseContent(response); String ask = responseContent.getString("ask"); response = HttpMethed.getAkFromAsk(httpNode, ask); @@ -3826,10 +3638,15 @@ public static Boolean getSpendResult(String httpNode, ShieldAddressInfo shieldAd 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()); + 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(); @@ -3839,8 +3656,9 @@ public static Boolean getSpendResult(String httpNode, ShieldAddressInfo shieldAd 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"))) { + 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; @@ -3852,16 +3670,17 @@ public static Boolean getSpendResult(String httpNode, ShieldAddressInfo shieldAd } } - /** - * constructor. - */ - public static Boolean getSpendResultFromSolidity(String httpNode, String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx) { + /** 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)); + response = + HttpMethed.getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); responseContent = HttpMethed.parseResponseContent(response); String ask = responseContent.getString("ask"); response = HttpMethed.getAkFromAsk(httpNode, ask); @@ -3874,10 +3693,15 @@ public static Boolean getSpendResultFromSolidity(String httpNode, String httpSol 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()); + 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(); @@ -3887,8 +3711,9 @@ 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"))) { + 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; @@ -3900,17 +3725,18 @@ public static Boolean getSpendResultFromSolidity(String httpNode, String httpSol } } - /** - * constructor. - */ - public static Boolean getSpendResultFromPbft(String httpNode, String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo, ShieldNoteInfo noteTx) { + /** 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)); + response = + HttpMethed.getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); responseContent = HttpMethed.parseResponseContent(response); String ask = responseContent.getString("ask"); final String nsk = responseContent.getString("nsk"); @@ -3920,10 +3746,15 @@ public static Boolean getSpendResultFromPbft(String httpNode, String httpSolidit 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()); + 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()); @@ -3931,8 +3762,9 @@ public static Boolean getSpendResultFromPbft(String httpNode, String httpSolidit 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"))) { + 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; @@ -3944,18 +3776,16 @@ public static Boolean getSpendResultFromPbft(String httpNode, String httpSolidit } } - /** - * constructor. - */ - public static List scanNoteByOvkFromPbft(String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo) { + /** 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(); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -3996,19 +3826,16 @@ public static List scanNoteByOvkFromPbft(String httpSolidityNode } } - - /** - * constructor. - */ - public static List scanNoteByIvk(String httpNode, - ShieldAddressInfo shieldAddressInfo) { + /** 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(); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -4052,18 +3879,16 @@ public static List scanNoteByIvk(String httpNode, } } - /** - * constructor. - */ - public static List scanNoteByIvkFromSolidity(String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo) { + /** 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(); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -4105,18 +3930,16 @@ public static List scanNoteByIvkFromSolidity(String httpSolidity } } - /** - * constructor. - */ - public static List scanNoteByIvkFromPbft(String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo) { + /** 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(); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -4157,15 +3980,12 @@ public static List scanNoteByIvkFromPbft(String httpSolidityNode } } - - /** - * constructor. - */ - public static List scanAndMarkNoteByIvk(String httpNode, - ShieldAddressInfo shieldAddressInfo) { + /** constructor. */ + public static List scanAndMarkNoteByIvk( + String httpNode, ShieldAddressInfo shieldAddressInfo) { try { - response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + response = + HttpMethed.getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); responseContent = HttpMethed.parseResponseContent(response); String ask = responseContent.getString("ask"); String nsk = responseContent.getString("nsk"); @@ -4181,8 +4001,8 @@ public static List scanAndMarkNoteByIvk(String httpNode, responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -4228,14 +4048,12 @@ public static List scanAndMarkNoteByIvk(String httpNode, } } - /** - * constructor. - */ - public static List scanAndMarkNoteByIvkFromSolidity(String httpNode, - String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { + /** constructor. */ + public static List scanAndMarkNoteByIvkFromSolidity( + String httpNode, String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { try { - response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + response = + HttpMethed.getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); responseContent = HttpMethed.parseResponseContent(response); String ask = responseContent.getString("ask"); String nsk = responseContent.getString("nsk"); @@ -4251,8 +4069,8 @@ public static List scanAndMarkNoteByIvkFromSolidity(String httpN responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -4299,14 +4117,12 @@ public static List scanAndMarkNoteByIvkFromSolidity(String httpN } } - /** - * constructor. - */ - public static List scanAndMarkNoteByIvkFromPbft(String httpNode, - String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { + /** constructor. */ + public static List scanAndMarkNoteByIvkFromPbft( + String httpNode, String httpSolidityNode, ShieldAddressInfo shieldAddressInfo) { try { - response = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); + response = + HttpMethed.getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.sk)); responseContent = HttpMethed.parseResponseContent(response); String ask = responseContent.getString("ask"); String nsk = responseContent.getString("nsk"); @@ -4322,8 +4138,8 @@ public static List scanAndMarkNoteByIvkFromPbft(String httpNode, responseContent = HttpMethed.parseResponseContent(response); HttpMethed.printJsonContent(responseContent); String blockHeaderString = responseContent.getString("block_header"); - String rawDataString = HttpMethed.parseStringContent(blockHeaderString).get("raw_data") - .toString(); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -4367,19 +4183,16 @@ public static List scanAndMarkNoteByIvkFromPbft(String httpNode, } } - - /** - * constructor. - */ - public static List scanNoteByOvk(String httpNode, - ShieldAddressInfo shieldAddressInfo) { + /** 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(); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -4421,18 +4234,16 @@ public static List scanNoteByOvk(String httpNode, } } - /** - * constructor. - */ - public static List scanNoteByOvkFromSolidity(String httpSolidityNode, - ShieldAddressInfo shieldAddressInfo) { + /** 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(); + String rawDataString = + HttpMethed.parseStringContent(blockHeaderString).get("raw_data").toString(); Integer currentBlockNum = HttpMethed.parseStringContent(rawDataString).getInteger("number"); Integer startBlockNum = 0; if (currentBlockNum > 100) { @@ -4474,13 +4285,18 @@ 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, + /** 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 = @@ -4494,8 +4310,9 @@ public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String http String ask = ""; byte[] alpha = null; if (shieldAddressInfo != null) { - HttpResponse expandedSpendingKey = HttpMethed - .getExpandedSpendingKey(httpNode, ByteArray.toHexString(shieldAddressInfo.getSk())); + HttpResponse expandedSpendingKey = + HttpMethed.getExpandedSpendingKey( + httpNode, ByteArray.toHexString(shieldAddressInfo.getSk())); responseContent = HttpMethed.parseResponseContent(expandedSpendingKey); HttpMethed.printJsonContent(responseContent); map.put("nsk", responseContent.getString("nsk")); @@ -4507,17 +4324,17 @@ public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String http map.put("ak", responseContent.getString("value")); logger.info("noteTx.getTrxId():" + noteTx.getTrxId()); - HttpMethed.response = HttpMethed - .getMerkleTreeVoucherInfoFromSolidity(httpSolidityNode, noteTx.getTrxId(), - noteTx.getIndex(), 1); + 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.response = + HttpMethed.getMerkleTreeVoucherInfoFromPbft( + httpPbftNode, noteTx.getTrxId(), noteTx.getIndex(), 1); HttpMethed.responseContent = HttpMethed.parseResponseContent(HttpMethed.response); HttpMethed.printJsonContent(responseContent); JSONArray vouchersPbft = HttpMethed.responseContent.getJSONArray("vouchers"); @@ -4525,13 +4342,19 @@ public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String http 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))); + 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 { @@ -4550,7 +4373,8 @@ public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String http 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", + noteInfo.put( + "memo", ByteArray.toHexString(shieldOutputList.get(i).getMemo().toStringUtf8().getBytes())); final Map note = new HashMap(); note.put("note", noteInfo); @@ -4576,8 +4400,11 @@ public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String http 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); + 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()); @@ -4587,9 +4414,15 @@ public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String http 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); + 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); } @@ -4609,23 +4442,19 @@ public static HttpResponse sendShieldCoinWithoutAsk(String httpNode, String http return response; } - /** - * constructor. - */ - public static void freedResource(String httpNode, byte[] fromAddress, byte[] toAddress, - String fromKey) { + /** constructor. */ + public static void freedResource( + String httpNode, byte[] fromAddress, byte[] toAddress, String fromKey) { long balance = HttpMethed.getBalance(httpNode, fromAddress); - //System.out.println("剩余资源:" + balance); + // System.out.println("剩余资源:" + balance); sendCoin(httpNode, fromAddress, toAddress, balance - 50000, fromKey); balance = HttpMethed.getBalance(httpNode, fromAddress); - //System.out.println("之后资源:" + balance); + // System.out.println("之后资源:" + balance); } - /** - * constructor. - */ - public static HttpResponse updateBrokerage(String httpNode, byte[] ownerAddress, Long brokerage, - String fromKey) { + /** 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(); @@ -4644,11 +4473,9 @@ public static HttpResponse updateBrokerage(String httpNode, byte[] ownerAddress, return response; } - /** - * constructor. - */ - public static HttpResponse updateBrokerageOnVisible(String httpNode, byte[] ownerAddress, - Long brokerage, String fromKey, String visible) { + /** 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(); @@ -4672,9 +4499,7 @@ public static HttpResponse updateBrokerageOnVisible(String httpNode, byte[] owne return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getReward(String httpNode, byte[] address) { try { String requestUrl = "http://" + httpNode + "/wallet/getReward"; @@ -4690,9 +4515,7 @@ public static HttpResponse getReward(String httpNode, byte[] address) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getRewardFromSolidity(String httpSolidityNode, byte[] address) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getReward"; @@ -4708,9 +4531,7 @@ public static HttpResponse getRewardFromSolidity(String httpSolidityNode, byte[] return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getRewardFromPbft(String httpSolidityNode, byte[] address) { try { String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getReward"; @@ -4726,10 +4547,7 @@ public static HttpResponse getRewardFromPbft(String httpSolidityNode, byte[] add return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getBrokerage(String httpNode, byte[] address) { try { String requestUrl = "http://" + httpNode + "/wallet/getBrokerage"; @@ -4745,9 +4563,7 @@ public static HttpResponse getBrokerage(String httpNode, byte[] address) { return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getBrokerageFromSolidity(String httpSolidityNode, byte[] address) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getBrokerage"; @@ -4763,9 +4579,7 @@ public static HttpResponse getBrokerageFromSolidity(String httpSolidityNode, byt return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getRewardOnVisible(String httpNode, byte[] address, String visible) { try { final String requestUrl = "http://" + httpNode + "/wallet/getReward"; @@ -4786,11 +4600,9 @@ public static HttpResponse getRewardOnVisible(String httpNode, byte[] address, S return response; } - /** - * constructor. - */ - public static HttpResponse getRewardFromSolidityOnVisible(String httpSolidityNode, byte[] address, - String visible) { + /** constructor. */ + public static HttpResponse getRewardFromSolidityOnVisible( + String httpSolidityNode, byte[] address, String visible) { try { final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getReward"; JsonObject userBaseObj2 = new JsonObject(); @@ -4810,11 +4622,9 @@ public static HttpResponse getRewardFromSolidityOnVisible(String httpSolidityNod return response; } - /** - * constructor. - */ - public static HttpResponse getBrokerageOnVisible(String httpNode, byte[] address, - String visible) { + /** constructor. */ + public static HttpResponse getBrokerageOnVisible( + String httpNode, byte[] address, String visible) { try { final String requestUrl = "http://" + httpNode + "/wallet/getBrokerage"; JsonObject userBaseObj2 = new JsonObject(); @@ -4834,11 +4644,9 @@ public static HttpResponse getBrokerageOnVisible(String httpNode, byte[] address return response; } - /** - * constructor. - */ - public static HttpResponse getBrokerageFromSolidityOnVisible(String httpSolidityNode, - byte[] address, String visible) { + /** constructor. */ + public static HttpResponse getBrokerageFromSolidityOnVisible( + String httpSolidityNode, byte[] address, String visible) { try { final String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getBrokerage"; JsonObject userBaseObj2 = new JsonObject(); @@ -4858,9 +4666,7 @@ public static HttpResponse getBrokerageFromSolidityOnVisible(String httpSolidity return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getBrokerageFromPbft(String httpSolidityNode, byte[] address) { try { final String requestUrl = "http://" + httpSolidityNode + "/walletpbft/getBrokerage"; @@ -4875,12 +4681,15 @@ public static HttpResponse getBrokerageFromPbft(String httpSolidityNode, byte[] return response; } - /** - * constructor. - */ - public static String marketSellAssetGetTxId(String httpNode, byte[] ownerAddress, + /** constructor. */ + public static String marketSellAssetGetTxId( + String httpNode, + byte[] ownerAddress, String sellTokenId, - Long sellTokenQuantity, String buyTokenId, Long buyTokenQuantity, String fromKey, + Long sellTokenQuantity, + String buyTokenId, + Long buyTokenQuantity, + String fromKey, String visible) { try { final String requestUrl = "http://" + httpNode + "/wallet/marketsellasset"; @@ -4912,9 +4721,7 @@ public static String marketSellAssetGetTxId(String httpNode, byte[] ownerAddress return responseContent.getString("txID"); } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getMarketOrderById(String httpNode, String orderId, String visible) { try { String requestUrl = "http://" + httpNode + "/wallet/getmarketorderbyid"; @@ -4930,11 +4737,9 @@ public static HttpResponse getMarketOrderById(String httpNode, String orderId, S return response; } - /** - * constructor. - */ - public static HttpResponse getMarketOrderByIdFromSolidity(String httpSolidityNode, String orderId, - String visible) { + /** constructor. */ + public static HttpResponse getMarketOrderByIdFromSolidity( + String httpSolidityNode, String orderId, String visible) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderbyid"; JsonObject userBaseObj2 = new JsonObject(); @@ -4949,11 +4754,9 @@ public static HttpResponse getMarketOrderByIdFromSolidity(String httpSolidityNod return response; } - /** - * constructor. - */ - public static HttpResponse getMarketOrderByIdFromPbft(String httpPbftNode, String orderId, - String visible) { + /** constructor. */ + public static HttpResponse getMarketOrderByIdFromPbft( + String httpPbftNode, String orderId, String visible) { try { String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderbyid"; JsonObject userBaseObj2 = new JsonObject(); @@ -4968,11 +4771,9 @@ public static HttpResponse getMarketOrderByIdFromPbft(String httpPbftNode, Strin return response; } - /** - * constructor. - */ - public static String marketCancelOrder(String httpNode, byte[] ownerAddress, String orderId, - String fromKey, String visible) { + /** 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(); @@ -4998,11 +4799,9 @@ public static String marketCancelOrder(String httpNode, byte[] ownerAddress, Str return responseContent.getString("txID"); } - /** - * constructor. - */ - public static HttpResponse getMarketOrderByAccount(String httpNode, byte[] ownerAddress, - String visible) { + /** constructor. */ + public static HttpResponse getMarketOrderByAccount( + String httpNode, byte[] ownerAddress, String visible) { try { String requestUrl = "http://" + httpNode + "/wallet/getmarketorderbyaccount"; JsonObject userBaseObj2 = new JsonObject(); @@ -5021,11 +4820,9 @@ public static HttpResponse getMarketOrderByAccount(String httpNode, byte[] owner return response; } - /** - * constructor. - */ - public static HttpResponse getMarketOrderByAccountFromSolidity(String httpSolidityNode, - byte[] ownerAddress, String visible) { + /** constructor. */ + public static HttpResponse getMarketOrderByAccountFromSolidity( + String httpSolidityNode, byte[] ownerAddress, String visible) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderbyaccount"; JsonObject userBaseObj2 = new JsonObject(); @@ -5044,11 +4841,9 @@ public static HttpResponse getMarketOrderByAccountFromSolidity(String httpSolidi return response; } - /** - * constructor. - */ - public static HttpResponse getMarketOrderByAccountFromPbft(String httpPbftNode, - byte[] ownerAddress, String visible) { + /** constructor. */ + public static HttpResponse getMarketOrderByAccountFromPbft( + String httpPbftNode, byte[] ownerAddress, String visible) { try { String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderbyaccount"; JsonObject userBaseObj2 = new JsonObject(); @@ -5067,9 +4862,7 @@ public static HttpResponse getMarketOrderByAccountFromPbft(String httpPbftNode, return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getMarketPairList(String httpNode, String visible) { try { String requestUrl = "http://" + httpNode + "/wallet/getmarketpairlist"; @@ -5084,11 +4877,9 @@ public static HttpResponse getMarketPairList(String httpNode, String visible) { return response; } - /** - * constructor. - */ - public static HttpResponse getMarketPairListFromSolidity(String httpSolidityNode, - String visible) { + /** constructor. */ + public static HttpResponse getMarketPairListFromSolidity( + String httpSolidityNode, String visible) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketpairlist"; JsonObject userBaseObj2 = new JsonObject(); @@ -5102,9 +4893,7 @@ public static HttpResponse getMarketPairListFromSolidity(String httpSolidityNode return response; } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getMarketPairListFromPbft(String httpPbftNode, String visible) { try { String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketpairlist"; @@ -5119,11 +4908,9 @@ public static HttpResponse getMarketPairListFromPbft(String httpPbftNode, String return response; } - /** - * constructor. - */ - public static HttpResponse getMarketOrderListByPair(String httpNode, String sellTokenId, - String buyTokenId, String visible) { + /** constructor. */ + public static HttpResponse getMarketOrderListByPair( + String httpNode, String sellTokenId, String buyTokenId, String visible) { try { String requestUrl = "http://" + httpNode + "/wallet/getmarketorderlistbypair"; JsonObject userBaseObj2 = new JsonObject(); @@ -5144,12 +4931,9 @@ public static HttpResponse getMarketOrderListByPair(String httpNode, String sell return response; } - /** - * constructor. - */ - public static HttpResponse getMarketOrderListByPairFromSolidity(String httpSolidityNode, - String sellTokenId, - String buyTokenId, String visible) { + /** constructor. */ + public static HttpResponse getMarketOrderListByPairFromSolidity( + String httpSolidityNode, String sellTokenId, String buyTokenId, String visible) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketorderlistbypair"; JsonObject userBaseObj2 = new JsonObject(); @@ -5170,11 +4954,9 @@ public static HttpResponse getMarketOrderListByPairFromSolidity(String httpSolid return response; } - /** - * constructor. - */ - public static HttpResponse getMarketOrderListByPairFromPbft(String httpPbftNode, - String sellTokenId, String buyTokenId, String visible) { + /** constructor. */ + public static HttpResponse getMarketOrderListByPairFromPbft( + String httpPbftNode, String sellTokenId, String buyTokenId, String visible) { try { String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketorderlistbypair"; JsonObject userBaseObj2 = new JsonObject(); @@ -5195,11 +4977,9 @@ public static HttpResponse getMarketOrderListByPairFromPbft(String httpPbftNode, return response; } - /** - * constructor. - */ - public static HttpResponse getMarketPriceByPair(String httpNode, String sellTokenId, - String buyTokenId, String visible) { + /** constructor. */ + public static HttpResponse getMarketPriceByPair( + String httpNode, String sellTokenId, String buyTokenId, String visible) { try { String requestUrl = "http://" + httpNode + "/wallet/getmarketpricebypair"; JsonObject userBaseObj2 = new JsonObject(); @@ -5220,12 +5000,9 @@ public static HttpResponse getMarketPriceByPair(String httpNode, String sellToke return response; } - /** - * constructor. - */ - public static HttpResponse getMarketPriceByPairFromSolidity(String httpSolidityNode, - String sellTokenId, - String buyTokenId, String visible) { + /** constructor. */ + public static HttpResponse getMarketPriceByPairFromSolidity( + String httpSolidityNode, String sellTokenId, String buyTokenId, String visible) { try { String requestUrl = "http://" + httpSolidityNode + "/walletsolidity/getmarketpricebypair"; JsonObject userBaseObj2 = new JsonObject(); @@ -5246,11 +5023,9 @@ public static HttpResponse getMarketPriceByPairFromSolidity(String httpSolidityN return response; } - /** - * constructor. - */ - public static HttpResponse getMarketPriceByPairFromPbft(String httpPbftNode, - String sellTokenId, String buyTokenId, String visible) { + /** constructor. */ + public static HttpResponse getMarketPriceByPairFromPbft( + String httpPbftNode, String sellTokenId, String buyTokenId, String visible) { try { String requestUrl = "http://" + httpPbftNode + "/walletpbft/getmarketpricebypair"; JsonObject userBaseObj2 = new JsonObject(); @@ -5271,9 +5046,7 @@ public static HttpResponse getMarketPriceByPairFromPbft(String httpPbftNode, return response; } - /** - * constructor. - */ + /** constructor. */ public static int getTransactionPendingSize(String httpNode) { try { String requestUrl = "http://" + httpNode + "/wallet/getpendingsize"; @@ -5288,9 +5061,7 @@ public static int getTransactionPendingSize(String httpNode) { return responseContent.getInteger("pendingSize"); } - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getTransactionListFromPending(String httpNode) { try { String requestUrl = "http://" + httpNode + "/wallet/gettransactionlistfrompending"; @@ -5304,10 +5075,7 @@ public static HttpResponse getTransactionListFromPending(String httpNode) { return response; } - - /** - * constructor. - */ + /** constructor. */ public static HttpResponse getTransactionFromPending(String httpNode, String txid) { try { String requestUrl = "http://" + httpNode + "/wallet/gettransactionfrompending"; @@ -5321,9 +5089,4 @@ public static HttpResponse getTransactionFromPending(String httpNode, String txi } return response; } - - - - - } 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 98bffa9eed8..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 @@ -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; @@ -55,10 +56,12 @@ 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 = - 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); @@ -68,7 +71,6 @@ public class JsonRpcBase { 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 = @@ -106,7 +108,6 @@ public class JsonRpcBase { public static String blockId; public static String txid; public static String trc20Txid; - public static String NewFilterId; /** constructor. */ @BeforeSuite(enabled = true, description = "Deploy json rpc test case resource") 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..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 @@ -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,25 +141,45 @@ public class PublicMethed { - //Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + // 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; + // 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(); - - /** - * 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, + public static volatile Integer witnessNum; + + /** constructor. */ + public static Integer getWitnessNum(WalletGrpc.WalletBlockingStub blockingStubFull) { + if (null == witnessNum) { + witnessNum = PublicMethed.listWitnesses(blockingStubFull).get().getWitnessesList().size(); + } + + return witnessNum; + } + + /** constructor. */ + public static String createAssetIssueGetTxid( + byte[] address, + String name, + String abbreviation, + Long totalSupply, + Integer trxNum, + Integer icoNum, + Long startTime, + Long endTime, + Integer voteScore, + String description, + String url, + Long freeAssetNetLimit, + Long publicFreeAssetNetLimit, + Long fronzenAmount, + Long frozenDay, + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; @@ -183,8 +205,8 @@ public static String createAssetIssueGetTxid(byte[] address, String name, String builder.setUrl(ByteString.copyFrom(url.getBytes())); builder.setFreeAssetNetLimit(freeAssetNetLimit); builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); + AssetIssueContract.FrozenSupply.Builder frozenBuilder = + AssetIssueContract.FrozenSupply.newBuilder(); frozenBuilder.setFrozenAmount(fronzenAmount); frozenBuilder.setFrozenDays(frozenDay); builder.addFrozenSupply(0, frozenBuilder); @@ -198,8 +220,9 @@ public static String createAssetIssueGetTxid(byte[] address, String name, String GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); } catch (Exception ex) { ex.printStackTrace(); @@ -207,14 +230,23 @@ 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, + /** 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; @@ -239,8 +271,8 @@ public static Boolean createAssetIssue(byte[] address, String name, Long totalSu builder.setUrl(ByteString.copyFrom(url.getBytes())); builder.setFreeAssetNetLimit(freeAssetNetLimit); builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); + AssetIssueContract.FrozenSupply.Builder frozenBuilder = + AssetIssueContract.FrozenSupply.newBuilder(); frozenBuilder.setFrozenAmount(fronzenAmount); frozenBuilder.setFrozenDays(frozenDay); builder.addFrozenSupply(0, frozenBuilder); @@ -261,14 +293,24 @@ public static Boolean createAssetIssue(byte[] address, String name, Long totalSu } } - /** - * 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, + /** 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; @@ -294,8 +336,8 @@ public static Boolean createAssetIssue(byte[] address, String name, String abbre builder.setUrl(ByteString.copyFrom(url.getBytes())); builder.setFreeAssetNetLimit(freeAssetNetLimit); builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); + AssetIssueContract.FrozenSupply.Builder frozenBuilder = + AssetIssueContract.FrozenSupply.newBuilder(); frozenBuilder.setFrozenAmount(fronzenAmount); frozenBuilder.setFrozenDays(frozenDay); builder.addFrozenSupply(0, frozenBuilder); @@ -316,14 +358,24 @@ public static Boolean createAssetIssue(byte[] address, String name, String abbre } } - /** - * 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, + /** 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; @@ -349,8 +401,8 @@ public static Boolean createAssetIssue(byte[] address, String name, Long totalSu builder.setUrl(ByteString.copyFrom(url.getBytes())); builder.setFreeAssetNetLimit(freeAssetNetLimit); builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); + AssetIssueContract.FrozenSupply.Builder frozenBuilder = + AssetIssueContract.FrozenSupply.newBuilder(); frozenBuilder.setFrozenAmount(fronzenAmount); frozenBuilder.setFrozenDays(frozenDay); builder.addFrozenSupply(0, frozenBuilder); @@ -371,14 +423,23 @@ public static Boolean createAssetIssue(byte[] address, String name, Long totalSu } } - /** - * 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, + /** 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; @@ -389,7 +450,7 @@ public static Return createAssetIssue2(byte[] address, String name, Long totalSu ex.printStackTrace(); } ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(ecKey, blockingStubFull); + // Protocol.Account search = queryAccount(ecKey, blockingStubFull); try { AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); builder.setOwnerAddress(ByteString.copyFrom(address)); @@ -404,16 +465,16 @@ public static Return createAssetIssue2(byte[] address, String name, Long totalSu builder.setUrl(ByteString.copyFrom(url.getBytes())); builder.setFreeAssetNetLimit(freeAssetNetLimit); builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - //builder.setPublicFreeAssetNetUsage(); - //builder.setPublicLatestFreeNetTime(); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); + // 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()); + TransactionExtention transactionExtention = + blockingStubFull.createAssetIssue2(builder.build()); if (transactionExtention == null) { return transactionExtention.getResult(); @@ -449,42 +510,32 @@ public static Return createAssetIssue2(byte[] address, String name, Long totalSu return ret; } catch (Exception ex) { ex.printStackTrace(); - //return false; + // return false; return Return.getDefaultInstance(); } } - /** - * constructor. - */ - - public static Account queryAccountByAddress(byte[] address, - WalletGrpc.WalletBlockingStub 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, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** constructor. */ + public static Account queryAccount( + byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString addressBs = ByteString.copyFrom(address); Account request = Account.newBuilder().setAddress(addressBs).build(); return blockingStubFull.getAccount(request); } - - /** - * constructor. - */ - - public static Protocol.Account queryAccount(String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** constructor. */ + public static Protocol.Account queryAccount( + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); byte[] address; ECKey temKey = null; @@ -496,7 +547,7 @@ public static Protocol.Account queryAccount(String priKey, } ECKey ecKey = temKey; if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] + String pubKey = loadPubKey(); // 04 PubKey[128] if (StringUtils.isEmpty(pubKey)) { logger.warn("Warning: QueryAccount failed, no wallet address !!"); return null; @@ -508,138 +559,116 @@ public static Protocol.Account queryAccount(String priKey, return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); } - /** - * constructor. - */ - public static Account queryAccount(byte[] address, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + /** constructor. */ + public static Account queryAccount( + byte[] address, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString addressBs = ByteString.copyFrom(address); Account request = Account.newBuilder().setAddress(addressBs).build(); return blockingStubFull.getAccount(request); } - /** - * constructor. - */ - - public static Account getAccountById(String accountId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** constructor. */ + public static Account getAccountById( + String accountId, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString bsAccountId = ByteString.copyFromUtf8(accountId); Account request = Account.newBuilder().setAccountId(bsAccountId).build(); return blockingStubFull.getAccountById(request); } - /** - * constructor. - */ - - public static Account getAccountByIdFromSolidity(String accountId, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + /** 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. - */ + /** 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 byte[] getAddress(ECKey ecKey) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); return ecKey.getAddress(); } - /** - * constructor. - */ - - public static Protocol.Account grpcQueryAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** constructor. */ + public static Protocol.Account grpcQueryAccount( + byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString addressBs = ByteString.copyFrom(address); Protocol.Account request = Protocol.Account.newBuilder().setAddress(addressBs).build(); return blockingStubFull.getAccount(request); } - /** - * constructor. - */ - - public static Protocol.Block getBlock(long blockNum, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** constructor. */ + public static Protocol.Block getBlock( + long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); builder.setNum(blockNum); return blockingStubFull.getBlockByNum(builder.build()); } - /** - * constructor. - */ - - public static BlockExtention getBlock2(long blockNum, - WalletBlockingStub blockingStubFull) { + /** constructor. */ + public static BlockExtention getBlock2(long blockNum, WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); builder.setNum(blockNum); return blockingStubFull.getBlockByNum2(builder.build()); } - /** - * constructor. - */ - - public static Protocol.Transaction signTransaction(ECKey ecKey, - Protocol.Transaction transaction) { + /** 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 !!"); + // 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()))); + logger.info( + "Txid in sign is " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); return TransactionUtils.sign(transaction, ecKey); } - /** - * constructor. - */ - - public static Protocol.Transaction signTransactionForShield(ECKey ecKey, - Protocol.Transaction transaction) { + /** 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 !!"); + // 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()))); + logger.info( + "Txid in sign is " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); return TransactionUtils.sign(transaction, ecKey); } - - /** - * constructor. - */ - - public static boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, - byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -665,12 +694,14 @@ public static boolean participateAssetIssue(byte[] to, byte[] assertName, long a return response.getResult(); } - /** - * constructor. - */ - - public static Return participateAssetIssue2(byte[] to, byte[] assertName, long amount, - byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -709,7 +740,7 @@ public static Return participateAssetIssue2(byte[] to, byte[] assertName, long a System.out.println( "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - //Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); + // Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); @@ -720,17 +751,18 @@ public static Return participateAssetIssue2(byte[] to, byte[] assertName, long a } } - /** - * constructor. - */ - - public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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; + // String priKey = testKey002; ECKey temKey = null; try { BigInteger priK = new BigInteger(priKey, 16); @@ -739,23 +771,25 @@ public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long fre ex.printStackTrace(); } final ECKey ecKey = temKey; - Protocol.Block currentBlock = blockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + 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(); + // Long beforeBandwidth = beforeFronzen.getBandwidth(); if (beforeFronzen.getFrozenCount() != 0) { beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); + // 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) + builder + .setOwnerAddress(byteAddreess) + .setFrozenBalance(frozenBalance) .setFrozenDuration(frozenDuration); FreezeBalanceContract contract = builder.build(); @@ -787,17 +821,18 @@ public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long fre Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance);*/ } - /** - * constructor. - */ - - public static Return freezeBalance2(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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; + // String priKey = testKey002; ECKey temKey = null; try { BigInteger priK = new BigInteger(priKey, 16); @@ -806,23 +841,25 @@ public static Return freezeBalance2(byte[] addRess, long freezeBalance, long fre ex.printStackTrace(); } final ECKey ecKey = temKey; - Protocol.Block currentBlock = blockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + 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(); + // Long beforeBandwidth = beforeFronzen.getBandwidth(); if (beforeFronzen.getFrozenCount() != 0) { beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); + // 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) + builder + .setOwnerAddress(byteAddreess) + .setFrozenBalance(frozenBalance) .setFrozenDuration(frozenDuration); FreezeBalanceContract contract = builder.build(); @@ -859,8 +896,8 @@ public static Return freezeBalance2(byte[] addRess, long freezeBalance, long fre Long afterBlockNum = 0L; while (afterBlockNum < beforeBlockNum) { - Protocol.Block currentBlock1 = blockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Protocol.Block currentBlock1 = + blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); } @@ -868,18 +905,21 @@ 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; } - /** - * constructor. - */ - - public static Boolean unFreezeBalance(byte[] address, String priKey, int resourceCode, - byte[] receiverAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -905,14 +945,15 @@ public static Boolean unFreezeBalance(byte[] address, String priKey, int resourc return response.getResult(); } - /** - * constructor. - */ - - public static Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey, + /** 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; + // String priKey = testKey002; ECKey temKey = null; try { BigInteger priK = new BigInteger(priKey, 16); @@ -945,12 +986,13 @@ public static Boolean sendcoin(byte[] to, long amount, byte[] owner, String priK return false; } - /** - * constructor. - */ - - public static String sendcoinGetTransactionHex(byte[] to, long amount, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -974,21 +1016,18 @@ public static String sendcoinGetTransactionHex(byte[] to, long amount, byte[] ow 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())); + 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) { + /** 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 { @@ -1034,12 +1073,9 @@ public static Boolean cancelDeferredTransactionById(String txid, byte[] owner, S return null; } - /** - * constructor. - */ - - public static String cancelDeferredTransactionByIdGetTxid(String txid, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -1052,13 +1088,14 @@ public static String cancelDeferredTransactionByIdGetTxid(String txid, byte[] ow return null; } - - /** - * constructor. - */ - - public static Boolean sendcoinDelayed(byte[] to, long amount, long delaySeconds, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -1079,26 +1116,31 @@ public static Boolean sendcoinDelayed(byte[] to, long amount, long delaySeconds, TransferContract contract = builder.build(); Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + // 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()))); + 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, + /** 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; @@ -1121,7 +1163,7 @@ public static boolean transferAssetDelay(byte[] to, byte[] assertName, long amou 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) { @@ -1132,19 +1174,23 @@ public static boolean transferAssetDelay(byte[] to, byte[] assertName, long amou return false; } transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + 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 response.getResult(); } - /** - * constructor. - */ - - public static String createAccountDelayGetTxid(byte[] ownerAddress, byte[] newAddress, - Long delaySeconds, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -1161,26 +1207,31 @@ public static String createAccountDelayGetTxid(byte[] ownerAddress, byte[] newAd builder.setAccountAddress(ByteString.copyFrom(newAddress)); AccountCreateContract contract = builder.build(); Transaction transaction = blockingStubFull.createAccount(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + // 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()))); + 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(), + 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) { + /** 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 { @@ -1200,26 +1251,30 @@ public static String updateAccountDelayGetTxid(byte[] addressBytes, byte[] accou AccountUpdateContract contract = builder.build(); Protocol.Transaction transaction = blockingStubFull.updateAccount(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + // 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()))); + 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(), + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); } - /** - * constructor. - */ - - public static String unfreezeAssetDelayGetTxid(byte[] address, Long delaySeconds, String priKey, + /** 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; @@ -1237,28 +1292,33 @@ public static String unfreezeAssetDelayGetTxid(byte[] address, Long delaySeconds UnfreezeAssetContract contract = builder.build(); Protocol.Transaction transaction = blockingStubFull.unfreezeAsset(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + // 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()))); + 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(), + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); } - - /** - * constructor. - */ - - public static String transferAssetDelayGetTxid(byte[] to, byte[] assertName, long amount, - long delaySeconds, byte[] address, String priKey, + /** 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; @@ -1281,7 +1341,7 @@ public static String transferAssetDelayGetTxid(byte[] to, byte[] assertName, lon 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) { @@ -1292,22 +1352,27 @@ public static String transferAssetDelayGetTxid(byte[] to, byte[] assertName, lon return null; } transaction = signTransaction(ecKey, transaction); - logger.info("Txid is " + 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(), + 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) { + /** 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 { @@ -1328,28 +1393,33 @@ public static String sendcoinDelayedGetTxid(byte[] to, long amount, long delaySe TransferContract contract = builder.build(); Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + // 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()))); + 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(), + 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) { + /** 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 { @@ -1368,29 +1438,35 @@ public static String setAccountIdDelayGetTxid(byte[] accountIdBytes, long delayS builder.setOwnerAddress(bsAddress); SetAccountIdContract contract = builder.build(); Transaction transaction = blockingStubFull.setAccountId(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + // 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()))); + 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(), + 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, + /** 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; @@ -1411,27 +1487,31 @@ public static String updateAssetDelay(byte[] address, byte[] description, byte[] UpdateAssetContract contract = builder.build(); Protocol.Transaction transaction = blockingStubFull.updateAsset(contract); - //transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); + // 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()))); + 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(), + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); } - - /** - * constructor. - */ - - public static Return sendcoin2(byte[] to, long amount, byte[] owner, String priKey, + /** 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; @@ -1442,7 +1522,7 @@ public static Return sendcoin2(byte[] to, long amount, byte[] owner, String priK ex.printStackTrace(); } final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); + // Protocol.Account search = queryAccount(priKey, blockingStubFull); TransferContract.Builder builder = TransferContract.newBuilder(); ByteString bsTo = ByteString.copyFrom(to); @@ -1484,14 +1564,15 @@ public static Return sendcoin2(byte[] to, long amount, byte[] owner, String priK return ret; } - /** - * constructor. - */ - - public static String sendcoinGetTransactionId(byte[] to, long amount, byte[] owner, String priKey, + /** 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; + // String priKey = testKey002; ECKey temKey = null; try { BigInteger priK = new BigInteger(priKey, 16); @@ -1500,7 +1581,7 @@ public static String sendcoinGetTransactionId(byte[] to, long amount, byte[] own ex.printStackTrace(); } final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); + // Protocol.Account search = queryAccount(priKey, blockingStubFull); TransferContract.Builder builder = TransferContract.newBuilder(); ByteString bsTo = ByteString.copyFrom(to); @@ -1515,7 +1596,7 @@ public static String sendcoinGetTransactionId(byte[] to, long amount, byte[] own logger.info("transaction ==null"); return null; } - //Test raw data + // Test raw data /* Protocol.Transaction.raw.Builder builder1 = transaction.getRawData().toBuilder(); builder1.setData(ByteString.copyFromUtf8("12345678")); Transaction.Builder builder2 = transaction.toBuilder(); @@ -1525,21 +1606,19 @@ public static String sendcoinGetTransactionId(byte[] to, long amount, byte[] own transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); if (response.getResult() == false) { - //logger.info(ByteArray.toStr(response.getMessage().toByteArray())); + // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); return null; } else { - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); } } - /** - * constructor. - */ - - public static Optional getTransactionById(String txId, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + /** 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); @@ -1547,23 +1626,18 @@ public static Optional getTransactionById(String txId, return Optional.ofNullable(transaction); } - /** - * constructor. - */ - - public static Optional getTransactionById(String txId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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) { + /** 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()) { @@ -1575,7 +1649,6 @@ public static Long getAssetBalanceByAssetId(ByteString assetId, String priKey, return assetOwnerAssetBalance; } - /* public static Optional getDeferredTransactionById(String txId, WalletGrpc.WalletBlockingStub blockingStubFull) { @@ -1589,35 +1662,32 @@ public static Optional getDeferredTransactionById(String tx } */ - - /** - * constructor. - */ - - public static Optional getTransactionByIdSolidity(String txId, - WalletGrpc.WalletBlockingStub blockingStubSolidity) { + /** 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. - */ - + /** constructor. */ public static String printTransaction(Transaction transaction) { String result = ""; result += "hash: "; result += "\n"; - result += ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.toByteArray())); + 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 += + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray())); result += "\n"; if (transaction.getRawData() != null) { @@ -1633,22 +1703,22 @@ public static String printTransaction(Transaction transaction) { return result; } - /** - * constructor. - */ - + /** constructor. */ public static long printTransactionRow(Transaction.raw raw) { long timestamp = raw.getTimestamp(); return timestamp; } - /** - * constructor. - */ - - public static boolean updateAsset(byte[] address, byte[] description, byte[] url, long newLimit, - long newPublicLimit, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -1678,12 +1748,15 @@ public static boolean updateAsset(byte[] address, byte[] description, byte[] url return response.getResult(); } - /** - * constructor. - */ - - public static Return updateAsset2(byte[] address, byte[] description, byte[] url, long newLimit, - long newPublicLimit, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -1727,18 +1800,20 @@ public static Return updateAsset2(byte[] address, byte[] description, byte[] url transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); if (response.getResult() == false) { - //logger.info(ByteArray.toStr(response.getMessage().toByteArray())); + // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); return response; } return ret; } - /** - * constructor. - */ - - public static boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -1775,12 +1850,11 @@ public static boolean transferAsset(byte[] to, byte[] assertName, long amount, b return response.getResult(); } - - /** - * constructor. - */ - - public static boolean updateAccount(byte[] addressBytes, byte[] accountNameBytes, String priKey, + /** 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; @@ -1811,30 +1885,32 @@ public static boolean updateAccount(byte[] addressBytes, byte[] accountNameBytes 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()); + 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 <= 24) { + < 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()); + 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; @@ -1844,10 +1920,7 @@ public static boolean waitSolidityNodeSynFullNodeData( 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()); @@ -1857,15 +1930,14 @@ public static boolean waitProduceNextBlock(WalletGrpc.WalletBlockingStub blockin Long nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); Integer wait = 0; - logger.info( - "Block num is " + currentBlock.getBlockHeader().getRawData().getNumber()); + 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"); + // logger.info("Wait to produce next block"); nextBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); if (wait == 45) { @@ -1878,12 +1950,9 @@ public static boolean waitProduceNextBlock(WalletGrpc.WalletBlockingStub blockin return true; } - /** - * constructor. - */ - - public static AccountNetMessage getAccountNet(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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(); @@ -1910,23 +1979,20 @@ 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); + // walletClient.init(0); return walletClient.getAddress(); } - /** - * constructor. - */ - - public static String createAccountGetTxid(byte[] ownerAddress, byte[] newAddress, String priKey, + /** 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; @@ -1952,18 +2018,19 @@ public static String createAccountGetTxid(byte[] ownerAddress, byte[] newAddress if (response.getResult() == false) { return null; } else { - //logger.info("brodacast succesfully"); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + // 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, + /** 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; @@ -1989,11 +2056,11 @@ public static boolean createAccount(byte[] ownerAddress, byte[] newAddress, Stri return response.getResult(); } - /** - * constructor. - */ - - public static Return createAccount2(byte[] ownerAddress, byte[] newAddress, String priKey, + /** 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; @@ -2036,18 +2103,18 @@ public static Return createAccount2(byte[] ownerAddress, byte[] newAddress, Stri transaction = signTransaction(ecKey, transaction); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); if (response.getResult() == false) { - //logger.info(ByteArray.toStr(response.getMessage().toByteArray())); + // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); return response; } return ret; } - /** - * constructor. - */ - - public static boolean voteWitness(byte[] ownerAddress, String priKey, - HashMap witnessMap, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -2058,7 +2125,6 @@ public static boolean voteWitness(byte[] ownerAddress, String priKey, } final ECKey ecKey = temKey; - byte[] owner = ownerAddress; VoteWitnessContract.Builder builder = VoteWitnessContract.newBuilder(); builder.setOwnerAddress(ByteString.copyFrom(owner)); @@ -2093,13 +2159,12 @@ public static boolean voteWitness(byte[] ownerAddress, String priKey, return response.getResult(); } - - /** - * constructor. - */ - - public static boolean createProposal(byte[] ownerAddress, String priKey, - HashMap parametersMap, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -2139,12 +2204,13 @@ public static boolean createProposal(byte[] ownerAddress, String priKey, return response.getResult(); } - /** - * constructor. - */ - - public static boolean approveProposal(byte[] ownerAddress, String priKey, long id, - boolean isAddApproval, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -2183,12 +2249,9 @@ public static boolean approveProposal(byte[] ownerAddress, String priKey, long i return response.getResult(); } - /** - * constructor. - */ - - public static boolean deleteProposal(byte[] ownerAddress, String priKey, long id, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -2227,10 +2290,7 @@ public static boolean deleteProposal(byte[] ownerAddress, String priKey, long id return response.getResult(); } - /** - * constructor. - */ - + /** constructor. */ public static boolean printAddress(String key) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); logger.info(key); @@ -2239,20 +2299,13 @@ public static boolean printAddress(String key) { return true; } - /** - * constructor. - */ - + /** constructor. */ public static String getAddressString(String key) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); return Base58.encode58Check(getFinalAddress(key)); } - /** - * constructor. - */ - - + /** constructor. */ public static ArrayList getAddressInfo(String key) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ArrayList accountList = new ArrayList(); @@ -2262,11 +2315,11 @@ public static ArrayList getAddressInfo(String key) { return accountList; } - /** - * constructor. - */ - - public static boolean setAccountId(byte[] accountIdBytes, byte[] ownerAddress, String priKey, + /** 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; @@ -2294,23 +2347,32 @@ public static boolean setAccountId(byte[] accountIdBytes, byte[] ownerAddress, S return response.getResult(); } - /** - * constructor. - */ - - public static Boolean freezeBalanceGetTronPower(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, ByteString receiverAddress,String priKey, + /** 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 freezeBalanceForReceiver( + addRess, + freezeBalance, + freezeDuration, + resourceCode, + receiverAddress, + priKey, + blockingStubFull); } - /** - * constructor. - */ - - public static Boolean freezeBalanceGetEnergy(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, String priKey, + /** 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; @@ -2328,8 +2390,11 @@ public static Boolean freezeBalanceGetEnergy(byte[] addRess, long freezeBalance, FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); + builder + .setOwnerAddress(byteAddreess) + .setFrozenBalance(frozenBalance) + .setFrozenDuration(frozenDuration) + .setResourceValue(resourceCode); FreezeBalanceContract contract = builder.build(); Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); @@ -2344,22 +2409,20 @@ public static Boolean freezeBalanceGetEnergy(byte[] addRess, long freezeBalance, return response.getResult(); } - /** - * constructor. - */ - public static AccountResourceMessage getAccountResource(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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, + /** 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; @@ -2397,10 +2460,11 @@ public static boolean buyStorage(long quantity, byte[] address, String priKey, return response.getResult(); } - /** - * constructor. - */ - public static boolean sellStorage(long quantity, byte[] address, String priKey, + /** constructor. */ + public static boolean sellStorage( + long quantity, + byte[] address, + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; @@ -2438,14 +2502,22 @@ public static boolean sellStorage(long quantity, byte[] address, String priKey, return response.getResult(); } - /** - * constructor. - */ - public static byte[] deployContractFallbackReceive(String contractName, String abiString, + /** 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 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 { @@ -2462,7 +2534,7 @@ public static byte[] deployContractFallbackReceive(String contractName, String a logger.error("abi is null"); return null; } - //byte[] codeBytes = Hex.decode(code); + // byte[] codeBytes = Hex.decode(code); SmartContract.Builder builder = SmartContract.newBuilder(); builder.setName(contractName); builder.setOriginAddress(ByteString.copyFrom(owner)); @@ -2487,25 +2559,25 @@ public static byte[] deployContractFallbackReceive(String contractName, String a contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); contractBuilder.setCallTokenValue(tokenValue); contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + CreateSmartContract contractDeployContract = + contractBuilder.setNewContract(builder.build()).build(); - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); + 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()); + 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(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -2539,9 +2611,12 @@ public static byte[] deployContractFallbackReceive(String contractName, String a return null; } transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + 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)); @@ -2550,18 +2625,27 @@ public static byte[] deployContractFallbackReceive(String contractName, String a if (response.getResult() == false) { return null; } else { - //logger.info("brodacast succesfully"); + // logger.info("brodacast succesfully"); return contractAddress; } } - /** - * constructor. - */ - public static byte[] deployContract(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, - byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -2578,7 +2662,7 @@ public static byte[] deployContract(String contractName, String abiString, Strin logger.error("abi is null"); return null; } - //byte[] codeBytes = Hex.decode(code); + // byte[] codeBytes = Hex.decode(code); SmartContract.Builder builder = SmartContract.newBuilder(); builder.setName(contractName); builder.setOriginAddress(ByteString.copyFrom(owner)); @@ -2603,25 +2687,25 @@ public static byte[] deployContract(String contractName, String abiString, Strin contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); contractBuilder.setCallTokenValue(tokenValue); contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + CreateSmartContract contractDeployContract = + contractBuilder.setNewContract(builder.build()).build(); - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); + 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()); + 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(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -2655,9 +2739,12 @@ public static byte[] deployContract(String contractName, String abiString, Strin return null; } transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + 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)); @@ -2666,42 +2753,84 @@ public static byte[] deployContract(String contractName, String abiString, Strin if (response.getResult() == false) { return null; } else { - //logger.info("brodacast succesfully"); + // logger.info("brodacast succesfully"); return contractAddress; } } - /** - * constructor. - */ - public static byte[] deployContract(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - String libraryAddress, String priKey, byte[] ownerAddress, + /** 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, + 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, + /** 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, + 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, + /** 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; @@ -2719,7 +2848,7 @@ public static byte[] deployContractForLibrary(String contractName, String abiStr logger.error("abi is null"); return null; } - //byte[] codeBytes = Hex.decode(code); + // byte[] codeBytes = Hex.decode(code); SmartContract.Builder builder = SmartContract.newBuilder(); builder.setName(contractName); builder.setOriginAddress(ByteString.copyFrom(owner)); @@ -2737,7 +2866,7 @@ public static byte[] deployContractForLibrary(String contractName, String abiStr if (compilerVersion.equals("v5") || compilerVersion.equals("V5")) { byteCode = replaceLibraryAddresscompilerVersion(code, libraryAddress, "v5"); } else { - //old version + // old version byteCode = replaceLibraryAddresscompilerVersion(code, libraryAddress, null); } @@ -2750,25 +2879,25 @@ public static byte[] deployContractForLibrary(String contractName, String abiStr contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); contractBuilder.setCallTokenValue(0); contractBuilder.setTokenId(Long.parseLong("0")); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + CreateSmartContract contractDeployContract = + contractBuilder.setNewContract(builder.build()).build(); - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); + 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()); + 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(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -2802,9 +2931,12 @@ public static byte[] deployContractForLibrary(String contractName, String abiStr return null; } transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + 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)); @@ -2813,33 +2945,56 @@ public static byte[] deployContractForLibrary(String contractName, String abiStr if (response.getResult() == false) { return null; } else { - //logger.info("brodacast succesfully"); + // logger.info("brodacast succesfully"); return contractAddress; } - } - /** - * constructor. - */ - - public static String deployContractAndGetTransactionInfoById(String contractName, - String abiString, String code, String data, Long feeLimit, long value, - long consumeUserResourcePercent, String libraryAddress, String priKey, byte[] ownerAddress, + /** 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, + return deployContractAndGetTransactionInfoById( + contractName, + abiString, + code, + data, + feeLimit, + value, + consumeUserResourcePercent, + 1000L, + "0", + 0L, + libraryAddress, + priKey, + ownerAddress, blockingStubFull); } - /** - * constructor. - */ - - public static String deployContractAndGetTransactionInfoById(String contractName, - String abiString, String code, String data, Long feeLimit, long value, - long consumeUserResourcePercent, long originEnergyLimit, String tokenId, long tokenValue, - String libraryAddress, String priKey, byte[] ownerAddress, + /** 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; @@ -2857,7 +3012,7 @@ public static String deployContractAndGetTransactionInfoById(String contractName logger.error("abi is null"); return null; } - //byte[] codeBytes = Hex.decode(code); + // byte[] codeBytes = Hex.decode(code); SmartContract.Builder builder = SmartContract.newBuilder(); builder.setName(contractName); builder.setOriginAddress(ByteString.copyFrom(owner)); @@ -2882,25 +3037,25 @@ public static String deployContractAndGetTransactionInfoById(String contractName contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); contractBuilder.setCallTokenValue(tokenValue); contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + CreateSmartContract contractDeployContract = + contractBuilder.setNewContract(builder.build()).build(); - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); + 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()); + 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(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -2931,9 +3086,12 @@ public static String deployContractAndGetTransactionInfoById(String contractName return null; } transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + 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)); @@ -2941,17 +3099,15 @@ public static String deployContractAndGetTransactionInfoById(String contractName if (response.getResult() == false) { return null; } else { - //logger.info("brodacast succesfully"); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + // logger.info("brodacast succesfully"); + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); } } - /** - * constructor. - */ - + /** constructor. */ public static SmartContract.ABI jsonStr2Abi(String jsonStr) { if (jsonStr == null) { return null; @@ -2964,29 +3120,34 @@ 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; @@ -3035,8 +3196,8 @@ public static SmartContract.ABI jsonStr2Abi(String jsonStr) { } 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(); + SmartContract.ABI.Entry.Param.Builder paramBuilder = + SmartContract.ABI.Entry.Param.newBuilder(); JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); @@ -3058,10 +3219,7 @@ public static SmartContract.ABI jsonStr2Abi(String jsonStr) { return abiBuilder.build(); } - /** - * constructor. - */ - + /** constructor. */ public static SmartContract.ABI jsonStr2Abi2(String jsonStr) { if (jsonStr == null) { return null; @@ -3074,34 +3232,40 @@ 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") + if (!type.equalsIgnoreCase("fallback") + && !type.equalsIgnoreCase("receive") && null == inputs) { logger.error("No inputs!"); return null; @@ -3146,8 +3310,8 @@ public static SmartContract.ABI jsonStr2Abi2(String jsonStr) { } 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(); + SmartContract.ABI.Entry.Param.Builder paramBuilder = + SmartContract.ABI.Entry.Param.newBuilder(); JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); @@ -3168,11 +3332,7 @@ public static SmartContract.ABI jsonStr2Abi2(String jsonStr) { return abiBuilder.build(); } - - /** - * constructor. - */ - + /** constructor. */ public static SmartContract.ABI.Entry.EntryType getEntryType(String type) { switch (type) { case "constructor": @@ -3190,9 +3350,7 @@ public static SmartContract.ABI.Entry.EntryType getEntryType(String type) { } } - /** - * constructor. - */ + /** constructor. */ public static SmartContract.ABI.Entry.EntryType getEntryType2(String type) { switch (type) { case "constructor": @@ -3210,10 +3368,7 @@ public static SmartContract.ABI.Entry.EntryType getEntryType2(String type) { } } - /** - * constructor. - */ - + /** constructor. */ public static SmartContract.ABI.Entry.StateMutabilityType getStateMutability( String stateMutability) { switch (stateMutability) { @@ -3230,10 +3385,7 @@ public static SmartContract.ABI.Entry.StateMutabilityType getStateMutability( } } - /** - * constructor. - */ - + /** constructor. */ public static byte[] generateContractAddress(Transaction trx, byte[] owneraddress) { // get owner address @@ -3241,9 +3393,10 @@ public static byte[] generateContractAddress(Transaction trx, byte[] owneraddres byte[] ownerAddress = owneraddress; // get tx hash - byte[] txRawDataHash = Sha256Hash - .of(CommonParameter.getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()) - .getBytes(); + byte[] txRawDataHash = + Sha256Hash.of( + CommonParameter.getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()) + .getBytes(); // combine byte[] combined = new byte[txRawDataHash.length + ownerAddress.length]; @@ -3251,15 +3404,11 @@ public static byte[] generateContractAddress(Transaction trx, byte[] owneraddres System.arraycopy(ownerAddress, 0, combined, txRawDataHash.length, ownerAddress.length); return sha3omit12(combined); - } - /** - * constructor. - */ - - public static SmartContract getContract(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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(); @@ -3268,18 +3417,15 @@ public static SmartContract getContract(byte[] address, return blockingStubFull.getContract(bytesMessage); } - /** - * constructor. - */ - - public static SmartContractDataWrapper getContractInfo(byte[] address, - WalletBlockingStub blockingStubFull) { + /** 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()); + "contract name is " + + blockingStubFull.getContractInfo(bytesMessage).getSmartContract().getName()); logger.info("contract address is " + WalletClient.encode58Check(address)); return blockingStubFull.getContractInfo(bytesMessage); } @@ -3297,8 +3443,8 @@ 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); + 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; @@ -3318,8 +3464,8 @@ private static byte[] replaceLibraryAddress_1(String code, byte[] libraryAddress return Hex.decode(code); } - private static byte[] replaceLibraryAddresscompilerVersion(String code, String libraryAddressPair, - String compilerVersion) { + private static byte[] replaceLibraryAddresscompilerVersion( + String code, String libraryAddressPair, String compilerVersion) { String[] libraryAddressList = libraryAddressPair.split("[,]"); @@ -3333,18 +3479,19 @@ private static byte[] replaceLibraryAddresscompilerVersion(String code, String l 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); + libraryAddressHex = + (new String(Hex.encode(Commons.decodeFromBase58Check(addr)), StandardCharsets.US_ASCII)) + .substring(2); String beReplaced; if (compilerVersion == null) { - //old version + // 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); + // 0.5.4 version + String libraryNameKeccak256 = + ByteArray.toHexString(sha3(ByteArray.fromString(libraryName))).substring(0, 34); beReplaced = "__\\$" + libraryNameKeccak256 + "\\$__"; } else { throw new RuntimeException("unknown compiler version."); @@ -3357,12 +3504,13 @@ private static byte[] replaceLibraryAddresscompilerVersion(String code, String l return Hex.decode(code); } - /** - * constructor. - */ - - public static boolean updateSetting(byte[] contractAddress, long consumeUserResourcePercent, - String priKey, byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -3380,14 +3528,14 @@ public static boolean updateSetting(byte[] contractAddress, long consumeUserReso builder.setConsumeUserResourcePercent(consumeUserResourcePercent); UpdateSettingContract updateSettingContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateSetting(updateSettingContract); + 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()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); } return false; } @@ -3412,12 +3560,13 @@ public static boolean updateSetting(byte[] contractAddress, long consumeUserReso return response.getResult(); } - /** - * constructor. - */ - - public static boolean updateSettingDelay(byte[] contractAddress, long consumeUserResourcePercent, - long delaySeconds, String priKey, byte[] ownerAddress, + /** 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; @@ -3436,14 +3585,14 @@ public static boolean updateSettingDelay(byte[] contractAddress, long consumeUse builder.setConsumeUserResourcePercent(consumeUserResourcePercent); UpdateSettingContract updateSettingContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateSetting(updateSettingContract); + 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()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); } return false; } @@ -3471,12 +3620,13 @@ public static boolean updateSettingDelay(byte[] contractAddress, long consumeUse return false; } - /** - * constructor. - */ - - public static String updateSettingDelayGetTxid(byte[] contractAddress, - long consumeUserResourcePercent, long delaySeconds, String priKey, byte[] ownerAddress, + /** 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; @@ -3495,25 +3645,27 @@ public static String updateSettingDelayGetTxid(byte[] contractAddress, builder.setConsumeUserResourcePercent(consumeUserResourcePercent); UpdateSettingContract updateSettingContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateSetting(updateSettingContract); + 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()); + 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, + /** 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; @@ -3532,18 +3684,18 @@ public static String updateEnergyLimitDelayGetTxid(byte[] contractAddress, long builder.setOriginEnergyLimit(originEnergyLimit); UpdateEnergyLimitContract updateEnergyLimitContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateEnergyLimit(updateEnergyLimitContract); + 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()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); } return null; } - //transactionExtention = TransactionUtils.setDelaySecondsToExtension( + // transactionExtention = TransactionUtils.setDelaySecondsToExtension( // transactionExtention, delaySeconds); if (transactionExtention == null) { return null; @@ -3563,18 +3715,15 @@ public static String updateEnergyLimitDelayGetTxid(byte[] contractAddress, long "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(), + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); } - - /** - * 61 constructor. - */ - - public static Optional getTransactionInfoById(String txId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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; @@ -3582,11 +3731,9 @@ public static Optional getTransactionInfoById(String txId, return Optional.ofNullable(transactionInfo); } - /** - * 61 constructor. - */ - public static Optional getTransactionInfoByIdFromSolidity(String txId, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + /** 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; @@ -3594,12 +3741,9 @@ public static Optional getTransactionInfoByIdFromSolidity(Strin return Optional.ofNullable(transactionInfo); } - - /** - * constructor. - */ - public static Optional getTransactionInfoByBlockNum(long blockNum, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** constructor. */ + public static Optional getTransactionInfoByBlockNum( + long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { NumberMessage.Builder builder = NumberMessage.newBuilder(); builder.setNum(blockNum); TransactionInfoList transactionInfoList; @@ -3607,9 +3751,7 @@ public static Optional getTransactionInfoByBlockNum(long bl return Optional.ofNullable(transactionInfoList); } - /** - * constructor. - */ + /** constructor. */ public static Optional getTransactionInfoByBlockNumFromSolidity( long blockNum, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { NumberMessage.Builder builder = NumberMessage.newBuilder(); @@ -3619,23 +3761,44 @@ public static Optional getTransactionInfoByBlockNumFromSoli 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, + /** 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); + 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) { + /** 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 { @@ -3669,12 +3832,13 @@ public static String triggerContract(byte[] contractAddress, String method, Stri 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()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); return null; } Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null + 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()); @@ -3686,8 +3850,8 @@ 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(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); @@ -3719,38 +3883,63 @@ public static String triggerContract(byte[] contractAddress, String method, Stri return null; } transaction = signTransaction(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + 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(), + 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, + /** 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); + 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, + /** 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; @@ -3782,12 +3971,13 @@ public static String triggerContractBoth(byte[] contractAddress, String method, 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()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); return null; } Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null + 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()); @@ -3799,8 +3989,8 @@ 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(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -3830,28 +4020,36 @@ public static String triggerContractBoth(byte[] contractAddress, String method, 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); + 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(), + 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, + /** constructor. */ + public static String triggerParamListContract( + byte[] contractAddress, + String method, + List params, + Boolean isHex, + long callValue, + long feeLimit, + String tokenId, + long tokenValue, + byte[] ownerAddress, + String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); @@ -3880,12 +4078,13 @@ public static String triggerParamListContract(byte[] contractAddress, String met 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()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); return null; } Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null + 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()); @@ -3897,8 +4096,8 @@ 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(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -3928,27 +4127,31 @@ public static String triggerParamListContract(byte[] contractAddress, String met return null; } transaction = signTransaction(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + 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(), + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); } - - } - /** - * constructor. - */ - - public static Boolean exchangeCreate(byte[] firstTokenId, long firstTokenBalance, - byte[] secondTokenId, long secondTokenBalance, byte[] ownerAddress, String priKey, + /** 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; @@ -3963,8 +4166,10 @@ public static Boolean exchangeCreate(byte[] firstTokenId, long firstTokenBalance byte[] owner = ownerAddress; ExchangeCreateContract.Builder builder = ExchangeCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)) - .setFirstTokenId(ByteString.copyFrom(firstTokenId)).setFirstTokenBalance(firstTokenBalance) + builder + .setOwnerAddress(ByteString.copyFrom(owner)) + .setFirstTokenId(ByteString.copyFrom(firstTokenId)) + .setFirstTokenBalance(firstTokenBalance) .setSecondTokenId(ByteString.copyFrom(secondTokenId)) .setSecondTokenBalance(secondTokenBalance); ExchangeCreateContract contract = builder.build(); @@ -3986,21 +4191,26 @@ public static Boolean exchangeCreate(byte[] firstTokenId, long firstTokenBalance 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()))); + System.out.println( + "txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response.getResult(); } - /** - * constructor. - */ - - public static Boolean injectExchange(long exchangeId, byte[] tokenId, long quant, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -4014,8 +4224,11 @@ public static Boolean injectExchange(long exchangeId, byte[] tokenId, long quant byte[] owner = ownerAddress; ExchangeInjectContract.Builder builder = ExchangeInjectContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); + 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) { @@ -4035,9 +4248,12 @@ public static Boolean injectExchange(long exchangeId, byte[] tokenId, long quant 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()))); + System.out.println( + "txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response.getResult(); @@ -4049,48 +4265,44 @@ public static Optional getExchangeList( return Optional.ofNullable(exchangeList); } - /** - * constructor. - */ - + /** constructor. */ public static Optional getExchangeList( WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - ExchangeList exchangeList = blockingStubSolidity - .listExchanges(EmptyMessage.newBuilder().build()); + ExchangeList exchangeList = + blockingStubSolidity.listExchanges(EmptyMessage.newBuilder().build()); return Optional.ofNullable(exchangeList); } - - /** - * constructor. - */ - - public static Optional getExchange(String id, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - BytesMessage request = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))).build(); + /** constructor. */ + public static Optional getExchange( + String id, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + BytesMessage request = + BytesMessage.newBuilder() + .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))) + .build(); Exchange exchange = blockingStubSolidity.getExchangeById(request); return Optional.ofNullable(exchange); } - /** - * constructor. - */ - - public static Optional getExchange(String id, - WalletGrpc.WalletBlockingStub blockingStubFull) { - BytesMessage request = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))).build(); + /** constructor. */ + public static Optional getExchange( + String id, WalletGrpc.WalletBlockingStub blockingStubFull) { + BytesMessage request = + BytesMessage.newBuilder() + .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))) + .build(); Exchange exchange = blockingStubFull.getExchangeById(request); return Optional.ofNullable(exchange); } - /** - * constructor. - */ - - public static boolean exchangeWithdraw(long exchangeId, byte[] tokenId, long quant, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -4103,8 +4315,11 @@ public static boolean exchangeWithdraw(long exchangeId, byte[] tokenId, long qua byte[] owner = ownerAddress; ExchangeWithdrawContract.Builder builder = ExchangeWithdrawContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); + 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) { @@ -4124,20 +4339,25 @@ public static boolean exchangeWithdraw(long exchangeId, byte[] tokenId, long qua 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()))); + 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, + /** 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; @@ -4151,8 +4371,12 @@ public static boolean exchangeTransaction(long exchangeId, byte[] tokenId, long byte[] owner = ownerAddress; ExchangeTransactionContract.Builder builder = ExchangeTransactionContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant).setExpected(expected); + 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) { @@ -4172,35 +4396,68 @@ public static boolean exchangeTransaction(long exchangeId, byte[] tokenId, long 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()))); + System.out.println( + "txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response.getResult(); } - /** - * constructor. - */ - - public static String deployContractWithConstantParame(String contractName, String abiString, - String code, String constructorStr, String argsStr, String data, Long feeLimit, long value, - long consumeUserResourcePercent, String libraryAddress, String priKey, byte[] ownerAddress, + /** 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); + return deployContractWithConstantParame( + contractName, + abiString, + code, + constructorStr, + argsStr, + data, + feeLimit, + value, + consumeUserResourcePercent, + 1000L, + "0", + 0L, + libraryAddress, + priKey, + ownerAddress, + blockingStubFull); } - /** - * constructor. - */ - - public static String deployContractWithConstantParame(String contractName, String abiString, - String code, String constructorStr, String argsStr, String data, Long feeLimit, long value, - long consumeUserResourcePercent, long originEnergyLimit, String tokenId, long tokenValue, - String libraryAddress, String priKey, byte[] ownerAddress, + /** 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; @@ -4244,25 +4501,25 @@ public static String deployContractWithConstantParame(String contractName, Strin contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); contractBuilder.setCallTokenValue(tokenValue); contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + CreateSmartContract contractDeployContract = + contractBuilder.setNewContract(builder.build()).build(); - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); + 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()); + 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(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -4293,9 +4550,12 @@ public static String deployContractWithConstantParame(String contractName, Strin return null; } transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + 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)); @@ -4303,19 +4563,22 @@ public static String deployContractWithConstantParame(String contractName, Strin if (response.getResult() == false) { return null; } else { - //logger.info("brodacast succesfully"); - return ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), + // logger.info("brodacast succesfully"); + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); } } - /** - * constructor. - */ - - public static Boolean freezeBalanceForReceiver(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, ByteString receiverAddressBytes, String priKey, + /** 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; @@ -4333,8 +4596,11 @@ public static Boolean freezeBalanceForReceiver(byte[] addRess, long freezeBalanc FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); + builder + .setOwnerAddress(byteAddreess) + .setFrozenBalance(frozenBalance) + .setFrozenDuration(frozenDuration) + .setResourceValue(resourceCode); if (receiverAddressBytes != null) { builder.setReceiverAddress(receiverAddressBytes); } @@ -4351,43 +4617,41 @@ public static Boolean freezeBalanceForReceiver(byte[] addRess, long freezeBalanc return response.getResult(); } - - /** - * constructor. - */ - - public static Optional getDelegatedResource(byte[] fromAddress, - byte[] toAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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(); + 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) { + /** 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(); + DelegatedResourceMessage request = + DelegatedResourceMessage.newBuilder() + .setFromAddress(fromAddressBs) + .setToAddress(toAddressBs) + .build(); DelegatedResourceList delegatedResource = blockingStubFull.getDelegatedResource(request); return Optional.ofNullable(delegatedResource); } - - /** - * constructor. - */ - + /** constructor. */ public static Optional getDelegatedResourceAccountIndex( byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); @@ -4396,60 +4660,47 @@ public static Optional getDelegatedResourceAccoun BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(addressBs).build(); - DelegatedResourceAccountIndex accountIndex = blockingStubFull - .getDelegatedResourceAccountIndex(bytesMessage); + DelegatedResourceAccountIndex accountIndex = + blockingStubFull.getDelegatedResourceAccountIndex(bytesMessage); return Optional.ofNullable(accountIndex); } - - /** - * constructor. - */ + /** 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); BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(addressBs).build(); - DelegatedResourceAccountIndex accountIndex = blockingStubFull - .getDelegatedResourceAccountIndex(bytesMessage); + DelegatedResourceAccountIndex accountIndex = + blockingStubFull.getDelegatedResourceAccountIndex(bytesMessage); return Optional.ofNullable(accountIndex); } - - /** - * constructor. - */ - - public static AssetIssueContract getAssetIssueByName(String assetName, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** constructor. */ + public static AssetIssueContract getAssetIssueByName( + String assetName, WalletGrpc.WalletBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); return blockingStubFull.getAssetIssueByName(request); } - /** - * constructor. - */ - public static AssetIssueContract getAssetIssueByNameFromSolidity(String assetName, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + /** constructor. */ + public static AssetIssueContract getAssetIssueByNameFromSolidity( + String assetName, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); return blockingStubFull.getAssetIssueByName(request); } - - /** - * constructor. - */ - - public static Optional getAssetIssueListByName(String assetName, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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(); @@ -4457,11 +4708,9 @@ public static Optional getAssetIssueListByName(String assetName, return Optional.ofNullable(assetIssueList); } - /** - * constructor. - */ - public static Optional getAssetIssueListByNameFromSolidity(String assetName, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { + /** 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(); @@ -4469,79 +4718,62 @@ public static Optional getAssetIssueListByNameFromSolidity(Strin return Optional.ofNullable(assetIssueList); } - /** - * constructor. - */ + /** constructor. */ public static Optional listAssetIssueFromSolidity( WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - GrpcAPI.AssetIssueList assetIssueList = blockingStubFull - .getAssetIssueList(EmptyMessage.newBuilder().build()); + GrpcAPI.AssetIssueList assetIssueList = + blockingStubFull.getAssetIssueList(EmptyMessage.newBuilder().build()); return Optional.ofNullable(assetIssueList); } - /** - * constructor. - */ + /** 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()); + AssetIssueList assetIssueList = + blockingStubFull.getPaginatedAssetIssueList(pageMessageBuilder.build()); return Optional.ofNullable(assetIssueList); } - - /** - * constructor. - */ + /** constructor. */ public static Optional listWitnesses( WalletGrpc.WalletBlockingStub blockingStubFull) { - GrpcAPI.WitnessList witnessList = blockingStubFull - .listWitnesses(EmptyMessage.newBuilder().build()); + GrpcAPI.WitnessList witnessList = + blockingStubFull.listWitnesses(EmptyMessage.newBuilder().build()); return Optional.ofNullable(witnessList); } - /** - * constructor. - */ + /** constructor. */ public static Optional listWitnessesFromSolidity( WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - GrpcAPI.WitnessList witnessList = blockingStubFull - .listWitnesses(EmptyMessage.newBuilder().build()); + GrpcAPI.WitnessList witnessList = + blockingStubFull.listWitnesses(EmptyMessage.newBuilder().build()); return Optional.ofNullable(witnessList); } - - /** - * constructor. - */ - - public static AssetIssueContract getAssetIssueById(String assetId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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) { + /** 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) { + /** 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(); @@ -4560,7 +4792,7 @@ private static Permission json2Permission(JSONObject json) { permissionBuilder.setPermissionName(permissionName); } if (json.containsKey("threshold")) { - //long threshold = json.getLong("threshold"); + // long threshold = json.getLong("threshold"); long threshold = Long.parseLong(json.getString("threshold")); permissionBuilder.setThreshold(threshold); } @@ -4580,8 +4812,8 @@ private static Permission json2Permission(JSONObject json) { 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())); + // 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()); @@ -4591,11 +4823,13 @@ private static Permission json2Permission(JSONObject json) { return permissionBuilder.build(); } - /** - * constructor. - */ - public static boolean accountPermissionUpdate(String permissionJson, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] priKeys) { + /** 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 { @@ -4655,13 +4889,13 @@ public static boolean accountPermissionUpdate(String permissionJson, byte[] owne return response.getResult(); } - - /** - * constructor. - */ - public static long getFreezeBalanceCount(byte[] accountAddress, String ecKey, Long targetEnergy, + /** constructor. */ + public static long getFreezeBalanceCount( + byte[] accountAddress, + String ecKey, + Long targetEnergy, WalletGrpc.WalletBlockingStub blockingStubFull) { - //Precision change as the entire network freezes + // Precision change as the entire network freezes AccountResourceMessage resourceInfo = getAccountResource(accountAddress, blockingStubFull); Account info = queryAccount(accountAddress, blockingStubFull); @@ -4685,9 +4919,12 @@ 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(); + long needBalance = + totalEnergyWeightBi + .multiply(BigInteger.valueOf(1_000_000)) + .multiply(BigInteger.valueOf(targetEnergy)) + .divide(BigInteger.valueOf(totalEnergyLimit - targetEnergy)) + .longValue(); logger.info("getFreezeBalanceCount, needBalance: " + needBalance); @@ -4698,10 +4935,10 @@ public static long getFreezeBalanceCount(byte[] accountAddress, String ecKey, Lo return needBalance; } - /** - * constructor. - */ - public static Long getAssetIssueValue(byte[] accountAddress, ByteString assetIssueId, + /** constructor. */ + public static Long getAssetIssueValue( + byte[] accountAddress, + ByteString assetIssueId, WalletGrpc.WalletBlockingStub blockingStubFull) { Long assetIssueCount = 0L; Account contractAccount = queryAccount(accountAddress, blockingStubFull); @@ -4714,9 +4951,7 @@ public static Long getAssetIssueValue(byte[] accountAddress, ByteString assetIss return assetIssueCount; } - /** - * constructor. - */ + /** constructor. */ public static List getStrings(byte[] data) { int index = 0; List ret = new ArrayList<>(); @@ -4727,9 +4962,7 @@ public static List getStrings(byte[] data) { return ret; } - /** - * constructor. - */ + /** 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++) { @@ -4739,12 +4972,9 @@ public static String byte2HexStr(byte[] b, int offset, int length) { return ssBuilder.toString().toUpperCase().trim(); } - - /** - * constructor. - */ - public static Transaction addTransactionSign(Transaction transaction, String priKey, - WalletGrpc.WalletBlockingStub 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 { @@ -4756,8 +4986,10 @@ public static Transaction addTransactionSign(Transaction transaction, String pri ECKey ecKey = temKey; Transaction.Builder transactionBuilderSigned = transaction.toBuilder(); - byte[] hash = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()); + byte[] hash = + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()); ECDSASignature signature = ecKey.sign(hash); ByteString bsSign = ByteString.copyFrom(signature.toByteArray()); @@ -4766,13 +4998,22 @@ public static Transaction addTransactionSign(Transaction transaction, String pri 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) { + /** 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 { @@ -4789,7 +5030,7 @@ public static GrpcAPI.Return deployContractAndGetResponse(String contractName, S logger.error("abi is null"); return null; } - //byte[] codeBytes = Hex.decode(code); + // byte[] codeBytes = Hex.decode(code); SmartContract.Builder builder = SmartContract.newBuilder(); builder.setName(contractName); builder.setOriginAddress(ByteString.copyFrom(owner)); @@ -4814,25 +5055,25 @@ public static GrpcAPI.Return deployContractAndGetResponse(String contractName, S contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); contractBuilder.setCallTokenValue(tokenValue); contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); + CreateSmartContract contractDeployContract = + contractBuilder.setNewContract(builder.build()).build(); - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); + 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()); + 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(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -4863,9 +5104,12 @@ public static GrpcAPI.Return deployContractAndGetResponse(String contractName, S return null; } transaction = signTransaction(ecKey, transaction); - System.out.println("txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + 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)); @@ -4874,12 +5118,19 @@ public static GrpcAPI.Return deployContractAndGetResponse(String contractName, S return response; } - /** - * constructor. - */ - public static GrpcAPI.Return triggerContractAndGetResponse(byte[] contractAddress, String method, - String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -4910,12 +5161,13 @@ public static GrpcAPI.Return triggerContractAndGetResponse(byte[] contractAddres 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()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); return null; } Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null + 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()); @@ -4927,8 +5179,8 @@ 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(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -4958,18 +5210,23 @@ public static GrpcAPI.Return triggerContractAndGetResponse(byte[] contractAddres return null; } transaction = signTransaction(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + System.out.println( + "trigger txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); return response; } - /** - * constructor. - */ - public static boolean updateEnergyLimit(byte[] contractAddress, long originEnergyLimit, - String priKey, byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -4987,14 +5244,14 @@ public static boolean updateEnergyLimit(byte[] contractAddress, long originEnerg builder.setOriginEnergyLimit(originEnergyLimit); UpdateEnergyLimitContract updateEnergyLimitContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateEnergyLimit(updateEnergyLimitContract); + 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()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); } return false; } @@ -5019,11 +5276,12 @@ public static boolean updateEnergyLimit(byte[] contractAddress, long originEnerg return response.getResult(); } - /** - * constructor. - */ - public static GrpcAPI.Return accountPermissionUpdateForResponse(String permissionJson, - byte[] owner, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -5084,17 +5342,18 @@ public static GrpcAPI.Return accountPermissionUpdateForResponse(String permissio return response; } - public static TransactionApprovedList getTransactionApprovedList(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull) { + public static TransactionApprovedList getTransactionApprovedList( + Transaction transaction, WalletGrpc.WalletBlockingStub blockingStubFull) { return blockingStubFull.getTransactionApprovedList(transaction); } - /** - * constructor. - */ - public static long getFreezeBalanceNetCount(byte[] accountAddress, String ecKey, Long targetNet, + /** constructor. */ + public static long getFreezeBalanceNetCount( + byte[] accountAddress, + String ecKey, + Long targetNet, WalletGrpc.WalletBlockingStub blockingStubFull) { - //Precision change as the entire network freezes + // Precision change as the entire network freezes AccountResourceMessage resourceInfo = getAccountResource(accountAddress, blockingStubFull); Account info = queryAccount(accountAddress, blockingStubFull); @@ -5117,29 +5376,29 @@ 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(); + long needBalance = + totalNetWeightBi + .multiply(BigInteger.valueOf(1_000_000)) + .multiply(BigInteger.valueOf(targetNet)) + .divide(BigInteger.valueOf(totalNetLimit - targetNet)) + .longValue(); logger.info("getFreezeBalanceNetCount, needBalance: " + needBalance); if (needBalance < 1000000L) { needBalance = 1000000L; - logger - .info("getFreezeBalanceNetCount, needBalance less than 1 TRX, modify to: " + needBalance); + logger.info( + "getFreezeBalanceNetCount, needBalance less than 1 TRX, modify to: " + needBalance); } return needBalance; } - /** - * constructor. - */ - public static GrpcAPI.Return broadcastTransaction(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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) { + while (!response.getResult() && response.getCode() == response_code.SERVER_BUSY && i > 0) { try { Thread.sleep(300); } catch (InterruptedException e) { @@ -5157,17 +5416,17 @@ public static GrpcAPI.Return broadcastTransaction(Transaction transaction, return response; } - /** - * constructor. - */ - public static GrpcAPI.Return broadcastTransactionBoth(Transaction transaction, + /** 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 + while (response.getResult() == false + && response.getCode() == response_code.SERVER_BUSY && i > 0) { try { Thread.sleep(300); @@ -5186,9 +5445,7 @@ public static GrpcAPI.Return broadcastTransactionBoth(Transaction transaction, return response; } - /** - * constructor. - */ + /** constructor. */ public static String exec(String command) throws InterruptedException { String returnString = ""; Process pro = null; @@ -5213,12 +5470,68 @@ public static String exec(String command) throws InterruptedException { return returnString; } - /** - * constructor. - */ + /** 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"); + 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; @@ -5238,9 +5551,15 @@ 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; @@ -5266,9 +5585,7 @@ public static HashMap getBycodeAbi(String solFile, String contra return retMap; } - /** - * constructor. - */ + /** constructor. */ public static String fileRead(String filePath, boolean isLibrary) throws Exception { File file = new File(filePath); FileReader reader = new FileReader(file); @@ -5295,11 +5612,9 @@ public static String fileRead(String filePath, boolean isLibrary) throws Excepti return sb.toString(); } - /** - * constructor. - */ - public static HashMap getBycodeAbiForLibrary(String solFile, - String contractName) { + /** 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; @@ -5315,12 +5630,19 @@ public static HashMap getBycodeAbiForLibrary(String solFile, 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) { + /** 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 { @@ -5347,17 +5669,18 @@ public static String triggerConstantContract(byte[] contractAddress, String meth builder.setCallTokenValue(tokenValue); TriggerSmartContract triggerContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .triggerConstantContract(triggerContract); + 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()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); return null; } Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null + 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()); @@ -5369,8 +5692,8 @@ 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(); + Transaction.raw.Builder rawBuilder = + transactionExtention.getTransaction().getRawData().toBuilder(); rawBuilder.setFeeLimit(feeLimit); transBuilder.setRawData(rawBuilder); for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { @@ -5400,25 +5723,35 @@ public static String triggerConstantContract(byte[] contractAddress, String meth return null; } transaction = signTransaction(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + 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(), + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); } } - /** - * constructor. - */ + /** 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, + 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; @@ -5446,16 +5779,16 @@ public static TransactionExtention triggerConstantContractForExtentionOnSolidity builder.setCallTokenValue(tokenValue); TriggerSmartContract triggerContract = builder.build(); - TransactionExtention transactionExtention = blockingStubSolidity - .triggerConstantContract(triggerContract); + TransactionExtention transactionExtention = + blockingStubSolidity.triggerConstantContract(triggerContract); return transactionExtention; - } - /** - * constructor. - */ - public static String clearContractAbi(byte[] contractAddress, byte[] ownerAddress, String priKey, + /** 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; @@ -5479,12 +5812,13 @@ public static String clearContractAbi(byte[] contractAddress, byte[] ownerAddres 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()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); return null; } Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null + 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()); @@ -5496,8 +5830,8 @@ 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(); + 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); @@ -5526,24 +5860,29 @@ public static String clearContractAbi(byte[] contractAddress, byte[] ownerAddres return null; } transaction = signTransaction(ecKey, transaction); - System.out.println("trigger txid = " + ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); + 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(), + 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) { + /** 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 { @@ -5564,15 +5903,20 @@ public static TransactionExtention clearContractAbiForExtention(byte[] contractA TransactionExtention transactionExtention = blockingStubFull.clearContractABI(clearAbiContract); return transactionExtention; - } - /** - * constructor. - */ - public static TransactionExtention triggerConstantContractForExtention(byte[] contractAddress, - String method, String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, - long tokenValue, byte[] ownerAddress, String priKey, + /** 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; @@ -5590,7 +5934,6 @@ public static TransactionExtention triggerConstantContractForExtention(byte[] co if (tokenId.equalsIgnoreCase("") || tokenId.equalsIgnoreCase("#")) { logger.info("tokenid is 0"); tokenId = "0"; - } byte[] owner = ownerAddress; @@ -5603,21 +5946,24 @@ public static TransactionExtention triggerConstantContractForExtention(byte[] co builder.setTokenId(Long.parseLong(tokenId)); builder.setCallTokenValue(tokenValue); TriggerSmartContract triggerContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .triggerConstantContract(triggerContract); + 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, + /** 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 priKey, + WalletSolidityGrpc.WalletSolidityBlockingStub solidityBlockingStubFull) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); ECKey temKey = null; try { @@ -5644,19 +5990,23 @@ public static TransactionExtention triggerSolidityContractForExtention(byte[] co builder.setCallTokenValue(tokenValue); TriggerSmartContract triggerContract = builder.build(); - TransactionExtention transactionExtention = solidityBlockingStubFull - .triggerConstantContract(triggerContract); + 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, + /** 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; @@ -5686,12 +6036,9 @@ public static TransactionExtention triggerContractForExtention(byte[] contractAd TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); return transactionExtention; - } - /** - * constructor. - */ + /** constructor. */ public static String create2(String[] parameters) { if (parameters == null || parameters.length != 3) { logger.error("create2 needs 3 parameter:\ncreate2 address code salt"); @@ -5721,13 +6068,16 @@ public static String create2(String[] parameters) { return create2Address; } - - /** - * constructor. - */ - public static boolean sendShieldCoin(byte[] publicZenTokenOwnerAddress, long fromAmount, - ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, - byte[] publicZenTokenToAddress, long toAmount, String priKey, + /** 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; @@ -5752,16 +6102,16 @@ public static boolean sendShieldCoin(byte[] publicZenTokenOwnerAddress, long fro if (shieldAddressInfo != null) { OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); + // 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)); + // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - //String shieldAddress = noteInfo.getPaymentAddress(); - //ShieldAddressInfo addressInfo = + // String shieldAddress = noteInfo.getPaymentAddress(); + // ShieldAddressInfo addressInfo = // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); try { @@ -5779,12 +6129,12 @@ public static boolean sendShieldCoin(byte[] publicZenTokenOwnerAddress, long fro 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())); + // 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()); @@ -5794,28 +6144,29 @@ public static boolean sendShieldCoin(byte[] publicZenTokenOwnerAddress, long fro System.out.println(e); } - IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); + 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"); + 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()); + builder.addShieldedReceives( + ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); } } - TransactionExtention transactionExtention = blockingStubFull - .createShieldedTransaction(builder.build()); + TransactionExtention transactionExtention = + blockingStubFull.createShieldedTransaction(builder.build()); if (transactionExtention == null) { return false; } @@ -5835,17 +6186,23 @@ public static boolean sendShieldCoin(byte[] publicZenTokenOwnerAddress, long fro Any any = transaction.getRawData().getContract(0).getParameter(); try { - ShieldedTransferContract shieldedTransferContract = any - .unpack(ShieldedTransferContract.class); + 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()))); + 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()))); + System.out.println( + "trigger txid = " + + ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()))); } } catch (Exception e) { System.out.println(e); @@ -5853,12 +6210,16 @@ public static boolean sendShieldCoin(byte[] publicZenTokenOwnerAddress, long fro 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, + /** 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; @@ -5884,22 +6245,22 @@ public static boolean sendShieldCoinWithoutAsk(byte[] publicZenTokenOwnerAddress if (shieldAddressInfo != null) { OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); + // 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()); + 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)); + // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - //String shieldAddress = noteInfo.getPaymentAddress(); - //ShieldAddressInfo addressInfo = + // String shieldAddress = noteInfo.getPaymentAddress(); + // ShieldAddressInfo addressInfo = // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); String shieldAddress = noteTx.getNote().getPaymentAddress(); SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); @@ -5920,12 +6281,12 @@ public static boolean sendShieldCoinWithoutAsk(byte[] publicZenTokenOwnerAddress 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())); + // 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()); @@ -5941,26 +6302,27 @@ public static boolean sendShieldCoinWithoutAsk(byte[] publicZenTokenOwnerAddress builder.addShieldedSpends(spendNoteBuilder.build()); } else { - byte[] ovk = ByteArray - .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); + 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()); + builder.addShieldedReceives( + ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); } } - TransactionExtention transactionExtention = blockingStubFull - .createShieldedTransactionWithoutSpendAuthSig(builder.build()); + TransactionExtention transactionExtention = + blockingStubFull.createShieldedTransactionWithoutSpendAuthSig(builder.build()); if (transactionExtention == null) { System.out.println("sendShieldCoinWithoutAsk failure."); return false; } - BytesMessage trxHash = blockingStubFull - .getShieldTransactionHash(transactionExtention.getTransaction()); + BytesMessage trxHash = + blockingStubFull.getShieldTransactionHash(transactionExtention.getTransaction()); if (trxHash == null || trxHash.getValue().toByteArray().length != 32) { System.out.println("sendShieldCoinWithoutAsk get transaction hash failure."); return false; @@ -5976,8 +6338,8 @@ public static boolean sendShieldCoinWithoutAsk(byte[] publicZenTokenOwnerAddress try { ShieldedTransferContract shieldContract = any.unpack(ShieldedTransferContract.class); List spendDescList = shieldContract.getSpendDescriptionList(); - ShieldedTransferContract.Builder contractBuild = shieldContract.toBuilder() - .clearSpendDescription(); + ShieldedTransferContract.Builder contractBuild = + shieldContract.toBuilder().clearSpendDescription(); for (int i = 0; i < spendDescList.size(); i++) { SpendAuthSigParameters.Builder builder1 = SpendAuthSigParameters.newBuilder(); @@ -5986,16 +6348,21 @@ public static boolean sendShieldCoinWithoutAsk(byte[] publicZenTokenOwnerAddress 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())); + 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.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(); @@ -6023,30 +6390,33 @@ public static boolean sendShieldCoinWithoutAsk(byte[] publicZenTokenOwnerAddress transaction1 = signTransaction(ecKey, transaction1); } else { Any any1 = transaction1.getRawData().getContract(0).getParameter(); - ShieldedTransferContract shieldedTransferContract = any1 - .unpack(ShieldedTransferContract.class); + 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()))); + 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()))); + 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) { + /** constructor. */ + public static List addShieldOutputList( + List shieldOutList, String shieldToAddress, String toAmountString, String menoString) { String shieldAddress = shieldToAddress; String amountString = toAmountString; if (menoString.equals("null")) { @@ -6068,13 +6438,11 @@ public static List addShieldOutputList(List shieldOutList, String sh } noteBuild.setMemo(ByteString.copyFrom(menoString.getBytes())); shieldOutList.add(noteBuild.build()); - //logger.info(shieldOutList.toString()); + // logger.info(shieldOutList.toString()); return shieldOutList; } - /** - * constructor. - */ + /** constructor. */ public static Optional generateShieldAddress() { ShieldAddressInfo addressInfo = new ShieldAddressInfo(); try { @@ -6100,11 +6468,9 @@ public static Optional generateShieldAddress() { return Optional.empty(); } - - /** - * constructor. - */ - public static DecryptNotes listShieldNote(Optional shieldAddressInfo, + /** constructor. */ + public static DecryptNotes listShieldNote( + Optional shieldAddressInfo, WalletGrpc.WalletBlockingStub blockingStubFull) { Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); @@ -6122,10 +6488,9 @@ public static DecryptNotes listShieldNote(Optional shieldAddr return notes; } - /** - * constructor. - */ - public static DecryptNotes getShieldNotesByIvk(Optional shieldAddressInfo, + /** constructor. */ + public static DecryptNotes getShieldNotesByIvk( + Optional shieldAddressInfo, WalletGrpc.WalletBlockingStub blockingStubFull) { Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); @@ -6133,7 +6498,7 @@ public static DecryptNotes getShieldNotesByIvk(Optional shiel if (currentBlockNum > 100) { startBlockNum = currentBlockNum - 100; } - //startBlockNum = 0L; + // startBlockNum = 0L; logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); builder.setStartBlockIndex(startBlockNum + 1); @@ -6144,9 +6509,7 @@ public static DecryptNotes getShieldNotesByIvk(Optional shiel return notes; } - /** - * constructor. - */ + /** constructor. */ public static DecryptNotesMarked getShieldNotesAndMarkByIvk( Optional shieldAddressInfo, WalletGrpc.WalletBlockingStub blockingStubFull) { @@ -6156,7 +6519,7 @@ public static DecryptNotesMarked getShieldNotesAndMarkByIvk( if (currentBlockNum > 100) { startBlockNum = currentBlockNum - 100; } - //startBlockNum = 0L; + // startBlockNum = 0L; logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); try { IvkDecryptAndMarkParameters.Builder builder = IvkDecryptAndMarkParameters.newBuilder(); @@ -6174,20 +6537,18 @@ public static DecryptNotesMarked getShieldNotesAndMarkByIvk( } } - /** - * constructor. - */ + /** constructor. */ public static DecryptNotesMarked getShieldNotesAndMarkByIvkOnSolidity( Optional shieldAddressInfo, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Block currentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + 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; + // startBlockNum = 0L; logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); try { IvkDecryptAndMarkParameters.Builder builder = IvkDecryptAndMarkParameters.newBuilder(); @@ -6205,10 +6566,9 @@ public static DecryptNotesMarked getShieldNotesAndMarkByIvkOnSolidity( } } - /** - * constructor. - */ - public static Integer getShieldNotesCount(Optional shieldAddressInfo, + /** constructor. */ + public static Integer getShieldNotesCount( + Optional shieldAddressInfo, WalletGrpc.WalletBlockingStub blockingStubFull) { Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); @@ -6240,17 +6600,14 @@ public static Integer getShieldNotesCount(Optional shieldAddr DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); count = count + notes.getNoteTxsCount(); return count; - } - /** - * constructor. - */ + /** constructor. */ public static DecryptNotes getShieldNotesByIvkOnSolidity( Optional shieldAddressInfo, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Block currentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Block currentBlock = + blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); Long startBlockNum = 0L; if (currentBlockNum > 100) { @@ -6265,11 +6622,9 @@ public static DecryptNotes getShieldNotesByIvkOnSolidity( return notes; } - - /** - * constructor. - */ - public static DecryptNotes getShieldNotesByOvk(Optional shieldAddressInfo, + /** constructor. */ + public static DecryptNotes getShieldNotesByOvk( + Optional shieldAddressInfo, WalletGrpc.WalletBlockingStub blockingStubFull) { Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); @@ -6287,14 +6642,12 @@ public static DecryptNotes getShieldNotesByOvk(Optional shiel return notes; } - /** - * constructor. - */ + /** constructor. */ public static DecryptNotes getShieldNotesByOvkOnSolidity( Optional shieldAddressInfo, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Block currentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); + Block currentBlock = + blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); Long startBlockNum = 0L; if (currentBlockNum > 100) { @@ -6309,18 +6662,15 @@ public static DecryptNotes getShieldNotesByOvkOnSolidity( return notes; } - - /** - * constructor. - */ + /** constructor. */ public static String getMemo(Note note) { return ZenUtils.getMemo(note.getMemo().toByteArray()); } - /** - * constructor. - */ - public static SpendResult getSpendResult(ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, + /** constructor. */ + public static SpendResult getSpendResult( + ShieldAddressInfo shieldAddressInfo, + NoteTx noteTx, WalletGrpc.WalletBlockingStub blockingStubFull) { OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); @@ -6328,8 +6678,8 @@ public static SpendResult getSpendResult(ShieldAddressInfo shieldAddressInfo, No outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); outPointBuild.setIndex(noteTx.getIndex()); request.addOutPoints(outPointBuild.build()); - Optional merkleVoucherInfo = Optional - .of(blockingStubFull.getMerkleTreeVoucherInfo(request.build())); + Optional merkleVoucherInfo = + Optional.of(blockingStubFull.getMerkleTreeVoucherInfo(request.build())); if (merkleVoucherInfo.isPresent() && merkleVoucherInfo.get().getVouchersCount() > 0) { NoteParameters.Builder builder = NoteParameters.newBuilder(); @@ -6350,28 +6700,26 @@ public static SpendResult getSpendResult(ShieldAddressInfo shieldAddressInfo, No builder.setNote(noteBuild.build()); builder.setTxid(ByteString.copyFrom(noteTx.getTxid().toByteArray())); builder.setIndex(noteTx.getIndex()); - //builder.setVoucher(merkleVoucherInfo.getVouchers(0)); + // builder.setVoucher(merkleVoucherInfo.getVouchers(0)); SpendResult result = blockingStubFull.isSpend(builder.build()); return result; - } return null; - } - /** - * constructor. - */ - public static SpendResult getSpendResultOnSolidity(ShieldAddressInfo shieldAddressInfo, - NoteTx noteTx, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + /** 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())); + Optional merkleVoucherInfo = + Optional.of(blockingStubSolidity.getMerkleTreeVoucherInfo(request.build())); if (merkleVoucherInfo.isPresent() && merkleVoucherInfo.get().getVouchersCount() > 0) { NoteParameters.Builder builder = NoteParameters.newBuilder(); @@ -6389,7 +6737,7 @@ public static SpendResult getSpendResultOnSolidity(ShieldAddressInfo shieldAddre builder.setNote(noteBuild.build()); builder.setTxid(ByteString.copyFrom(noteTx.getTxid().toByteArray())); builder.setIndex(noteTx.getIndex()); - //builder.setVoucher(merkleVoucherInfo.getVouchers(0)); + // builder.setVoucher(merkleVoucherInfo.getVouchers(0)); SpendResult result = blockingStubSolidity.isSpend(builder.build()); return result; @@ -6397,18 +6745,18 @@ public static SpendResult getSpendResultOnSolidity(ShieldAddressInfo shieldAddre return null; } - /** - * constructor. - */ - public static String getShieldNullifier(ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, + /** 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()); + IncrementalMerkleVoucherInfo merkleVoucherInfo = + blockingStubFull.getMerkleTreeVoucherInfo(request.build()); if (merkleVoucherInfo.getVouchersCount() < 1) { System.out.println("get merkleVoucherInfo failure."); return null; @@ -6422,7 +6770,7 @@ public static String getShieldNullifier(ShieldAddressInfo shieldAddressInfo, Not String shieldAddress = noteTx.getNote().getPaymentAddress(); SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); try { - //TODO + // TODO FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); NfParameters.Builder builder = NfParameters.newBuilder(); builder.setNote(noteBuild.build()); @@ -6437,16 +6785,18 @@ public static String getShieldNullifier(ShieldAddressInfo shieldAddressInfo, Not e.printStackTrace(); } return null; - } - - /** - * constructor. - */ - public static String sendShieldCoinGetTxid(byte[] publicZenTokenOwnerAddress, long fromAmount, - ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, - byte[] publicZenTokenToAddress, long toAmount, String priKey, + /** 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; @@ -6471,16 +6821,16 @@ public static String sendShieldCoinGetTxid(byte[] publicZenTokenOwnerAddress, lo if (shieldAddressInfo != null) { OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); + // 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)); + // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - //String shieldAddress = noteInfo.getPaymentAddress(); - //ShieldAddressInfo addressInfo = + // String shieldAddress = noteInfo.getPaymentAddress(); + // ShieldAddressInfo addressInfo = // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); try { @@ -6498,12 +6848,12 @@ public static String sendShieldCoinGetTxid(byte[] publicZenTokenOwnerAddress, lo 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())); + // 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()); @@ -6513,28 +6863,29 @@ public static String sendShieldCoinGetTxid(byte[] publicZenTokenOwnerAddress, lo System.out.println(e); } - IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); + 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"); + 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()); + builder.addShieldedReceives( + ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); } } - TransactionExtention transactionExtention = blockingStubFull - .createShieldedTransaction(builder.build()); + TransactionExtention transactionExtention = + blockingStubFull.createShieldedTransaction(builder.build()); if (transactionExtention == null) { return null; } @@ -6554,30 +6905,35 @@ public static String sendShieldCoinGetTxid(byte[] publicZenTokenOwnerAddress, lo Any any = transaction.getRawData().getContract(0).getParameter(); try { - ShieldedTransferContract shieldedTransferContract = any - .unpack(ShieldedTransferContract.class); + 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()))); + 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()))); + 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(), + return ByteArray.toHexString( + Sha256Hash.hash( + CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); } - /** - * constructor. - */ + /** constructor. */ public static byte[] decode58Check(String input) { byte[] decodeCheck = org.tron.common.utils.Base58.decode(input); if (decodeCheck.length <= 4) { @@ -6587,26 +6943,26 @@ public static byte[] decode58Check(String input) { 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]) { + 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, + /** 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. - */ + /** constructor. */ public static String parametersString(List parameters) { String[] inputArr = new String[parameters.size()]; int i = 0; @@ -6629,9 +6985,7 @@ public static String parametersString(List parameters) { return input; } - /** - * constructor. - */ + /** constructor. */ public static String bytes32ToString(byte[] bytes) { if (bytes == null) { return "null"; @@ -6650,12 +7004,14 @@ public static String bytes32ToString(byte[] bytes) { } } - /** - * constructor. - */ - - public static Return transferAssetForReturn(byte[] to, byte[] assertName, long amount, - byte[] address, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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 { @@ -6683,18 +7039,17 @@ public static Return transferAssetForReturn(byte[] to, byte[] assertName, long a } Return ret = transaction.getResult(); return ret; - } - - /** - * constructor. - */ - - public static Return sendcoinForReturn(byte[] to, long amount, byte[] owner, String priKey, + /** 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; + // String priKey = testKey002; ECKey temKey = null; try { BigInteger priK = new BigInteger(priKey, 16); @@ -6720,14 +7075,15 @@ public static Return sendcoinForReturn(byte[] to, long amount, byte[] owner, Str return ret; } - /** - * constructor. - */ - - public static Transaction sendcoinForTransaction(byte[] to, long amount, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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; + // String priKey = testKey002; ECKey temKey = null; try { BigInteger priK = new BigInteger(priKey, 16); @@ -6750,11 +7106,14 @@ public static Transaction sendcoinForTransaction(byte[] to, long amount, byte[] return transaction; } - /** - * constructor. - */ - public static String marketSellAsset(byte[] owner, String priKey, byte[] sellTokenId, - long sellTokenQuantity, byte[] buyTokenId, long buyTokenQuantity, + /** constructor. */ + public static String marketSellAsset( + byte[] owner, + String priKey, + byte[] sellTokenId, + long sellTokenQuantity, + byte[] buyTokenId, + long buyTokenQuantity, WalletGrpc.WalletBlockingStub blockingStubFull) { ECKey temKey = null; @@ -6766,8 +7125,8 @@ public static String marketSellAsset(byte[] owner, String priKey, byte[] sellTok } final ECKey ecKey = temKey; - MarketContract.MarketSellAssetContract.Builder builder = MarketContract.MarketSellAssetContract - .newBuilder(); + MarketContract.MarketSellAssetContract.Builder builder = + MarketContract.MarketSellAssetContract.newBuilder(); builder .setOwnerAddress(ByteString.copyFrom(owner)) .setSellTokenId(ByteString.copyFrom(sellTokenId)) @@ -6799,20 +7158,24 @@ public static String marketSellAsset(byte[] owner, String priKey, byte[] sellTok 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; - } - /** - * constructor. - */ - public static Return marketSellAssetGetResposne(byte[] owner, String priKey, byte[] sellTokenId, - long sellTokenQuantity, byte[] buyTokenId, long buyTokenQuantity, + /** constructor. */ + public static Return marketSellAssetGetResposne( + byte[] owner, + String priKey, + byte[] sellTokenId, + long sellTokenQuantity, + byte[] buyTokenId, + long buyTokenQuantity, WalletGrpc.WalletBlockingStub blockingStubFull) { ECKey temKey = null; @@ -6824,8 +7187,8 @@ public static Return marketSellAssetGetResposne(byte[] owner, String priKey, byt } ECKey ecKey = temKey; - MarketContract.MarketSellAssetContract.Builder builder = MarketContract.MarketSellAssetContract - .newBuilder(); + MarketContract.MarketSellAssetContract.Builder builder = + MarketContract.MarketSellAssetContract.newBuilder(); builder .setOwnerAddress(ByteString.copyFrom(owner)) .setSellTokenId(ByteString.copyFrom(sellTokenId)) @@ -6836,14 +7199,11 @@ public static Return marketSellAssetGetResposne(byte[] owner, String priKey, byt TransactionExtention transactionExtention = blockingStubFull.marketSellAsset(builder.build()); return transactionExtention.getResult(); - } - /** - * constructor. - */ - public static String marketCancelOrder(byte[] owner, String priKey, byte[] orderId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** constructor. */ + public static String marketCancelOrder( + byte[] owner, String priKey, byte[] orderId, WalletGrpc.WalletBlockingStub blockingStubFull) { ECKey temKey = null; try { @@ -6854,8 +7214,8 @@ public static String marketCancelOrder(byte[] owner, String priKey, byte[] order } final ECKey ecKey = temKey; - MarketContract.MarketCancelOrderContract.Builder builder = MarketContract - .MarketCancelOrderContract.newBuilder(); + MarketContract.MarketCancelOrderContract.Builder builder = + MarketContract.MarketCancelOrderContract.newBuilder(); builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); @@ -6883,21 +7243,20 @@ public static String marketCancelOrder(byte[] owner, String priKey, byte[] order 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; } - /** - * constructor. - */ - - public static Return marketCancelOrderGetResposne(byte[] owner, String priKey, byte[] orderId, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** constructor. */ + public static Return marketCancelOrderGetResposne( + byte[] owner, String priKey, byte[] orderId, WalletGrpc.WalletBlockingStub blockingStubFull) { ECKey temKey = null; try { @@ -6908,8 +7267,8 @@ public static Return marketCancelOrderGetResposne(byte[] owner, String priKey, b } ECKey ecKey = temKey; - MarketContract.MarketCancelOrderContract.Builder builder = MarketContract - .MarketCancelOrderContract.newBuilder(); + MarketContract.MarketCancelOrderContract.Builder builder = + MarketContract.MarketCancelOrderContract.newBuilder(); builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); @@ -6920,11 +7279,9 @@ public static Return marketCancelOrderGetResposne(byte[] owner, String priKey, b return transactionExtention.getResult(); } - /** - * constructor. - */ - public static Optional getMarketOrderByAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** constructor. */ + public static Optional getMarketOrderByAccount( + byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { ByteString addressBs = ByteString.copyFrom(address); BytesMessage request = BytesMessage.newBuilder().setValue(addressBs).build(); @@ -6933,11 +7290,9 @@ public static Optional getMarketOrderByAccount(byte[] return Optional.ofNullable(marketOrderList); } - /** - * constructor. - */ - public static Optional getMarketOrderByAccountSolidity(byte[] address, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + /** constructor. */ + public static Optional getMarketOrderByAccountSolidity( + byte[] address, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { ByteString addressBs = ByteString.copyFrom(address); BytesMessage request = BytesMessage.newBuilder().setValue(addressBs).build(); @@ -6946,33 +7301,27 @@ public static Optional getMarketOrderByAccountSolidity return Optional.ofNullable(marketOrderList); } - /** - * constructor. - */ - public static Optional getMarketOrderById(byte[] order, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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) { + /** 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) { + /** constructor. */ + public static Optional getMarketPriceByPair( + byte[] sellTokenId, byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { Protocol.MarketOrderPair request = Protocol.MarketOrderPair.newBuilder() .setSellTokenId(ByteString.copyFrom(sellTokenId)) @@ -6983,11 +7332,9 @@ public static Optional getMarketPriceByPair(byte[] sel return Optional.ofNullable(marketPriceList); } - /** - * constructor. - */ - public static Optional getMarketOrderListByPair(byte[] sellTokenId, - byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { + /** constructor. */ + public static Optional getMarketOrderListByPair( + byte[] sellTokenId, byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { Protocol.MarketOrderPair request = Protocol.MarketOrderPair.newBuilder() .setSellTokenId(ByteString.copyFrom(sellTokenId)) @@ -6998,46 +7345,39 @@ public static Optional getMarketOrderListByPair(byte[] return Optional.ofNullable(marketOrderList); } - /** - * constructor. - */ + /** constructor. */ public static Optional getMarketOrderListByPairSolidity( byte[] sellTokenId, - byte[] buyTokenId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { + 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); + 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()); + Protocol.MarketOrderPairList marketOrderList = + blockingStubFull.getMarketPairList(EmptyMessage.newBuilder().build()); return Optional.ofNullable(marketOrderList); } - /** - * constructor. - */ + /** constructor. */ public static Optional getMarketPairListSolidity( WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Protocol.MarketOrderPairList marketOrderList = blockingStubSolidity - .getMarketPairList(EmptyMessage.newBuilder().build()); + Protocol.MarketOrderPairList marketOrderList = + blockingStubSolidity.getMarketPairList(EmptyMessage.newBuilder().build()); return Optional.ofNullable(marketOrderList); } - /** - * constructor. - */ + /** constructor. */ public static String stringToHexString(String s) { String str = ""; for (int i = 0; i < s.length(); i++) { @@ -7048,9 +7388,7 @@ public static String stringToHexString(String s) { return str; } - /** - * constructor. - */ + /** constructor. */ public static String hexStringToString(String s) { if (s == null || s.equals("")) { return null; @@ -7059,8 +7397,7 @@ public static String hexStringToString(String s) { 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)); + baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16)); } catch (Exception e) { e.printStackTrace(); } @@ -7074,16 +7411,12 @@ public static String hexStringToString(String s) { return s; } - /** - * constructor. - */ + /** constructor. */ public static String removeAll0sAtTheEndOfHexStr(String s) { return s.replaceAll("(00)+$", ""); } - /** - * constructor. - */ + /** constructor. */ public static String replaceCode(String code, String address) { if (code.indexOf("__$") == -1) { return code; @@ -7097,52 +7430,58 @@ public static String replaceCode(String code, String address) { } } - /** - * constructor. - */ - public static Map getAllowance2(Long startNum, Long endNum, - WalletGrpc.WalletBlockingStub blockingStubFull) { - final String blackHole = Configuration.getByPath("testng.conf") - .getString("defaultParameter.blackHoleAddress"); + /** 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(); + 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(); + 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()); + 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(); + List transList = + PublicMethed.getBlock(k, blockingStubFull).getTransactionsList(); for (Transaction tem : transList) { - String txid = ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - tem.getRawData().toByteArray())); + 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); + witnessAllowance.put( + witnessAdd, witnessAllowance.getOrDefault(witnessAdd, 0L) + packingFee); } } logger.info("========totalCount:" + totalCount); List chainParaList = - blockingStubFull.getChainParameters(EmptyMessage.newBuilder().build()) + blockingStubFull + .getChainParameters(EmptyMessage.newBuilder().build()) .getChainParameterList(); Long witness127PayPerBlock = 0L; Long witnessPayPerBlock = 0L; @@ -7154,8 +7493,11 @@ public static Map getAllowance2(Long startNum, Long endNum, witnessPayPerBlock = para.getValue(); } } - logger.info("witness127PayPerBlock:" + witness127PayPerBlock - + "\n witnessPayPerBlock:" + witnessPayPerBlock); + logger.info( + "witness127PayPerBlock:" + + witness127PayPerBlock + + "\n witnessPayPerBlock:" + + witnessPayPerBlock); for (Map.Entry entry : witnessBrokerage.entrySet()) { logger.info("-----witnessBrokerage " + entry.getKey() + " : " + entry.getValue()); @@ -7169,13 +7511,19 @@ 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)); - Long pay = (witnessBlockCount.get(witnessAdd) * witnessPayPerBlock - + (endNum - startNum) * witness127PayPerBlock * entry.getValue() / totalCount - + witnessAllowance.getOrDefault(witnessAdd, 0L)) - * witnessBrokerage.get(witnessAdd) / 100; + 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); @@ -7188,11 +7536,9 @@ public static String getContractStringMsg(byte[] contractMsgArray) { return ByteArray.toStr(ByteArray.subArray(contractMsgArray, 64, 64 + resultLenth)); } - /** - * constructor. - */ - public boolean updateBrokerage(byte[] owner, int brokerage, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** constructor. */ + public boolean updateBrokerage( + byte[] owner, int brokerage, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { ECKey temKey = null; try { @@ -7205,14 +7551,14 @@ 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()); + 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()); + System.out.println( + "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); } return false; } @@ -7222,61 +7568,61 @@ public boolean updateBrokerage(byte[] owner, int brokerage, String priKey, return response.getResult(); } - /** - * constructor. - */ - public static Long getAccountBalance(Protocol.Block block,byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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(); + 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(); + BalanceContract.AccountBalanceRequest accountBalanceRequest = + BalanceContract.AccountBalanceRequest.newBuilder() + .setAccountIdentifier(accountIdentifier) + .setBlockIdentifier(blockIdentifier) + .build(); return blockingStubFull.getAccountBalance(accountBalanceRequest).getBalance(); } - /** - * constructor. - */ - public static BalanceContract.BlockBalanceTrace getBlockBalance(Protocol.Block block, - WalletGrpc.WalletBlockingStub blockingStubFull) { + /** 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(); + 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) { + /** 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/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/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"); 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..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 @@ -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"); @@ -1057,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); 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..733fe939e7d --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java @@ -0,0 +1,1245 @@ +package stest.tron.wallet.dailybuild.jsonrpc; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import io.grpc.ManagedChannelBuilder; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import lombok.extern.slf4j.Slf4j; +import org.apache.http.HttpResponse; +import org.junit.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.tron.api.GrpcAPI; +import org.tron.api.WalletGrpc; +import org.tron.common.utils.ByteArray; +import org.tron.protos.Protocol.Block; +import stest.tron.wallet.common.client.utils.HttpMethed; +import stest.tron.wallet.common.client.utils.JsonRpcBase; +import stest.tron.wallet.common.client.utils.PublicMethed; + +@Slf4j +public class Accounts002 extends JsonRpcBase { + private JSONObject responseContent; + private HttpResponse response; + String realGasPrice; + String bid = null; + int indexNum = 0; + String indexHex = null; + JSONObject result = null; + String transacionHash = null; + String blockHash = null; + String blockNumHex = null; + String parentHash = null; + String txTrieRoot = null; + String witnessAddress = null; + String feeLimit = null; + String accountStateRoot = null; + String energyUsed = "0x135c6"; + + List transactionIdList = null; + long size = 0; + long gas = 0; + long blockTimeStamp = 0; + long gasPriceFromHttp = 0; + + /** constructor. */ + @BeforeClass(enabled = true) + public void beforeClass() { + channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); + blockingStubFull = WalletGrpc.newBlockingStub(channelFull); + } + + @Test(enabled = true, description = "Json rpc api of eth_accounts") + 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); + } + + @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; + } + } + 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)); + /* 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 = false, 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 = false, 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 = false, 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"); + } + + @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); + } + } +} 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..c566fc5532c --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.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 Accounts003 extends JsonRpcBase { + JSONObject responseContent; + HttpResponse response; + String topic0 = null; + String topic1 = null; + String fromBlock = null; + String toBlock = null; + String newFilterResultIdfrom01 = null; + String newFilterResultIdfrom02 = null; + String blockHash = null; + + @Test(enabled = true, description = "Eth api of eth_newFilter contains nothing.") + public void test01GetNewFilterContainNothing() { + JsonObject paramBody = new JsonObject(); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test01GetNewFilterContainNothing_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test01GetNewFilterContainNothing_responseContent" + responseContent); + logger.info("result:" + responseContent.getString("result")); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test( + enabled = true, + description = "Eth api of eth_newFilter contains address,fromBlock and toBlock.") + public void test02GetNewFilterContainAddress() { + if (blockNumForTrc20 - 10 < 0) { + fromBlock = "0"; + } else { + fromBlock = "0x" + Integer.toHexString(blockNumForTrc20 - 10); + } + toBlock = "0x" + Integer.toHexString(blockNumForTrc20 + 10); + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test02GetNewFilterContainAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test02GetNewFilterContainAddress_responseContent" + responseContent); + newFilterResultIdfrom01 = responseContent.getString("result"); + logger.info("test02GetNewFilterContainAddress_id:" + responseContent.getString("result")); + } + + @Test( + enabled = true, + description = "Eth api of eth_newFilter contains topic fromBlock and toBlock.") + public void test03GetNewFilterContainTopic() { + response = HttpMethed.getBlockByNum(httpFullNode, blockNumForTrc20); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("responseContent:" + responseContent); + logger.info("blockHash:" + responseContent.getString("blockID")); + + blockHash = responseContent.getString("blockID"); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + JsonObject paramBody = new JsonObject(); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test03GetNewFilterContainTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test03GetNewFilterContainTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + newFilterResultIdfrom02 = responseContent.getString("result"); + logger.info("test03GetNewFilterContainTopic_id:" + newFilterResultIdfrom02); + } + + @Test(enabled = true, description = "Eth api of eth_newFilter contains topic and address.") + public void test04GetNewFilterContainsTopicAndAddress() { + + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", fromBlock); + paramBody.addProperty("toBlock", toBlock); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test04GetNewFilterContainsTopicAndAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test04GetNewFilterContainsTopicAndAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_newFilter only contain topic and blockHash.") + public void test05GetNewFilterOnlyContainTopic() { + JsonObject paramBody = new JsonObject(); + paramBody.addProperty("blockHash", blockHash); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + paramBody.add("topics", topicArray); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test05GetNewFilterOnlyContainTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test05GetNewFilterOnlyContainTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_newFilter which only contains blockHash.") + public void test06GetNewFilterHasOnlyBlockHash() { + + response = HttpMethed.getNowBlock(httpFullNode); + responseContent = HttpMethed.parseResponseContent(response); + String blockHash = responseContent.getString("blockID"); + JsonObject paramBody = new JsonObject(); + paramBody.addProperty("blockHash", blockHash); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test06GetNewFilterHasOnlyBlockHash_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test06GetNewFilterHasOnlyBlockHash_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_newFilter check new and after block.") + public void test07GetNewFilterCheckNewBlock() { + JsonObject paramBody = new JsonObject(); + JsonArray topicArray = new JsonArray(); + topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); + paramBody.add("topics", topicArray); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test07GetNewFilterCheckNewBlock_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test07GetNewFilterCheckNewBlock_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_newBlockFilter") + public void test08GetEthNewBlockFilter() { + + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test08GetEthNewBlockFilter_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test08GetEthNewBlockFilter_responseContent:" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_getFilterChanges has less 20 elements.") + public void test09GetFilterChanges() { + + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); + String ethNewBlockFilterResult = responseContent.get("result").toString(); + logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); + String newFilterId = responseContent.getString("result"); + logger.info("newFilterId:" + newFilterId); + params = new JsonArray(); + params.add(newFilterId); + requestBody = getJsonRpcBody("eth_getFilterChanges", params); + logger.info("test09GetFilterChanges_requestBody: " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test09GetFilterChanges_responseContent:" + responseContent); + Assert.assertEquals("[]", responseContent.getString("result")); + } + + @Test( + enabled = true, + description = "Eth api of eth_getLogs contains address ,fromBlock and toBlock.") + public void test10GetLogsOnlyContainAddress() { + JsonArray addressArray = new JsonArray(); + logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); + addressArray.add(contractTrc20AddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + logger.info("blockNumForTrc20:" + blockNumForTrc20); + paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 20))); + paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 20))); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); + logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test10GetLogsOnlyContainAddress_responseContent:" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + String address = + responseContent.getJSONArray("result").getJSONObject(0).getString("address").substring(2); + Assert.assertEquals(address, contractTrc20AddressFrom58.substring(2)); + topic0 = responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); + } + + @Test(enabled = true, description = "Eth api of eth_getLogs both contains topic and address.") + public void test11GetLogsContainsTopicAndAddress() { + JsonArray topicArray = new JsonArray(); + topicArray.add(topic0); + JsonObject paramBody = new JsonObject(); + paramBody.add("topics", topicArray); + paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 10))); + paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 10))); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); + logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test11GetLogsContainsTopicAndAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + String topicFromResult = + responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); + Assert.assertEquals(topicFromResult, topic0); + } + + @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") + public void test12GetFilterLogsContainsAddress() { + + JsonArray params = new JsonArray(); + params.add(newFilterResultIdfrom01); + JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); + logger.info("test12GetFilterLogsContainsAddress_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test12GetFilterLogsContainsAddress_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") + public void test13GetFilterLogsContainsTopic() { + + JsonArray params = new JsonArray(); + params.add(newFilterResultIdfrom02); + JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); + logger.info("test13GetFilterLogsContainsTopic_requestBody " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test13GetFilterLogsContainsTopic_responseContent" + responseContent); + Assert.assertNotNull(responseContent.getString("result")); + } + + @Test( + enabled = true, + description = + "Eth api of eth_uninstallFilter which method is eth_newFilter" + + " and params has one element ") + public void test14EthUninstallFilter() { + // create ID + JsonArray addressArray = new JsonArray(); + addressArray.add(contractAddressFrom58.substring(2)); + JsonObject paramBody = new JsonObject(); + paramBody.add("address", addressArray); + paramBody.addProperty("fromBlock", "0x1f8b6a7"); + paramBody.addProperty("toBlock", "0x1f8b6a7"); + JsonArray params = new JsonArray(); + params.add(paramBody); + JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); + logger.info("test14_newfilter " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_newfilter_responseContentr" + responseContent); + String ethNewFilterResult = responseContent.get("result").toString(); + logger.info("EthNewFilterResult:" + ethNewFilterResult); + Assert.assertNotNull(responseContent.getString("result")); + + // verify ID invalid + + // first time + params = new JsonArray(); + params.add(responseContent.get("result").toString()); + requestBody = getJsonRpcBody("eth_uninstallFilter", params); + logger.info("test14_eth_uninstallFilter " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_eth_uninstallFilter_responseContentr_first" + responseContent); + Assert.assertEquals(responseContent.get("result"), true); + // second time + logger.info("test14_eth_uninstallFilter_second " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14_eth_uninstallFilter_responseContentr_second " + responseContent); + Assert.assertEquals( + responseContent.getJSONObject("error").getString("message"), "filter not found"); + + // query getFilterChanges to verify ID has invalid + params = new JsonArray(); + params.add(ethNewFilterResult); + requestBody = getJsonRpcBody("getFilterChanges", params); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test14EthUninstallFilter_responseContent" + responseContent); + String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; + Assert.assertEquals(responseContent.get("error").toString(), expectResult); + } + + @Test( + enabled = true, + description = + "Eth api of eth_uninstallFilter which method is eth_newBlockFilter" + + " and params has one element ") + public void test15EthUninstallFilter() { + // create ID + + JsonArray params = new JsonArray(); + JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); + logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); + String ethNewBlockFilterResult = responseContent.get("result").toString(); + logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); + Assert.assertNotNull(responseContent.getString("result")); + + // verify ID invalid + // first time + params = new JsonArray(); + params.add(responseContent.get("result").toString()); + requestBody = getJsonRpcBody("eth_uninstallFilter", params); + logger.info("test15_eth_uninstallFilter " + requestBody); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15_eth_uninstallFilter_responseContentr_first" + responseContent); + Assert.assertEquals(responseContent.get("result"), true); + // second time + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15_eth_uninstallFilter_responseContentr_second" + responseContent); + Assert.assertEquals( + responseContent.getJSONObject("error").getString("message"), "filter not found"); + // query getFilterChanges to verify ID has invalid + params = new JsonArray(); + params.add(ethNewBlockFilterResult); + requestBody = getJsonRpcBody("getFilterChanges", params); + response = getJsonRpc(jsonRpcNode, requestBody); + responseContent = HttpMethed.parseResponseContent(response); + logger.info("test15EthUninstallFilter_responseContent" + responseContent); + String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; + Assert.assertEquals(responseContent.get("error").toString(), expectResult); + } +} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java new file mode 100644 index 00000000000..be42416ccbb --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java @@ -0,0 +1,374 @@ +package stest.tron.wallet.dailybuild.jsonrpc; + +import com.alibaba.fastjson.JSONObject; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.HttpResponse; +import org.junit.Assert; +import org.testng.annotations.Test; +import stest.tron.wallet.common.client.utils.HttpMethed; +import stest.tron.wallet.common.client.utils.JsonRpcBase; + +@Slf4j +public class Accounts004 extends JsonRpcBase { + JSONObject responseContent; + HttpResponse response; + String topic0 = null; + String topic1 = null; + String fromBlock = null; + String toBlock = null; + String newFilterResultIdfrom01 = null; + String newFilterResultIdfrom02 = null; + String blockHash = null; + + @Test(enabled = true, description = "Eth api of eth_newFilter contains nothing.") + 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(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() { + + 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(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_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); + 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_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); + } +} 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); 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..65515d6db51 --- /dev/null +++ b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java @@ -0,0 +1,509 @@ +package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; + +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import java.util.HashMap; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; +import org.tron.api.GrpcAPI; +import org.tron.api.WalletGrpc; +import org.tron.common.crypto.ECKey; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.Utils; +import org.tron.core.Wallet; +import org.tron.protos.Protocol; +import org.tron.protos.contract.SmartContractOuterClass; +import stest.tron.wallet.common.client.Configuration; +import stest.tron.wallet.common.client.Parameter; +import stest.tron.wallet.common.client.utils.Base58; +import stest.tron.wallet.common.client.utils.PublicMethed; + + + +@Slf4j +public class Opcode { + + private final String testNetAccountKey = Configuration.getByPath("testng.conf") + .getString("foundationAccount.key2"); + private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); + byte[] mapKeyContract = null; + ECKey ecKey1 = new ECKey(Utils.getRandom()); + byte[] contractExcAddress = ecKey1.getAddress(); + String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); + private Long maxFeeLimit = Configuration.getByPath("testng.conf") + .getLong("defaultParameter.maxFeeLimit"); + private ManagedChannel channelFull = null; + private WalletGrpc.WalletBlockingStub blockingStubFull = null; + + private String fullnode = Configuration.getByPath("testng.conf") + .getStringList("fullnode.ip.list").get(0); + + @BeforeSuite + public void beforeSuite() { + Wallet wallet = new Wallet(); + Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); + } + + /** + * constructor. + */ + + @BeforeClass(enabled = true) + public void beforeClass() { + PublicMethed.printAddress(contractExcKey); + channelFull = ManagedChannelBuilder.forTarget(fullnode) + .usePlaintext(true) + .build(); + blockingStubFull = WalletGrpc.newBlockingStub(channelFull); + + Assert.assertTrue(PublicMethed + .sendcoin(contractExcAddress, 300100_000_000L, + testNetAccountAddress, testNetAccountKey, blockingStubFull)); + PublicMethed.waitProduceNextBlock(blockingStubFull); + + String filePath = "src/test/resources/soliditycode/opCode.sol"; + String contractName = "A"; + HashMap retMap = PublicMethed.getBycodeAbiNoOptimize(filePath, contractName); + String code = retMap.get("byteCode").toString(); + String abi = retMap.get("abI").toString(); + mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, + 0L, 100, null, contractExcKey, + contractExcAddress, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, + blockingStubFull); + Assert.assertNotNull(smartContract.getAbi()); + + } + + + @Test(enabled = true, description = "test opcode smod, used for int") + public void test01Smod() { + GrpcAPI.TransactionExtention transactionExtention = PublicMethed + .triggerConstantContractForExtention(mapKeyContract, + "sssmod()", "#", true, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); + logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); + Assert.assertEquals(1, trueRes); + } + + @Test(enabled = true, description = "test opcode extcodecopy return contract bytecode") + public void test02Extcodecopy() { + String base58 = Base58.encode58Check(mapKeyContract); + String txid = PublicMethed.triggerContract(mapKeyContract, + "eextcodecopy(address)", "\"" + base58 + "\"", false, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + Optional infoById = PublicMethed + .getTransactionInfoById(txid, blockingStubFull); + logger.info("txid: " + txid + "\n" + infoById.toString()); + Assert.assertEquals(0, infoById.get().getResultValue()); + Assert.assertTrue(ByteArray.toHexString( + infoById.get().getContractResult(0).toByteArray()).length() > 0); + + } + + @Test(enabled = true, description = "test opcode coinbase," + + "block.coinbase is sr address which produced the block") + public void test03Coinbase() { + GrpcAPI.TransactionExtention transactionExtention = PublicMethed + .triggerConstantContractForExtention(mapKeyContract, + "cccoinbase()", "#", true, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + String trueRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); + logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); + Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); + Assert.assertTrue(trueRes.startsWith("00000000000000000000000" + + "0bafb56091591790e00aa05eaddcc7dc1474b5d4b") + || trueRes.startsWith("0000000000000000000000000be88a918d74d0dfd71dc84bd4abf036d0562991")); + + } + + @Test(enabled = true, description = "test opcode difficulty,block.difficulty is always 0") + public void test04Difficulty() { + GrpcAPI.TransactionExtention transactionExtention = PublicMethed + .triggerConstantContractForExtention(mapKeyContract, + "ddifficulty()", "#", true, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); + logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); + Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); + Assert.assertEquals(0, trueRes); + + } + + @Test(enabled = true, description = "test opcode gaslimit,block.gaslimit is always 0") + public void test05Gaslimit() { + GrpcAPI.TransactionExtention transactionExtention = PublicMethed + .triggerConstantContractForExtention(mapKeyContract, + "gggaslimit()", "#", true, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); + logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); + Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); + Assert.assertEquals(0, trueRes); + + } + + @Test(enabled = true, description = "test opcode pc,return current position, " + + "ppppc() can refer to opCode.sol") + public void test06Pc() { + String code = "608060405260838060116000396000f3fe608060405234" + + "8015600f57600080fd5b506004361060285760003560e01c806" + + "36d3a027714602d575b600080fd5b60336045565b6040805191825251" + + "9081900360200190f35b60005890509056fea264697" + + "0667358221220fe03cbd3d2aae7454565f203b9abd76ce74cf0ac" + + "a079b151cf6b8e2bfda2d5c464736f6c634300060c0033"; + String abi = "[\n" + + "\t{\n" + + "\t\t\"inputs\": [],\n" + + "\t\t\"stateMutability\": \"payable\",\n" + + "\t\t\"type\": \"constructor\"\n" + + "\t},\n" + + "\t{\n" + + "\t\t\"inputs\": [],\n" + + "\t\t\"name\": \"ppppc\",\n" + + "\t\t\"outputs\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"internalType\": \"uint256\",\n" + + "\t\t\t\t\"name\": \"a\",\n" + + "\t\t\t\t\"type\": \"uint256\"\n" + + "\t\t\t}\n" + + "\t\t],\n" + + "\t\t\"stateMutability\": \"nonpayable\",\n" + + "\t\t\"type\": \"function\"\n" + + "\t}\n" + + "]"; + byte[] temContract = PublicMethed.deployContract("A", abi, code, "", maxFeeLimit, + 0L, 100, null, contractExcKey, + contractExcAddress, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(temContract, + blockingStubFull); + Assert.assertNotNull(smartContract.getAbi()); + + GrpcAPI.TransactionExtention transactionExtention = PublicMethed + .triggerConstantContractForExtention(temContract, + "ppppc()", "#", true, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); + logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); + Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); + Assert.assertEquals(72, trueRes); + + } + + @Test(enabled = true, description = "test opcode msize,return size of memory, " + + "msize cannot be used if optimize is open, mmmsize() can refer to opCode.sol") + public void test07Msize() { + String code = "608060405260b5806100126000396000f3fe6080604052348015600f5760" + + "0080fd5b506004361060285760003560e01c8063bf1a725d14602d575b600080fd5b60" + + "336047565b604051603e9190605c565b60405180910390f35b600059905090565b6056" + + "816075565b82525050565b6000602082019050606f6000830184604f565b9291505056" + + "5b600081905091905056fea26469706673582212202252652aad4bca9a4aa9db179e03" + + "f7b3bf439f47152e31f45d8587b710bce79664736f6c63430008060033"; + String abi = "[\n" + + "\t{\n" + + "\t\t\"inputs\": [],\n" + + "\t\t\"stateMutability\": \"payable\",\n" + + "\t\t\"type\": \"constructor\"\n" + + "\t},\n" + + "\t{\n" + + "\t\t\"inputs\": [],\n" + + "\t\t\"name\": \"mmmsize\",\n" + + "\t\t\"outputs\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"internalType\": \"uint256\",\n" + + "\t\t\t\t\"name\": \"a\",\n" + + "\t\t\t\t\"type\": \"uint256\"\n" + + "\t\t\t}\n" + + "\t\t],\n" + + "\t\t\"stateMutability\": \"nonpayable\",\n" + + "\t\t\"type\": \"function\"\n" + + "\t}\n" + + "]"; + byte[] temContract = PublicMethed.deployContract("A", abi, code, "", maxFeeLimit, + 0L, 100, null, contractExcKey, + contractExcAddress, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(temContract, + blockingStubFull); + Assert.assertNotNull(smartContract.getAbi()); + + GrpcAPI.TransactionExtention transactionExtention = PublicMethed + .triggerConstantContractForExtention(temContract, + "mmmsize()", "#", true, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); + logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); + Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); + Assert.assertEquals(96, trueRes); + + } + + + @Test(enabled = true, description = "test opcode swap14-16,solidity cannot use optimize") + public void test08Swap() { + GrpcAPI.TransactionExtention transactionExtention = PublicMethed + .triggerConstantContractForExtention(mapKeyContract, + "ssswap()", "#", true, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); + logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); + Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); + Assert.assertEquals(1, trueRes); + + } + + @Test(enabled = true, description = "test opcode push13-30 but exclude push20 and push29," + + "solidity cannot use optimize") + public void test08Pushx() { + GrpcAPI.TransactionExtention transactionExtention = PublicMethed + .triggerConstantContractForExtention(mapKeyContract, + "pppushx()", "#", true, + 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + Protocol.Transaction transaction = transactionExtention.getTransaction(); + String trueRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); + logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); + Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); + Assert.assertTrue(trueRes.contains("000000000000000000000000000000000000001" + + "1223344556677889900112233")); + } + + @Test(enabled = true, description = "test opcode callcode,difference with delegatecall " + + "is caller and callvalue,the bytecode is compiled with solidity 0.4.22, " + + "can refer to opCode.sol for code") + public void test09Callcode() { + String code = "60806040526103b4806100136000396000f3006080604052600436106100565763" + + "ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416634" + + "cb335db811461005b578063ae02d91d14610081578063ea856db2146100a5575b600080fd5b61007f" + + "73ffffffffffffffffffffffffffffffffffffffff600435166024356100c9565b005b61007f73ffff" + + "ffffffffffffffffffffffffffffffffffff600435166024356101b6565b61007f73ffffffffffffff" + + "ffffffffffffffffffffffffff600435166024356102a3565b604080516024808201849052825180830" + + "39091018152604490910182526020810180517bffffffffffffffffffffffffffffffffffffffffffff" + + "ffffffffffff167f66c99139000000000000000000000000000000000000000000000000000000001781529" + + "151815173ffffffffffffffffffffffffffffffffffffffff861693600a93929182919080838360005b8" + + "3811015610170578181015183820152602001610158565b50505050905090810190601f16801561019d5" + + "780820380516001836020036101000a031916815260200191505b5091505060006040518083038185875" + + "af1505050505050565b60408051602480820184905282518083039091018152604490910182526020810" + + "180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f66c99139000000000" + + "000000000000000000000000000000000000000000000001781529151815173fffffffffffffffffffff" + + "fffffffffffffffffff861693600a93929182919080838360005b8381101561025d57818101518382015" + + "2602001610245565b50505050905090810190601f16801561028a5780820380516001836020036101000" + + "a031916815260200191505b5091505060006040518083038185875af2505050505050565b60408051602" + + "480820184905282518083039091018152604490910182526020810180517bfffffffffffffffffffffff" + + "fffffffffffffffffffffffffffffffff167f66c991390000000000000000000000000000000000000000" + + "00000000000000001781529151815173ffffffffffffffffffffffffffffffffffffffff8616938291808" + + "38360005b8381101561034457818101518382015260200161032c565b50505050905090810190601f1680" + + "156103715780820380516001836020036101000a031916815260200191505b50915050600060405180830" + + "381855af450505050505600a165627a7a72305820210d132d0c4006264ef113f342556c616d9e69acc20" + + "bfa80cf440a4eac170de80029"; + String abi = "[\n" + + "\t{\n" + + "\t\t\"constant\": false,\n" + + "\t\t\"inputs\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"name\": \"callCAddress\",\n" + + "\t\t\t\t\"type\": \"address\"\n" + + "\t\t\t},\n" + + "\t\t\t{\n" + + "\t\t\t\t\"name\": \"amount\",\n" + + "\t\t\t\t\"type\": \"uint256\"\n" + + "\t\t\t}\n" + + "\t\t],\n" + + "\t\t\"name\": \"testInCall\",\n" + + "\t\t\"outputs\": [],\n" + + "\t\t\"payable\": true,\n" + + "\t\t\"stateMutability\": \"payable\",\n" + + "\t\t\"type\": \"function\"\n" + + "\t},\n" + + "\t{\n" + + "\t\t\"constant\": false,\n" + + "\t\t\"inputs\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"name\": \"callCAddress\",\n" + + "\t\t\t\t\"type\": \"address\"\n" + + "\t\t\t},\n" + + "\t\t\t{\n" + + "\t\t\t\t\"name\": \"amount\",\n" + + "\t\t\t\t\"type\": \"uint256\"\n" + + "\t\t\t}\n" + + "\t\t],\n" + + "\t\t\"name\": \"testInCallcode\",\n" + + "\t\t\"outputs\": [],\n" + + "\t\t\"payable\": true,\n" + + "\t\t\"stateMutability\": \"payable\",\n" + + "\t\t\"type\": \"function\"\n" + + "\t},\n" + + "\t{\n" + + "\t\t\"constant\": false,\n" + + "\t\t\"inputs\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"name\": \"callCAddress\",\n" + + "\t\t\t\t\"type\": \"address\"\n" + + "\t\t\t},\n" + + "\t\t\t{\n" + + "\t\t\t\t\"name\": \"amount\",\n" + + "\t\t\t\t\"type\": \"uint256\"\n" + + "\t\t\t}\n" + + "\t\t],\n" + + "\t\t\"name\": \"testIndelegateCall\",\n" + + "\t\t\"outputs\": [],\n" + + "\t\t\"payable\": true,\n" + + "\t\t\"stateMutability\": \"payable\",\n" + + "\t\t\"type\": \"function\"\n" + + "\t},\n" + + "\t{\n" + + "\t\t\"inputs\": [],\n" + + "\t\t\"payable\": true,\n" + + "\t\t\"stateMutability\": \"payable\",\n" + + "\t\t\"type\": \"constructor\"\n" + + "\t}\n" + + "]"; + byte[] contractA = PublicMethed.deployContract("A", abi, code, "", maxFeeLimit, + 1000000L, 100, null, contractExcKey, + contractExcAddress, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(contractA, + blockingStubFull); + Assert.assertNotNull(smartContract.getAbi()); + + code = "608060405260d2806100126000396000f300608060405260043610603e5763ffffffff7c0" + + "10000000000000000000000000000000000000000000000000000000060003504166366c99" + + "13981146043575b600080fd5b604c600435604e565b005b6040805173fffffffffffffffff" + + "fffffffffffffffffffffff3316815234602082015280820183905290517fac74fdf75f0e5" + + "a43f870f7135801b44f404be82b1dcad73423c542b840d1d64b9181900360600190a150560" + + "0a165627a7a72305820c460a35f70e363777be22b3a4ace5f95533de626073ab4e06d9bf3bbb2cffceb0029"; + abi = "[\n" + + "\t{\n" + + "\t\t\"constant\": false,\n" + + "\t\t\"inputs\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"name\": \"amount\",\n" + + "\t\t\t\t\"type\": \"uint256\"\n" + + "\t\t\t}\n" + + "\t\t],\n" + + "\t\t\"name\": \"trans\",\n" + + "\t\t\"outputs\": [],\n" + + "\t\t\"payable\": true,\n" + + "\t\t\"stateMutability\": \"payable\",\n" + + "\t\t\"type\": \"function\"\n" + + "\t},\n" + + "\t{\n" + + "\t\t\"inputs\": [],\n" + + "\t\t\"payable\": true,\n" + + "\t\t\"stateMutability\": \"payable\",\n" + + "\t\t\"type\": \"constructor\"\n" + + "\t},\n" + + "\t{\n" + + "\t\t\"anonymous\": false,\n" + + "\t\t\"inputs\": [\n" + + "\t\t\t{\n" + + "\t\t\t\t\"indexed\": false,\n" + + "\t\t\t\t\"name\": \"\",\n" + + "\t\t\t\t\"type\": \"address\"\n" + + "\t\t\t},\n" + + "\t\t\t{\n" + + "\t\t\t\t\"indexed\": false,\n" + + "\t\t\t\t\"name\": \"\",\n" + + "\t\t\t\t\"type\": \"uint256\"\n" + + "\t\t\t},\n" + + "\t\t\t{\n" + + "\t\t\t\t\"indexed\": false,\n" + + "\t\t\t\t\"name\": \"\",\n" + + "\t\t\t\t\"type\": \"uint256\"\n" + + "\t\t\t}\n" + + "\t\t],\n" + + "\t\t\"name\": \"clog\",\n" + + "\t\t\"type\": \"event\"\n" + + "\t}\n" + + "]"; + byte[] contractC = PublicMethed.deployContract("C", abi, code, "", maxFeeLimit, + 0L, 100, null, contractExcKey, + contractExcAddress, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + smartContract = PublicMethed.getContract(contractC, + blockingStubFull); + Assert.assertNotNull(smartContract.getAbi()); + + String base58C = Base58.encode58Check(contractC); + + String txid = PublicMethed.triggerContract(contractA, + "testInCall(address,uint256)", "\"" + base58C + "\",1", false, + 1, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + Optional infoById = PublicMethed + .getTransactionInfoById(txid, blockingStubFull); + Assert.assertEquals(0, infoById.get().getResultValue()); + String logRes = ByteArray.toHexString(infoById.get().getLog(0).getData().toByteArray()); + System.out.println("000000: " + logRes); + String b = "41" + logRes.substring(24, 64); + String c = logRes.substring(64, 128); + String x = ByteArray.toHexString(contractA); + Assert.assertEquals(b, x); + Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000000a", c); + + txid = PublicMethed.triggerContract(contractA, + "testIndelegateCall(address,uint256)", "\"" + base58C + "\",1", false, + 2, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + infoById = PublicMethed + .getTransactionInfoById(txid, blockingStubFull); + logger.info("txid: " + txid + "\n" + infoById.toString()); + Assert.assertEquals(0, infoById.get().getResultValue()); + logRes = ByteArray.toHexString(infoById.get().getLog(0).getData().toByteArray()); + System.out.println("000000: " + logRes); + b = "41" + logRes.substring(24, 64); + c = logRes.substring(64, 128); + x = ByteArray.toHexString(contractExcAddress); + Assert.assertEquals(b, x); + Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000002", c); + + + txid = PublicMethed.triggerContract(contractA, + "testInCallcode(address,uint256)", "\"" + base58C + "\",1", false, + 3, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + infoById = PublicMethed + .getTransactionInfoById(txid, blockingStubFull); + logger.info("txid: " + txid + "\n" + infoById.toString()); + Assert.assertEquals(0, infoById.get().getResultValue()); + logRes = ByteArray.toHexString(infoById.get().getLog(0).getData().toByteArray()); + System.out.println("000000: " + logRes); + b = "41" + logRes.substring(24, 64); + c = logRes.substring(64, 128); + x = ByteArray.toHexString(contractA); + Assert.assertEquals(b, x); + Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000000a", c); + } + + + /** + * constructor. + */ + @AfterClass + public void shutdown() throws InterruptedException { + PublicMethed.freedResource(contractExcAddress, contractExcKey, + testNetAccountAddress, blockingStubFull); + if (channelFull != null) { + channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); + } + } + + +} + diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java b/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java index 2616c3835e8..1b1ca3ab2e9 100644 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java +++ b/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java @@ -1,7 +1,11 @@ package stest.tron.wallet.onlinestress; +import com.alibaba.fastjson.JSONObject; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; import com.google.protobuf.ByteString; import io.grpc.ManagedChannel; +import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import java.io.BufferedReader; import java.io.File; @@ -10,8 +14,20 @@ import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.util.HashMap; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.PoolingClientConnectionManager; +import org.apache.http.params.CoreConnectionPNames; +import org.apache.http.util.EntityUtils; +import org.bouncycastle.util.encoders.Hex; import org.junit.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -29,17 +45,20 @@ import org.zeromq.ZMQ; import stest.tron.wallet.common.client.Configuration; import stest.tron.wallet.common.client.Parameter.CommonConstant; +import stest.tron.wallet.common.client.WalletClient; +import stest.tron.wallet.common.client.utils.HttpMethed; +import stest.tron.wallet.common.client.utils.JsonRpcBase; import stest.tron.wallet.common.client.utils.PublicMethed; import zmq.ZMQ.Event; @Slf4j -public class ContractEvent001 { +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 +71,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 +88,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 +110,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 +129,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 +409,290 @@ 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(); + logger.info("event001Address:" + event001Address); + String event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); + ECKey ecKey2 = new ECKey(Utils.getRandom()); + byte[] event002Address = ecKey2.getAddress(); + logger.info("event002Address:" + event002Address); + String event002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); + PublicMethed.printAddress(event001Key); + PublicMethed.printAddress(testKey002); + + Assert.assertTrue( + PublicMethed.sendcoin( + event001Address, maxFeeLimit * 30, fromAddress, testKey002, blockingStubFull)); + Assert.assertTrue( + PublicMethed.sendcoin( + event002Address, maxFeeLimit * 30, fromAddress, testKey002, blockingStubFull)); + PublicMethed.waitProduceNextBlock(blockingStubFull1); + + String contractName = "SolidityTest"; + String filePath = "./src/test/resources/soliditycode/testGetFilterChange.sol"; + HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); + + String code = retMap.get("byteCode").toString(); + String abi = retMap.get("abI").toString(); + byte[] contractAddress = + PublicMethed.deployContract( + contractName, + abi, + code, + "", + maxFeeLimit, + 0L, + 50, + null, + event001Key, + event001Address, + blockingStubFull); + PublicMethed.waitProduceNextBlock(blockingStubFull); + SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); + Assert.assertTrue(smartContract.getAbi() != null); + logger.info("11111111111111111111111111111111111"); + Thread.sleep(180000); + + long txidNum = 0; + HttpResponse response = getNowBlock(httpFullNode); + JSONObject responseContent = parseResponseContent(response); + long blockBefore = + responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); + logger.info("blockBefore:" + blockBefore); + Thread.sleep(180000); + for (int i = 0; i < 5000; i++) { + String txid = + PublicMethed.triggerContract( + contractAddress, + "getResult(uint256)", + param, + false, + 2L, + 100000000L, + event002Address, + event002Key, + blockingStubFull); + logger.info("txid:" + txid); + txidNum++; + } + Thread.sleep(180000); + response = getNowBlock(httpFullNode); + responseContent = parseResponseContent(response); + long blockAfter = + responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); + + logger.info("txidNum:" + txidNum); + + // 扫块 + long sumLogs = 0; + long totalTransactionsSize = 0; + logger.info("blockBefore:" + blockBefore); + logger.info("blockAfter:" + blockAfter); + for (long i = blockBefore; i <= blockAfter; i++) { + + response = getTransactionCountByBlocknum(httpFullNode, (int) i); + responseContent = parseResponseContent(response); + long transactionsSize = responseContent.getLong("count"); + + totalTransactionsSize += transactionsSize; + } + logger.info( + (int) (Thread.currentThread().getId()) + + "sumLogs:" + + totalTransactionsSize * Long.parseLong(param)); + } + + public static String[] arr = + new String[] { + "00", + "0x6b5c9c34aae469576dfcde3655c9036d", + "0x450de4565abf4434d66948fb2a568608", + "0x02a65b2cc37d2d34808a63b50b86e0cd", + "0x7474d244cecf3a943bf8ac6dbd7d60fa", + "0x4ab110c02b04d7781f774eeffa6432a3" + }; + + @Test( + enabled = true, + threadPoolSize = 5, + invocationCount = 5, + description = "Eth api of eth_getFilterChanges .") + public void test09GetFilterChanges() { + long sumSize = 0; + while (true) { + JsonArray params = new JsonArray(); + String id = arr[(int) (Thread.currentThread().getId()) - 16]; + params.add(id); + JsonObject requestBody = getJsonRpcBody("eth_getFilterChanges", params); + HttpResponse response = getJsonRpc(jsonRpcNode, requestBody); + JSONObject responseContent = parseResponseContent(response); + long size = responseContent.getJSONArray("result").size(); + sumSize += size; + logger.info(Thread.currentThread().getId() + ":sumSize:" + sumSize); + } + } + + /** constructor. */ + public static JSONObject parseResponseContent(HttpResponse response) { + try { + String result = EntityUtils.toString(response.getEntity()); + StringEntity entity = new StringEntity(result, Charset.forName("UTF-8")); + response.setEntity(entity); + JSONObject obj = JSONObject.parseObject(result); + return obj; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /* public static HttpResponse getNowBlock(String httpNode, Boolean visible) { + try { + String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + httppost.releaseConnection(); + return null; + } + return response; + }*/ + + /** constructor. */ + public static HttpResponse getTransactionCountByBlocknum(String httpNode, long blocknum) { + HttpResponse response; + try { + + String requestUrl = "http://" + httpNode + "/wallet/gettransactioncountbyblocknum"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("num", blocknum); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + + return null; + } + return response; + } + + public static HttpResponse getNowBlock(String httpNode) { + return getNowBlock(httpNode, false); + } + + /** constructor. */ + public static HttpResponse getNowBlock(String httpNode, Boolean visible) { + + HttpResponse response; + try { + String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; + JsonObject userBaseObj2 = new JsonObject(); + userBaseObj2.addProperty("visible", visible); + response = createConnect(requestUrl, userBaseObj2); + } catch (Exception e) { + e.printStackTrace(); + + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse createConnect(String url, JsonObject requestBody) { + HttpResponse response; + HttpPost httppost; + HttpClient httpClient; + Integer connectionTimeout = + Configuration.getByPath("testng.conf").getInt("defaultParameter.httpConnectionTimeout"); + Integer soTimeout = + Configuration.getByPath("testng.conf").getInt("defaultParameter.httpSoTimeout"); + PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(); + pccm.setDefaultMaxPerRoute(80); + pccm.setMaxTotal(100); + + httpClient = new DefaultHttpClient(pccm); + try { + + httpClient + .getParams() + .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); + httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); + httppost = new HttpPost(url); + httppost.setHeader("Content-type", "application/json; charset=utf-8"); + httppost.setHeader("Connection", "Close"); + if (requestBody != null) { + StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httppost.setEntity(entity); + } + + logger.info(httppost.toString()); + response = httpClient.execute(httppost); + } catch (Exception e) { + e.printStackTrace(); + + return null; + } + return response; + } + + /** constructor. */ + public static HttpResponse getJsonRpc(String jsonRpcNode, JsonObject jsonRpcObject) { + HttpResponse response; + try { + String requestUrl = "http://" + jsonRpcNode + "/jsonrpc"; + response = createConnect(requestUrl, jsonRpcObject); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + return response; + } + @Test(enabled = true, description = "Subscribe event client") public void testEnergyCostDetail() { ZMQ.Context context = ZMQ.context(1); @@ -281,36 +723,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 +759,3 @@ public void shutdown() throws InterruptedException { } } } - - 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 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