原文地址:Hyperledger fabric-sdk-java Basics Tutorial

This quick tutorial is for all Java developers, who started to look into Hyperledger Fabric platform (https://hyperledger.org/) and would like to use fabric-sdk-java for their projects.

When learning a new technology I always try to search for some minimal working example I can get up and running in my environment. This is a starting point for me to further play around with APIs, debug and get better handle of the framework.

There is a lot of good documentation and examples available on Hyperledger sites ( http://hyperledger-fabric.readthedocs.io and https://github.com/hyperledger/fabric-samples.git). What I have been missing is some minimal working project for Java developers using fabric-sdk-java. This tutorial tries to serve this purpose.

This tutorial assumes you are familiar with basics of Hyperledger fabric. If not, then I suggest you to look around and especially go through http://hyperledger-fabric.readthedocs.io/en/release/build_network.htmland http://hyperledger-fabric.readthedocs.io/en/release/write_first_app.html .

If you were successfully able to get through these two tutorials, then we are ready to have a look how to use fabric-sdk-java to do the same. We will use the fabcar example from https://github.com/hyperledger/fabric-samples.git to setup the network.

Tips:

  1. fabric-samples/scripts/fabric-preload.sh script will download the docker images and tag them for you.
  2. fabric-samples/fabcar/startFabric.sh can be used to start the fabcar network
  3. In case you are experiencing issues you might want to do some docker cleanup
# !!! THIS WILL REMOVE ALL YOUR DOCKER CONTAINERS AND IMAGES !!!
# remove all containers
$ docker rm $(docker ps -qa)
# remove all mages
$ docker rmi --force $(docker images -qa)
# prune networks
$ docker network prune

Enough talking and let’s get something up and running….

Clone the example code from here into demo directory

git clone https://github.com/lkolisko/scratch.git tutorial

and navigate to tutorial/hyperledger/fabric-sdk-java-scratch.

The project itself has just 4 three important files.

  1. pom.xml —maven build file including dependency to fabric-sdk-java artifact. org.hyperledger.fabric-sdk-java: fabric-sdk-java:1.0.1 . There might be a new version available at the time you are reading this. You must ensure you fabric-sdk-java version is the same release series as the images used in fabric-samples. Otherwise you might run into incompatibility issues at protobuf leves or APIs.
  2. src/main/java/lkolisko/hyperledger/example/AppUser.java — this is minimal implementation of the User interface. The sdk itself does not provide implementation, therefore we must do here ourselves.
  3. src/main/java/lkolisko/hyperledger/example/HFJavaSDKBasicExample.java — this is the main class and will further talk about details bellow.
  4. src/main/resources/log4j.xml — log4j configuration. I highly suggest to set the root logger to debug. You will be able to see all the information about communication between client the other components of the fabric network.

Enrolling admin

We need to create fabric-ca client to be able to register and enroll users. To be precise it might not be necessary, as you already enrolled admin and user using fabric-ca-client cli or following he fabcar example (the crypto material is available in fabric-samples/fabcar/hfc-key-store and can be loaded) . But lets start from scratch and learn how to do that in Java.

CryptoSuite cryptoSuite = CryptoSuite.Factory.getCryptoSuite();
HFCAClient caClient = HFCAClient.createNewInstance(“grpc://localhost:7054”, null);
caClient.setCryptoSuite(cryptoSuite);

The grpc://localhost:7054 is the endpoint where fabric-ca server listens. You can check that running docker ps . The properties can be left empty or null for now.

Enroll Admin

To communicate with fabric components we have to have key pair and a certificate signed by the fabric-ca. We can either use the crypto material generated in fabric-samples/fabcar/hfc-key-store. For the purpose of learning the API we will let the fabric-ca client generate the crypto material for us.

Enrollment adminEnrollment = caClient.enroll("admin", "adminpw");
AppUser admin = new AppUser("admin","org1", "Org1MSP", adminEnrollment);

The ca client will generate the key pair and CSR (certificate signature request) using the CryptoSuite and send it to the fabric-ca.

fabri-ca will

  1. authenticate admin using basic authentication
  2. perform verification e.g. check if max enrollment count for the account has not been reached
  3. sign the certificate
  4. store the certificate (along with its serial number, aki and other information)
  5. send it back to client

The Enrollment object contains private key and the certificate. The sample stores the object using Java Serialization. This is definitely a bad practice and is used just for the purpose of keeping the example simple.

Register and Enroll user

In the step two we are going to register a new user and enroll the user.

RegistrationRequest rr = new RegistrationRequest("hfuser", "org1");
String userSecret = caClient.register(rr, registrar);
Enrollment userEnrollment = caClient.enroll("hfuser", userSecret);
AppUser appUser = new AppUser("hfuser", "org1","Org1MSP", userEnrollment);

To do that RegistrationRequest object with userId and affiliation has to be created. To understand what affiliation means, please refer here http://hyperledger-fabric-ca.readthedocs.io/en/latest/users-guide.html .

With the RegistrationRequest we will call fabri-ca using registrar (admin) . The fabric-ca will answer with secret (password) we will use for enrollment of the user. This is the same as we did for the admin in the previous step.

At this moment we have admin — private key and signed certificate and user with private key and signed certificate. This opens as the door to talk to fabric itself.

Initialize HF Client

We will create client instance using HFClient factory and set the default crypto suite. Next we set use context. This will be the account under which we are going to talk to Hyperledger Fabric and its private key will be used to sign the request.

CryptoSuite cryptoSuite = CryptoSuite.Factory.getCryptoSuite();
HFClient client = HFClient.createNewInstance();
client.setCryptoSuite(cryptoSuite);
client.setUserContext(appUser);

Initialize Channel object

The interesting stuff happens in channel. Therefore we have to get the Channel object. For this we need peer and orderer. The orderer is listening on 7050 and peer on 7051 and eventhub on 7053 ports of the localhost. We are not using TLS now so set the grpc protol. The orderer and peer names do not have to match the fqdn you see in the docker ps. The channel name for the sample is mychannel. After channel.initialize() we are ready to go.

Peer peer = client.newPeer("peer", "grpc://localhost:7051"); EventHub eventHub = client.newEventHub("eventhub", "grpc://localhost:7053");
Orderer orderer = client.newOrderer("orderer", "grpc://localhost:7050");
Channel channel = client.newChannel("mychannel");
channel.addPeer(peer);
channel.addEventHub(eventHub);
channel.addOrderer(orderer);
channel.initialize();

Invoking chain code

We will invoke simple query on the fabric chain code. To do so QueryByChaincodeRequest has to be set with chain code id fabcar and function we would like to invoke queryAllCars. Potentially you would like to pass arguments using setArgs and version using setVersion.

QueryByChaincodeRequest qpr = client.newQueryProposalRequest();
ChaincodeID fabcarCCId = ChaincodeID.newBuilder().setName("fabcar").build();
qpr.setChaincodeID(fabcarCCId);
qpr.setFcn("queryAllCars");
Collection<ProposalResponse> res = channel.queryByChaincode(qpr);
for (ProposalResponse pres : res) {
String stringResponse = new String(pres.getChaincodeActionResponsePayload());
log.info(stringResponse);
}

Once we are set, let submit the query request and enjoy the response. The response is protobuf backed object, therefore we just rely on simple toString here for simplicity.

Please do not consider the code above as a best practice to follow. We are ignoring handling invalid responses, exceptions, storing credentials using serialization and dozen of other bad practices. The purpose of the sample is to get something working with minimal effort and get you on track.

To study further I highly recommend checking

Happy coding !

— Lukas

Hyperledger fabric-sdk-java Basics Tutorial(转)的更多相关文章

  1. HyperLedger/Fabric SDK使用Docker容器镜像快速部署上线

    HyperLedger/Fabric SDK Docker Image 该项目在github上的地址是:https://github.com/aberic/fabric-sdk-container ( ...

  2. 区块链:基于Hyperledger Fabric的 java 客户端开发(java sdk /java api server/java event server)

    fabric针对java 开发的部分支持不是很友好.基于目前较为稳定的fabric 1.4版本,我们封装了一个java sdk,apiserver,eventServer 封装java sdk的主要目 ...

  3. hyperledger fabric 中java chaincode 支持离线打包

    联盟链由于其本身的特性,目前应用在一些大型国有企业银行比较多.出于安全考虑,这些企业一般会隔离外网环境.所以在实际生产需求中可能存在需要在一个离线的环境中打包安装chaincode的情况. 本文基于这 ...

  4. Hyperledger Fabric SDK use case 1

    ///////////////////////////////////////////////////////////////////////:End2endAndBackAgainIT 1.Crea ...

  5. hyperledger fabric超级账本java sdk样例e2e代码流程分析

     一  checkConfig  Before     1.1  private static final TestConfig testConfig = TestConfig.getConfig() ...

  6. Hyperledger Fabric 1.0 从零开始(十二)——fabric-sdk-java应用【补充】

    在 Hyperledger Fabric 1.0 从零开始(十二)--fabric-sdk-java应用 中我已经把官方sdk具体改良办法,即使用办法发出来了,所有的类及文件都是完整的,在文章的结尾也 ...

  7. Hyperledger Fabric 1.0 从零开始(十二)——fabric-sdk-java应用

    Hyperledger Fabric 1.0 从零开始(十)--智能合约 Hyperledger Fabric 1.0 从零开始(十一)--CouchDB 上述两章,最近网上各路大神文章云集,方案多多 ...

  8. 使用Node.JS访问Hyperledger Fabric的gRPC服务

    在即将正式发布的Hyperledger Fabric SDK 1.0中,Hyperledger Fabric通过gRPC提供服务接口以取代现有的REST API.本文介绍了如何使用Node.JS访问H ...

  9. Hyperledger Fabric 2.x Java区块链应用

    一.说明 在上一篇文章中 <Hyperledger Fabric 2.x 自定义智能合约> 分享了智能合约的安装并使用 cli 客户端进行合约的调用:本文将使用 Java 代码基于 fab ...

随机推荐

  1. 接口测试工具-Jmeter使用笔记(六:从文本读取参数)

    使用场景:测试一个接口并发处理数据的能力,并且每次请求传入的参数都要不同. 解决方法--- CSV Data Set Config 列举一个实例,步骤中会侧重读取参数操作的说明,其他有疑问的步骤请查阅 ...

  2. python 关于 input

    name = input("请输入你的姓名:") print(name) 解释:input表示输入,当你输入一个名字的时候, 它打印出来的东西,也就是你输入的东西, 结果: 请输入 ...

  3. [js]js中函数传参判断

    1,通过|| function fun(x,y){ x=x||0; y=y||1; alert(x+y); } fun(); 2.通过undefined对比 function fun(x,y){ if ...

  4. MATLAB变量

    序言 在Matlab中,变量名由A~Z.a~z.数字和下划线组成,且变量的第一个字符必须是字母. 尽管变量名可以是任意长度, 但是Matlab只识别名称的前N=namelengthmax个字符, 这里 ...

  5. spring AOP自定义注解方式实现日志管理

    今天继续实现AOP,到这里我个人认为是最灵活,可扩展的方式了,就拿日志管理来说,用Spring AOP 自定义注解形式实现日志管理.废话不多说,直接开始!!! 关于配置我还是的再说一遍. 在appli ...

  6. 2.0JAVA基础复习——JAVA语言的基础组成关键字和标识符

    JAVA语言的基础组成有: 1.关键字:被赋予特殊含义的单词. 2.标识符:用来标识的符号. 3.注释:用来注释说明程序的文字. 4.常量和变量:内存存储区域的表示. 5.运算符:程序中用来运算的符号 ...

  7. python的变量和简单的数据类型

    决定学习python这门语言了,本人资质愚钝,只会把学到的东西记录下来,供自己查漏补缺,也可以分享给和我一样正在学习python语言的人,若在记录中存在什么错误,希望多多批评指正,谢谢. Python ...

  8. URI/URL/URN的联系和区别

    下面是我整理的一些关于他们的描述. URI,是uniform resource identifier,统一资源标识符,用来唯一的标识一个资源. 而URL是uniform resource locato ...

  9. Linux 系统安全设置

    一.SElinux安全子系统策略. 临时修改 命令:setenforce 0 #临时关闭selinux. 命令:setenforce 1 #临时开启selinux 命令:getenforce      ...

  10. easyUI使用datagrid-detailview.js实现二级列表嵌套

    本文为博主原创,转载请注明: 在easyUI中使用datagrid-detailview.js可快速实现二级折叠列表,示例如下: 注意事项: 原本在谷歌浏览器进行示例测试的,url请求对应的json文 ...