Spring Boot整合区块链—区块链服务开发实例

Posted 雨云21

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot整合区块链—区块链服务开发实例相关的知识,希望对你有一定的参考价值。

本实例主要是将企业信息添加进区块链,然后实现对企业信息进行查询溯源,对区块链有新增、查询、修改、删除、查看历史等功能。

1、准备一个bsn-springboot项目

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.yuyun</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot</name>
    <description>springboot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2、引入jar包

下载: https://yuyunyaohui.lanzoul.com/iwnMXxuxm2f 密码:hk9i

项目下新建一个lib目录,将jar包放入

然后再pom.xml文件引入该jar包

<dependency>
    <groupId>com.example.javacc</groupId>
    <artifactId>bsn-sdk-java</artifactId>
    <version>1.0-SNAPSHOT</version>
    <scope>system</scope>
    <systemPath>$pom.basedir/lib/bsn-sdk-java-jar-with-dependencies.jar</systemPath>
</dependency>

3、区块链配置

方法一:新建config.json文件

在resources目录下新建个config目录,再在其中新建config.json文件,格式如下:


  "userPrivateKey": "",
  "bsnPublicKey": "",
  "appCode": "",
  "userCode": "",
  "nodeApi": "",
  "mspPath": ""

其中的内容,打开区块链官网我参与的服务

点击下载秘钥,下载解压后的文件,userAppCert目录中的两个文件,一个是私钥,一个是公钥,分别对应config.json中的userPrivateKey和bsnPublicKey

将两个文件里面的所有内容复制了放入,例如:


  "userPrivateKey": "-----BEGIN PRIVATE KEY-----\\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgVbS8svrC3sdFgIFW\\nUoLfczfjCjq0z7fGTSFfqMkjssChRANCAARXn4a1tA3PB8+wx9UgU0GDfGBG7BXZ\\nENL5GN3vYXqpcbCtvxAtINSK02KcQ1a6jAASy79T0ax9KfQDjzGVFN9K\\n-----END PRIVATE KEY-----",
  "bsnPublicKey": "-----BEGIN PUBLIC KEY-----\\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV5+GtbQNzwfPsMfVIFNBg3xgRuwV\\n2RDS+Rjd72F6qXGwrb8QLSDUitNinENWuowAEsu/U9GsfSn0A48xlRTfSg==\\n-----END PUBLIC KEY-----",
  "appCode": "app008809d6356825a4c249be16572723c6225",
  "userCode": "USER0001202112061433104102226",
  "nodeApi": "http://52.83.209.158:17502",
  "mspPath": ""

方法二:直接将userAppCert目录中的两个文件放进resources目录下

4、初始化config方法

如果区块链配置采用方法一,初始化config的代码如下:

public void initConfig() 
    String filePath = "config/config.json";
    Config config = Config.buildByConfigJson(filePath);
    config.initConfig(config);

如果采用方法二,初始化config的代码如下:

public void initConfig() throws IOException 
    Config config = new Config();
    config.setAppCode("app008809d6356825a4c249be16572723c6225");
    config.setUserCode("USER0001202112061433104102226");
    config.setApi("http://52.83.209.158:17502");
    config.setPrk(Common.readFile("cert/private_key.pem"));
    config.setPuk(Common.readFile("cert/public_key.pem"));
    config.setMspDir("");
    config.initConfig(config);

本实例采用方法一

5、具体实现

新建一个Service层代码,具体如下:

package com.yuyun.service;

import com.yuyun.dto.BsnHistoryDTO;
import com.yuyun.dto.CompanyDTO;

import java.io.IOException;
import java.util.List;

/**
 * @author hyh
 */
public interface FabricBsnService 

    /**
     * 保存(添加or修改)
     *
     * @param key  键值
     * @param body 内容
     * @return 成功 true
     * @return Boolean
     */
    Boolean save(String key, String body);

    /**
     * 查询
     *
     * @param key 键值
     * @return 结果
     */
    CompanyDTO query(String key);

    /**
     * 历史查询
     *
     * @param key 键值
     * @return 解密后的结果
     * @throws IOException 异常
     */
    List<BsnHistoryDTO> getHistory(String key) throws IOException;

    /**
     * 删除
     *
     * @param key 键值
     * @return 成功 true
     * @return Boolean
     */
    Boolean delete(String key);

新建Service类的实现

package com.yuyun.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bsnbase.sdk.client.fabric.FabricClient;
import com.bsnbase.sdk.entity.config.Config;
import com.bsnbase.sdk.entity.req.fabric.ReqKeyEscrow;
import com.bsnbase.sdk.entity.res.fabric.ResKeyEscrow;
import com.yuyun.dto.BsnHistoryDTO;
import com.yuyun.dto.CompanyDTO;
import com.yuyun.service.FabricBsnService;
import com.yuyun.utils.Base64Utils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author hyh
 */
