本文参考了fabric官网的nodejs版本:https://hyperledger-fabric.readthedocs.io/en/latest/write_first_app.html
使用应用时,网络中必须要有CA,因为我们需要用CA来注册管理员和app用户,然后再以他们的身份去调用智能合约,如以test-network为例,启动时必须使用如下命令:
./network.sh up createChannel -c mychannel -ca
链码这里仍然使用上篇博客所编写的atcc,在编写应用之前,我已经把他们提交到了网络中。
然后创建一个Maven项目,这里我创建的是一个springboot项目,并将Fabric相关操作封装在Dao层中。
1.引入必要的依赖
这里包括springboot的依赖和fabric的依赖。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hyperledger.fabric/fabric-gateway-java -->
<dependency>
<groupId>org.hyperledger.fabric</groupId>
<artifactId>fabric-gateway-java</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.用户相关的Dao层
首先定义相关的接口,这里包括一个管理员创建接口和一个根据用户名创建用户接口,用户创建相关的操作是应用和组织的CA进行交互的,不会涉及到链码,即只是该组织本身进行,不会有其他组织参与,这个过程完成之后,会产生该组织的一个操作者的身份来代表这个组织去调用链码。这个过程会在组织的CA数据库中留下记录,所以如果要重启项目,务必要删除这一步生成的wallet文件夹,否则会产生错误,因为test-network中新启动的CA会把数据库也清除,当然如果是自己启动并且持久化过的CA应该就不用做这一步了。
/** 创建相关的用户
* Create by zekdot on 2021/9/21.
*/
public interface UserDao {
// 创建管理员用户
boolean createAdmin() throws Exception;
// 创建app用户
boolean createUser(String username) throws Exception;
}
在实现中,admin的创建用的是enroll这个词,普通用户的创建用的是register这个词,我查到StackOverflow中有一个回答:https://stackoverflow.com/questions/55990837/what-is-the-meaning-of-register-and-enroll-in-the-context-of-fabric-ca,大意是register由CA管理员完成,只需要给一个身份赋予用户名和密码以及相关的属性,在CA数据库进行记录,就算完成了registration,这个过程没有证书被生成,而enroll则涉及到证书以及相关的公私钥对的生成。
两个操作都涉及链接到Org1的CA,这里我把连接返回客户端的方法进行了封装:
private HFCAClient getCaclient() throws Exception {
// Create a CA client for interacting with the CA.
Properties props = new