DemoSample.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. package com.izouma.nineth;
  2. import com.alipay.mychain.sdk.api.MychainClient;
  3. import com.alipay.mychain.sdk.api.env.ClientEnv;
  4. import com.alipay.mychain.sdk.api.env.ISslOption;
  5. import com.alipay.mychain.sdk.api.env.SignerOption;
  6. import com.alipay.mychain.sdk.api.env.SslBytesOption;
  7. import com.alipay.mychain.sdk.api.logging.AbstractLoggerFactory;
  8. import com.alipay.mychain.sdk.api.logging.ILogger;
  9. import com.alipay.mychain.sdk.api.utils.ConfidentialUtil;
  10. import com.alipay.mychain.sdk.api.utils.Utils;
  11. import com.alipay.mychain.sdk.common.VMTypeEnum;
  12. import com.alipay.mychain.sdk.crypto.MyCrypto;
  13. import com.alipay.mychain.sdk.crypto.keyoperator.Pkcs8KeyOperator;
  14. import com.alipay.mychain.sdk.crypto.keypair.Keypair;
  15. import com.alipay.mychain.sdk.crypto.signer.SignerBase;
  16. import com.alipay.mychain.sdk.domain.account.Identity;
  17. import com.alipay.mychain.sdk.errorcode.ErrorCode;
  18. import com.alipay.mychain.sdk.message.query.QueryAccountResponse;
  19. import com.alipay.mychain.sdk.message.transaction.AbstractTransactionRequest;
  20. import com.alipay.mychain.sdk.message.transaction.TransactionReceiptResponse;
  21. import com.alipay.mychain.sdk.message.transaction.confidential.ConfidentialRequest;
  22. import com.alipay.mychain.sdk.message.transaction.contract.CallContractRequest;
  23. import com.alipay.mychain.sdk.message.transaction.contract.DeployContractRequest;
  24. import com.alipay.mychain.sdk.type.BaseFixedSizeUnsignedInteger;
  25. import com.alipay.mychain.sdk.utils.ByteUtils;
  26. import com.alipay.mychain.sdk.utils.IOUtil;
  27. import com.alipay.mychain.sdk.utils.RandomUtil;
  28. import com.alipay.mychain.sdk.vm.EVMOutput;
  29. import com.alipay.mychain.sdk.vm.EVMParameter;
  30. import java.io.IOException;
  31. import java.math.BigInteger;
  32. import java.net.InetSocketAddress;
  33. import java.util.ArrayList;
  34. import java.util.List;
  35. public class DemoSample {
  36. /**
  37. * contract code
  38. */
  39. private static String contractCodeString
  40. =
  41. "6080604052633b9aca00600055600060015534801561001d57600080fd5b5033600281905550610492806100346000396000f3006080604"
  42. +
  43. "05260043610610057576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063"
  44. +
  45. "af7c102c1461005c578063b2628df81461009d578063d4486019146100ec575b600080fd5b34801561006857600080fd5b5061008"
  46. +
  47. "76004803603810190808035906020019092919050505061013b565b6040518082815260200191505060405180910390f35b348015"
  48. +
  49. "6100a957600080fd5b506100d26004803603810190808035906020019092919080359060200190929190505050610158565b60405"
  50. +
  51. "1808215151515815260200191505060405180910390f35b3480156100f857600080fd5b5061012160048036038101908080359060"
  52. +
  53. "200190929190803590602001909291905050506102d8565b604051808215151515815260200191505060405180910390f35b60006"
  54. +
  55. "0036000838152602001908152602001600020549050919050565b6000600254331415156101d3576040517f08c379a00000000000"
  56. +
  57. "000000000000000000000000000000000000000000000081526004018080602001828103825260118152602001807f5065726d697"
  58. +
  59. "373696f6e2064656e69656400000000000000000000000000000081525060200191505060405180910390fd5b6000548260015401"
  60. +
  61. "131580156101ee57506001548260015401135b80156101fa5750600082135b151561026e576040517f08c379a0000000000000000"
  62. +
  63. "00000000000000000000000000000000000000000815260040180806020018281038252600e8152602001807f496e76616c696420"
  64. +
  65. "76616c75652100000000000000000000000000000000000081525060200191505060405180910390fd5b816003600085815260200"
  66. +
  67. "190815260200160002060008282540192505081905550816001600082825401925050819055508183337f31a52246bf8c995cecfd"
  68. +
  69. "d5404cf290ae6c2f4e174e888e4de4fd208137ec274d60405160405180910390a46001905092915050565b6000816003600033815"
  70. +
  71. "26020019081526020016000205412151515610365576040517f08c379a00000000000000000000000000000000000000000000000"
  72. +
  73. "000000000081526004018080602001828103825260138152602001807f62616c616e6365206e6f7420656e6f75676821000000000"
  74. +
  75. "0000000000000000081525060200191505060405180910390fd5b60008213801561037757506000548213155b15156103eb576040"
  76. +
  77. "517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600e815"
  78. +
  79. "2602001807f496e76616c69642076616c756521000000000000000000000000000000000000815250602001915050604051809103"
  80. +
  81. "90fd5b816003600033815260200190815260200160002060008282540392505081905550816003600085815260200190815260200"
  82. +
  83. "1600020600082825401925050819055508183337f97c0c2106db19ca3c64afdc86820cd157d60361f777bf0e5323254d6c9689550"
  84. +
  85. "60405160405180910390a460009050929150505600a165627a7a72305820371af9e83b0e49ca71634c470c75e504d08db9abbaf39"
  86. + "92f30434f8d7a7994d40029";
  87. private static byte[] contractCode = ByteUtils.hexStringToBytes(contractCodeString);
  88. /**
  89. * contract id
  90. */
  91. private static String testContractId = "CreditManager" + System.currentTimeMillis();
  92. /**
  93. * baas上创建的帐户名字
  94. */
  95. private static final String account = "sy_test";
  96. private static Identity userIdentity;
  97. private static Keypair userKeypair;
  98. /**
  99. * create account test
  100. */
  101. private static Identity testAccount1 = Utils.getIdentityByName("test_account_" + System.currentTimeMillis());
  102. /**
  103. * sdk client
  104. */
  105. private static MychainClient sdk;
  106. /**
  107. * client key password
  108. */
  109. private static String keyPassword = "Arb1585Stat"; //根据实际情况更新,申请证书时候指定的SSL密码
  110. /**
  111. * user password
  112. */
  113. private static String userPassword = "12345678"; //根据实际情况更新。申请证书时,创建账户的密码
  114. /**
  115. * host ip
  116. */
  117. private static String host = "106.14.211.115"; //根据实际情况更新,在BaaS平台,通过查看目标合约链"详情",在"区块浏览器"中查看"节点详情"可获取链节点的 IP地址 和 端口号。
  118. /**
  119. * server port
  120. */
  121. private static int port = 18130; //根据实际情况更新
  122. /**
  123. * trustCa password.
  124. */
  125. private static String trustStorePassword = "mychain";
  126. /**
  127. * mychain environment
  128. */
  129. private static ClientEnv env;
  130. /**
  131. * mychain is tee Chain
  132. */
  133. private static boolean isTeeChain = false;
  134. /**
  135. * tee chain publicKeys
  136. */
  137. private static List<byte[]> publicKeys = new ArrayList<byte[]>();
  138. /**
  139. * tee chain secretKey
  140. */
  141. private static String secretKey = "123456";
  142. private static void exit(String tag, String msg) {
  143. exit(String.format("%s error : %s ", tag, msg));
  144. }
  145. private static void exit(String msg) {
  146. System.out.println(msg);
  147. System.exit(0);
  148. }
  149. private static String getErrorMsg(int errorCode) {
  150. int minMychainSdkErrorCode = ErrorCode.SDK_INTERNAL_ERROR.getErrorCode();
  151. if (errorCode < minMychainSdkErrorCode) {
  152. return ErrorCode.valueOf(errorCode).getErrorDesc();
  153. } else {
  154. return ErrorCode.valueOf(errorCode).getErrorDesc();
  155. }
  156. }
  157. private static void initMychainEnv() throws IOException {
  158. // any user key for sign message
  159. String userPrivateKeyFile = "user.key";
  160. userIdentity = Utils.getIdentityByName(account); //根据实际情况更新'gushui03'为'user.key'对应的账户名(BaaS申请证书时创建的账户名)
  161. Pkcs8KeyOperator pkcs8KeyOperator = new Pkcs8KeyOperator();
  162. userKeypair = pkcs8KeyOperator.load(IOUtil.inputStreamToByte(DemoSample.class.getClassLoader()
  163. .getResourceAsStream(userPrivateKeyFile)), userPassword);
  164. // use publicKeys by tee
  165. if (isTeeChain) {
  166. Keypair keypair = new Pkcs8KeyOperator()
  167. .loadPubkey(
  168. IOUtil.inputStreamToByte(DemoSample.class.getClassLoader()
  169. .getResourceAsStream("test_seal_pubkey.pem")));
  170. byte[] publicKeyDer = keypair.getPubkeyEncoded(); //tee_rsa_public_key.pem 从BaaS下载获取
  171. publicKeys.add(publicKeyDer);
  172. }
  173. env = buildMychainEnv();
  174. ILogger logger = AbstractLoggerFactory.getInstance(DemoSample.class);
  175. env.setLogger(logger);
  176. }
  177. private static ClientEnv buildMychainEnv() throws IOException {
  178. InetSocketAddress inetSocketAddress = InetSocketAddress.createUnresolved(host, port);
  179. String keyFilePath = "client.key";
  180. String certFilePath = "client.crt";
  181. String trustStoreFilePath = "trustCa";
  182. // build ssl option
  183. ISslOption sslOption = new SslBytesOption.Builder()
  184. .keyBytes(IOUtil.inputStreamToByte(DemoSample.class.getClassLoader().getResourceAsStream(keyFilePath)))
  185. .certBytes(IOUtil.inputStreamToByte(DemoSample.class.getClassLoader()
  186. .getResourceAsStream(certFilePath)))
  187. .keyPassword(keyPassword)
  188. .trustStorePassword(trustStorePassword)
  189. .trustStoreBytes(
  190. IOUtil.inputStreamToByte(DemoSample.class.getClassLoader()
  191. .getResourceAsStream(trustStoreFilePath)))
  192. .build();
  193. List<InetSocketAddress> socketAddressArrayList = new ArrayList<InetSocketAddress>();
  194. socketAddressArrayList.add(inetSocketAddress);
  195. List<SignerBase> signerBaseList = new ArrayList<SignerBase>();
  196. SignerBase signerBase = MyCrypto.getInstance().createSigner(userKeypair);
  197. signerBaseList.add(signerBase);
  198. SignerOption signerOption = new SignerOption();
  199. signerOption.setSigners(signerBaseList);
  200. return ClientEnv.build(socketAddressArrayList, sslOption, signerOption);
  201. }
  202. private static void signRequest(AbstractTransactionRequest request) {
  203. // sign request
  204. long ts = sdk.getNetwork().getSystemTimestamp();
  205. request.setTxTimeNonce(ts, BaseFixedSizeUnsignedInteger.Fixed64BitUnsignedInteger
  206. .valueOf(RandomUtil.randomize(ts + request.getTransaction().hashCode())), true);
  207. request.complete();
  208. sdk.getConfidentialService().signRequest(env.getSignerOption().getSigners(), request);
  209. }
  210. private static void deployContract() {
  211. EVMParameter contractParameters = new EVMParameter();
  212. // build DeployContractRequest
  213. DeployContractRequest request = new DeployContractRequest(userIdentity,
  214. Utils.getIdentityByName(testContractId), contractCode, VMTypeEnum.EVM,
  215. contractParameters, BigInteger.ZERO);
  216. // set Gas limit
  217. // Make sure your account balance is greater than 50,000
  218. request.setTxGas(50000L);
  219. TransactionReceiptResponse deployContractResult;
  220. if (isTeeChain) {
  221. signRequest(request);
  222. // generate transaction key
  223. byte[] transactionKey = ConfidentialUtil.keyGenerate(secretKey,
  224. request.getTransaction().getHash().getValue());
  225. ConfidentialRequest confidentialRequest = new ConfidentialRequest(request, publicKeys, transactionKey);
  226. deployContractResult = sdk.getConfidentialService().confidentialRequest(confidentialRequest);
  227. } else {
  228. deployContractResult = sdk.getContractService().deployContract(request);
  229. }
  230. // deploy contract
  231. if (!deployContractResult.isSuccess()
  232. || deployContractResult.getTransactionReceipt().getResult() != 0) {
  233. exit("deployContract",
  234. getErrorMsg((int) deployContractResult.getTransactionReceipt().getResult()));
  235. } else {
  236. System.out.println("deploy contract success.");
  237. }
  238. }
  239. private static void issue() {
  240. EVMParameter parameters = new EVMParameter("Issue(identity,int256)");
  241. parameters.addIdentity(userIdentity);
  242. parameters.addUint(BigInteger.valueOf(100));
  243. // build CallContractRequest
  244. CallContractRequest request = new CallContractRequest(userIdentity,
  245. Utils.getIdentityByName(testContractId), parameters, BigInteger.ZERO, VMTypeEnum.EVM);
  246. // set Gas limit
  247. // Make sure your account balance is greater than 50,000
  248. request.setTxGas(Long.valueOf(50000));
  249. TransactionReceiptResponse callContractResult;
  250. if (isTeeChain) {
  251. signRequest(request);
  252. // generate transaction key
  253. byte[] transactionKey = ConfidentialUtil.keyGenerate(secretKey,
  254. request.getTransaction().getHash().getValue());
  255. ConfidentialRequest confidentialRequest = new ConfidentialRequest(request, publicKeys, transactionKey);
  256. callContractResult = sdk.getConfidentialService().confidentialRequest(confidentialRequest);
  257. } else {
  258. callContractResult = sdk.getContractService().callContract(request);
  259. }
  260. if (!callContractResult.isSuccess() || callContractResult.getTransactionReceipt().getResult() != 0) {
  261. exit("issue", getErrorMsg((int) callContractResult.getTransactionReceipt().getResult()));
  262. } else {
  263. System.out.println("issue success.");
  264. }
  265. }
  266. private static void transfer() {
  267. // contract parameters
  268. EVMParameter contractParameters = new EVMParameter("Transfer(identity,int256)");
  269. contractParameters.addIdentity(testAccount1);
  270. contractParameters.addUint(BigInteger.valueOf(50));
  271. CallContractRequest request = new CallContractRequest(userIdentity,
  272. Utils.getIdentityByName(testContractId), contractParameters, BigInteger.ZERO, VMTypeEnum.EVM);
  273. // set Gas limit
  274. // Make sure your account balance is greater than 50,000
  275. request.setTxGas(Long.valueOf(50000));
  276. TransactionReceiptResponse callContractResult;
  277. if (isTeeChain) {
  278. signRequest(request);
  279. // generate transaction key
  280. byte[] transactionKey = ConfidentialUtil.keyGenerate(secretKey,
  281. request.getTransaction().getHash().getValue());
  282. ConfidentialRequest confidentialRequest = new ConfidentialRequest(request, publicKeys, transactionKey);
  283. callContractResult = sdk.getConfidentialService().confidentialRequest(confidentialRequest);
  284. } else {
  285. callContractResult = sdk.getContractService().callContract(request);
  286. }
  287. if (!callContractResult.isSuccess() || callContractResult.getTransactionReceipt().getResult() != 0) {
  288. exit("transfer", getErrorMsg((int) callContractResult.getTransactionReceipt().getResult()));
  289. } else {
  290. System.out.println("transfer success.");
  291. }
  292. }
  293. private static BigInteger query(Identity account) {
  294. // contract parameters
  295. EVMParameter parameters = new EVMParameter("Query(identity)");
  296. parameters.addIdentity(account);
  297. // build call contract request
  298. CallContractRequest request = new CallContractRequest(userIdentity,
  299. Utils.getIdentityByName(testContractId), parameters, BigInteger.ZERO, VMTypeEnum.EVM);
  300. // set Gas limit
  301. // Make sure your account balance is greater than 50,000
  302. request.setTxGas(Long.valueOf(50000));
  303. TransactionReceiptResponse callContractResult;
  304. if (isTeeChain) {
  305. signRequest(request);
  306. // generate transaction key
  307. byte[] transactionKey = ConfidentialUtil.keyGenerate(secretKey,
  308. request.getTransaction().getHash().getValue());
  309. ConfidentialRequest confidentialRequest = new ConfidentialRequest(request, publicKeys, transactionKey);
  310. callContractResult = sdk.getConfidentialService().confidentialRequest(confidentialRequest);
  311. } else {
  312. callContractResult = sdk.getContractService().callContract(request);
  313. }
  314. if (!callContractResult.isSuccess() || callContractResult.getTransactionReceipt().getResult() != 0) {
  315. exit("query", getErrorMsg((int) callContractResult.getTransactionReceipt().getResult()));
  316. }
  317. byte[] output = null;
  318. if (isTeeChain) {
  319. output = ConfidentialUtil.decrypt(secretKey, callContractResult.getTransactionReceipt()
  320. .getOutput(), request.getTransaction().getHash().hexStrValue());
  321. } else {
  322. output = callContractResult.getTransactionReceipt().getOutput();
  323. }
  324. if (output == null) {
  325. exit("decrypt tee", "decrypt tee output failed");
  326. return BigInteger.ZERO;
  327. }
  328. // decode return values
  329. EVMOutput contractReturnValues = new EVMOutput(ByteUtils.toHexString(output));
  330. return contractReturnValues.getUint();
  331. }
  332. private static void expect(BigInteger balance, BigInteger expectBalance) {
  333. if (balance.compareTo(expectBalance) != 0) {
  334. exit("expect", "the account value is not expected.");
  335. } else {
  336. System.out.println("check account balance success.");
  337. }
  338. }
  339. private static void initSdk() {
  340. sdk = new MychainClient();
  341. boolean initResult = sdk.init(env);
  342. if (!initResult) {
  343. exit("initSdk", "sdk init failed.");
  344. }
  345. }
  346. public static void main(String[] args) throws Exception {
  347. //step 1:init mychain env.
  348. initMychainEnv();
  349. //step 2: init sdk client
  350. initSdk();
  351. QueryAccountResponse queryAccountResponse = sdk.getQueryService()
  352. .queryAccount(Utils.getIdentityByName("test11133"));
  353. //step 3 : deploy a contract using useridentity.
  354. deployContract();
  355. //step 4 issue 100 assets to testAccount1.
  356. issue();
  357. //step 5 : transfer 50 assets from useridentity to testAccount1
  358. transfer();
  359. //step 6 : query testAccount1 whose balance should be 50.
  360. BigInteger balance = query(testAccount1);
  361. //step 7 : compare to expect balance.
  362. expect(balance, BigInteger.valueOf(50));
  363. //step 8 : sdk shut down
  364. sdk.shutDown();
  365. }
  366. }