@Log4j2
@Service
public class FabricBsnServiceImpl implements FabricBsnService 

    /**
     * 初始化config
     */
    public void initConfig() 
        String filePath = "config/config.json";
        Config config = Config.buildByConfigJson(filePath);
        config.initConfig(config);
    

    public String reqChainCode(String key, String funcName, String body) 
        try 
            initConfig();
            ReqKeyEscrow keyEscrow = new ReqKeyEscrow();

            String[] args;
            if (StringUtils.isNotBlank(body)) 
                args = new String[]key, body;
             else 
                args = new String[]key;
            

            keyEscrow.setArgs(args);
            keyEscrow.setFuncName(funcName);
            //链码部署名称,在我参与的服务信息中可以找到
            keyEscrow.setChainCode("cc_app0001");

            keyEscrow.setTransientData(new HashMap<>());
            ResKeyEscrow resKeyEscrow = FabricClient.reqChainCode(keyEscrow);
            if (200 == resKeyEscrow.getCcRes().getCcCode()) 
                String str = resKeyEscrow.getCcRes().getCcData();
                if ("null".equals(str)) 
                    return null;
                
                return str;
            
         catch (Exception e) 
            throw new RuntimeException("区块链访问失败:" + e.getMessage());
        
        return null;
    

    @Override
    public Boolean save(String key, String body) 
        log.info("key:" + key);
        String s = reqChainCode(key, "Set", body);
        return StringUtils.isNotBlank(s);
    

    @Override
    public CompanyDTO query(String key) 
        String queryStr = reqChainCode(key, "Query", null);
        if (StringUtils.isBlank(queryStr)) 
            return null;
        
        JSONObject jsonObject = JSONObject.parseObject(queryStr);

        return jsonObject.toJavaObject(CompanyDTO.class);
    

    @Override
    public List<BsnHistoryDTO> getHistory(String key) throws IOException 
        String historyStr = reqChainCode(key, "History", null);
        if (StringUtils.isBlank(historyStr)) 
            return new ArrayList<>();
        
        JSONArray jsonArray = JSONArray.parseArray(historyStr);

        List<BsnHistoryDTO> bsnHistoryDTOList = jsonArray.toJavaList(BsnHistoryDTO.class);
        for (BsnHistoryDTO b : bsnHistoryDTOList) 
            if (null != b) 
                String value = Base64Utils.Base64Decode(b.getValue().getBytes());
                if (StringUtils.isNotBlank(value)) 
                    JSONObject jsonObject = JSONObject.parseObject(value);
                    CompanyDTO companyDTO = jsonObject.toJavaObject(CompanyDTO.class);
                    b.setCompanyDTO(companyDTO);
                
                b.setValue("");
            
        

        return bsnHistoryDTOList;
    

    @Override
    public Boolean delete(String key) 
        String s = reqChainCode(key, "Delete", null);
        return "success".equals(s);
    

新建Controller层

package com.yuyun.controller;

import com.yuyun.dto.BsnHistoryDTO;
import com.yuyun.dto.CompanyDTO;
import com.yuyun.service.FabricBsnService;
import com.yuyun.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * @author hyh
 */
@RestController
@RequestMapping("fabricBsn")
@Api(tags = "区块链")
public class FabricBsnController 

    @Autowired
    private FabricBsnService fabricBsnService;

    @GetMapping("history/key")
    @ApiOperation("历史记录")
    public Result<List<BsnHistoryDTO>> history(@PathVariable("key") String key) throws IOException 
        List<BsnHistoryDTO> bsnHistoryDTOList = fabricBsnService.getHistory(key);

        return new Result<List<BsnHistoryDTO>>().success(bsnHistoryDTOList);
    

    @GetMapping("query/key")
    @ApiOperation("信息")
    public Result<CompanyDTO> get(@PathVariable("key") String key) 

        CompanyDTO data = fabricBsnService.query(key);

        return new Result<CompanyDTO>().success(data);
    

    @DeleteMapping("key")
    @ApiOperation("删除")
    public Result<Object> delete(@PathVariable("key") String key) 

        return new Result<>().ok(fabricBsnService.delete(key));
    

在企业管理中调用区块链的方法

先引入,再调用

@Autowiredprivate FabricBsnService fabricBsnService;
  • 新增信息

    fabricBsnService.save("company_" + companyDTO.getId(), JSON.toJSONString(companyDTO));
    
  • 修改信息

    fabricBsnService.save("company_" + companyDTO.getId(), JSON.toJSONString(companyDTO));
    
  • 删除信息

    fabricBsnService.delete("company_" + id);
    

6、运行效果

(1)添加企业信息

(2)查看企业信息

(3)查看区块链信息

(4)修改企业信息

(5)再次查看区块链信息

基于Spring的Fabric区块链Gateway,简化区块链开发

区块链SBaaS引关注 苏宁金融入选区块链金融科技领先100强

区块链系统,探讨区块链系统的奥秘

区块链干货:最佳的智能合约开发工具总结

技术实操:用GoLang语言来构建区块链

企业动态|数信区块链成为国家级联盟链(BSN)合格开发者