当前位置:   article > 正文

FISCO BCOS 搭建区块链,在SpringBoot中调用合约_srpingboot项目搭建区块链

srpingboot项目搭建区块链

一、搭建区块链

使用的是FISCO BCOS 和 WeBASE-Front来搭建区块链,详细教程:

https://blog.csdn.net/yueyue763184/article/details/128924144?spm=1001.2014.3001.5501

搭建好能达到下图效果即可:

二、部署智能合约与导出java文件、SDK证书下载

1.创建测试用户,导出pem文件

点击“测试用户”,即可“新增用户”。

点击“导出”,选择.pem文件。

2.编译部署智能合约,导出java文件和SDK证书下载

在“合约IDE”中准备智能合约,新建合约文件,合约名称是Asset。

  1. pragma solidity ^0.4.25;
  2. contract Asset {
  3. address public issuer;
  4. mapping (address => uint) public balances;
  5. event Sent(address from, address to, uint amount);
  6. constructor() {
  7. issuer = msg.sender;
  8. }
  9. function issue(address receiver, uint amount) public {
  10. if (msg.sender != issuer) return;
  11. balances[receiver] += amount;
  12. }
  13. function send(address receiver, uint amount) public {
  14. if (balances[msg.sender] < amount) return;
  15. balances[msg.sender] -= amount;
  16. balances[receiver] += amount;
  17. emit Sent(msg.sender, receiver, amount);
  18. }
  19. }

 合约IDE会自动保存的,点击“编译”、“部署”后即可得到合约地址contractAddress。

点击“导出java文件”,一般命名与合约名称相同为Asset;

点击“SDK证书下载”; 

得到的文件如下:

三、在SpringBoot项目中调用智能合约

1.首先创建SpringBoot项目

2.在pom文件中导入相关依赖

  1. <!-- web -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <!-- test -->
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-test</artifactId>
  10. <scope>test</scope>
  11. </dependency>
  12. <!-- fisco bcos -->
  13. <dependency>
  14. <groupId>org.fisco-bcos.java-sdk</groupId>
  15. <artifactId>fisco-bcos-java-sdk</artifactId>
  16. <version>2.9.1</version>
  17. </dependency>

3.将下载的相关文件导入对应的文件目录(sdk要先解压)

4.在application.yaml配置文件编写fisco的配置

注意:要将路径和合约地址换成自己的

  1. fisco:
  2. nodeList: 192.168.119.138:20201
  3. groupId: 1
  4. certPath: src\main\resources\sdk
  5. contractAddress:
  6. # Asset合约地址(一定要加引号 不然注解@Value会把按照16进制数字进行转换赋值)
  7. asset: "0xc6053e4f71cdcf14e31cc1031263cee4e1ac7768"
  8. # 测试用户地址
  9. account:
  10. # 测试用户秘钥地址
  11. accountAddress: src\main\resources\account
  12. # 测试用户文件地址
  13. accountFilePath: src\main\resources\account\buliangshuai_key_0x3a456344e952d0275e5e4af4766abb450d3b45ac.pem

说明: 

fisco.nodeList:区块链节点的ip和端口;
fisco.groupId:组ID;
fisco.certPath:证书保存目录;
fisco.contractAddress.asset:合约地址;
fisco.contractAddress.account.accountAddress:测试用户地址;
fisco.contractAddress.account.accountFilePath:测试用户的pem文件地址;

5.编写sdk访问合约方法

在client包中创建2个类,一个是环境配置类ApplicationContext

  1. package com.fisco.bcos.asset.client;
  2. import org.fisco.bcos.sdk.BcosSDK;
  3. import org.fisco.bcos.sdk.client.Client;
  4. import org.fisco.bcos.sdk.config.ConfigOption;
  5. import org.fisco.bcos.sdk.config.exceptions.ConfigException;
  6. import org.fisco.bcos.sdk.config.model.ConfigProperty;
  7. import org.fisco.bcos.sdk.crypto.CryptoSuite;
  8. import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair;
  9. import org.springframework.beans.factory.annotation.Value;
  10. import org.springframework.context.annotation.Bean;
  11. import org.springframework.context.annotation.Configuration;
  12. import java.util.Arrays;
  13. import java.util.HashMap;
  14. import java.util.List;
  15. import java.util.Map;
  16. /**
  17. * @Description: 配置类
  18. */
  19. @Configuration
  20. public class ApplicationContext {
  21. @Value("${fisco.nodeList}")
  22. private String nodeLists;
  23. @Value("${fisco.groupId}")
  24. private Integer groupId;
  25. @Value("${fisco.certPath}")
  26. private String certPath;
  27. @Value("${fisco.account.accountFilePath}")
  28. private String accountFilePath;
  29. @Bean(name = "configProperty")
  30. public ConfigProperty defaultConfigProperty() {
  31. ConfigProperty property = new ConfigProperty();
  32. // 配置cryptoMaterial
  33. Map<String, Object> cryptoMaterialMap = new HashMap<>();
  34. cryptoMaterialMap.put("certPath", certPath);
  35. property.setCryptoMaterial(cryptoMaterialMap);
  36. // 配置network
  37. Map<String, Object> networkMap = new HashMap<>();
  38. String[] split = nodeLists.split(",");
  39. List<String> nodeList = Arrays.asList(split);
  40. networkMap.put("peers", nodeList);
  41. property.setNetwork(networkMap);
  42. // 配置account
  43. Map<String, Object> accountMap = new HashMap<>();
  44. accountMap.put("keyStoreDir", "account");
  45. accountMap.put("accountAddress", "");
  46. accountMap.put("accountFileFormat", "pem");
  47. accountMap.put("password", "");
  48. accountMap.put("accountFilePath", accountFilePath);
  49. property.setAccount(accountMap);
  50. //配置 threadPool
  51. Map<String, Object> threadPoolMap = new HashMap<>();
  52. threadPoolMap.put("channelProcessorThreadSize", "16");
  53. threadPoolMap.put("receiptProcessorThreadSize", "16");
  54. threadPoolMap.put("maxBlockingQueueSize", "102400");
  55. property.setThreadPool(threadPoolMap);
  56. return property;
  57. }
  58. @Bean(name = "configOption")
  59. public ConfigOption defaultConfigOption(ConfigProperty configProperty) throws ConfigException {
  60. return new ConfigOption(configProperty);
  61. }
  62. @Bean(name = "bcosSDK")
  63. public BcosSDK bcosSDK(ConfigOption configOption) {
  64. return new BcosSDK(configOption);
  65. }
  66. @Bean(name = "client")
  67. public Client getClient(BcosSDK bcosSDK) {
  68. // 为群组初始化client
  69. Client client = bcosSDK.getClient(groupId);
  70. return client;
  71. }
  72. @Bean
  73. public CryptoKeyPair getCryptoKeyPair(Client client) {
  74. // 如果有密钥文件 那么每次读取的就不再是随机的
  75. CryptoSuite cryptoSuite = client.getCryptoSuite();
  76. CryptoKeyPair cryptoKeyPair = cryptoSuite.getCryptoKeyPair();
  77. return cryptoKeyPair;
  78. }
  79. }

另一个是合约客户端类AssetClient

  1. package com.fisco.bcos.asset.client;
  2. import com.fisco.bcos.asset.contract.Asset;
  3. import org.fisco.bcos.sdk.BcosSDK;
  4. import org.fisco.bcos.sdk.client.Client;
  5. import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair;
  6. import org.fisco.bcos.sdk.model.TransactionReceipt;
  7. import org.fisco.bcos.sdk.model.callback.TransactionCallback;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.beans.factory.annotation.Value;
  10. import org.springframework.stereotype.Component;
  11. import java.math.BigInteger;
  12. @Component
  13. public class AssetClient {
  14. @Autowired
  15. private BcosSDK bcosSDK;
  16. @Autowired
  17. private Client client;
  18. @Autowired
  19. private CryptoKeyPair cryptoKeyPair;
  20. @Value("${fisco.contractAddress.asset}")
  21. private String contractAddress;
  22. /**
  23. * 发布资产(条件:当前用户是Asset合约发布者)
  24. * @param receiver 接收者地址
  25. * @param amount 资产数量
  26. */
  27. public void issueAsset(String receiver, BigInteger amount) {
  28. Asset asset = Asset.load(contractAddress, client, cryptoKeyPair);
  29. asset.issue(receiver, amount, new CallbackResponse());
  30. }
  31. /**
  32. * 发送资产(条件:发送者的账号Balance必须大于等于amount)
  33. * @param receiver 接收者地址
  34. * @param amount 资产数量
  35. */
  36. public void sendAsset(String receiver, BigInteger amount) {
  37. Asset asset = Asset.load(contractAddress, client, cryptoKeyPair);
  38. asset.send(receiver, amount, new CallbackResponse());
  39. }
  40. private class CallbackResponse extends TransactionCallback {
  41. @Override
  42. public void onResponse(TransactionReceipt transactionReceipt) {
  43. System.out.println("回调结果:");
  44. System.out.println(transactionReceipt.getContractAddress());
  45. System.out.println(transactionReceipt.getFrom());
  46. System.out.println(transactionReceipt.getGasUsed());
  47. System.out.println(transactionReceipt.getRemainGas());
  48. System.out.println(transactionReceipt.getStatus());
  49. System.out.println(transactionReceipt.getMessage());
  50. System.out.println(transactionReceipt.getStatusMsg());
  51. }
  52. }
  53. }

6.编写测试类调用智能合约函数

首先编写测试类AssetClientTest

  1. package com.fisco.bcos.asset.client;
  2. import com.fisco.bcos.asset.AssetDemo1Application;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  8. import java.math.BigInteger;
  9. @RunWith(SpringJUnit4ClassRunner.class)
  10. @SpringBootTest(classes = AssetDemo1Application.class)
  11. public class AssetClientTest {
  12. @Autowired
  13. private AssetClient assetClient;
  14. @Test
  15. public void testIssueAsset() throws InterruptedException {
  16. String receiver = "0xc6053e4f71cdcf14e31cc1031263cee4e1ac7768";
  17. BigInteger amount = new BigInteger("10000");
  18. assetClient.issueAsset(receiver, amount);
  19. Thread.sleep(5000);
  20. System.out.println("发布成功!");
  21. }
  22. @Test
  23. public void testSendAsset() throws InterruptedException {
  24. String receiver = "0xc6053e4f71cdcf14e31cc1031263cee4e1ac7768";
  25. BigInteger amount = new BigInteger("50000");
  26. assetClient.sendAsset(receiver, amount);
  27. Thread.sleep(5000);
  28. System.out.println("发送成功!");
  29. }
  30. }

测试的步骤:

           1)先后执行testIssueAssettestSendAsset测试方法,该测试要保证服务器的20200、20201端口是开放的,命令如下:

firewall-cmd --zone=public --add-port=20201/tcp --permanent # 开放端口

firewall-cmd --zone=public --remove-port=20201/tcp --permanent #关闭端口

firewall-cmd --reload   # 配置立即生效

firewall-cmd --zone=public --list-ports    # 查看防火墙所有开放的端口

           2)执行成功后,在节点控制台的“合约列表”中找到对应的合约,点击“合约调用”,选择balances方法;

 结果如下:

以上就是在Fisco区块链上部署智能合约,并通过Java SDK调用智能合约函数的示例.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/953490
推荐阅读
相关标签
  

闽ICP备14008679号