Fabric-java-sdk 1.4.1 TLS 通信 访问Fabric网络
1.配置文件部分
- Fabric 1.4网络,采用solo模式,背书策略是: ‘OR (’’‘Org1MSP.peer’’’,’’‘Org2MSP.peer’’’)’
不采用 tls通信:
Peer0_Org1_Name=“peer0.org1.example.com”;
Peer0_Org1_Url=“grpc://localhost:7051”;
OrdererName=“orderer.example.com”;
OrdererUrl=“grpcs://localhost:7050”;
采用 tls通信:
Peer0_Org1_Name=“peer0.org1.example.com”;
Peer0_Org1_Url=“grpcs://localhost:7051”;
OrdererName=“orderer.example.com”;
OrdererUrl=“grpcs://localhost:7050”;
整个配置文件ConfigUrl.java如下:
package org.edu.fabric.sdk.config;
import com.google.protobuf.compiler.PluginProtos;
import java.io.File;
import java.nio.file.FileAlreadyExistsException;
public class ConfigUrl {
//private static String Org1_Admin_name="";
public static String Org1="org1";
public static String Org1_Msp="Org1MSP";
public static String Org2="org2";
public static String Org2_Msp="Org2MSP";
public static String Org1_Usr_Admin_Cert= File.separator+"root"+File.separator+"IdeaProjects"+File.separator+"fabricProject"
+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"crypto-config"+File.separator+"peerOrganizations"
+File.separator+"org1.example.com"+ File.separator+"users"+File.separator+"Admin@org1.example.com"+File.separator+"msp"+File.separator+"admincerts"
+File.separator+"Admin@org1.example.com-cert.pem";
public static String Org1_Usr_Admin_PK_Base_Path= File.separator+"root"+File.separator+"IdeaProjects"+File.separator+"fabricProject"
+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"crypto-config"+File.separator+"peerOrganizations"
+File.separator+"org1.example.com"+ File.separator+"users"+File.separator+"Admin@org1.example.com"+File.separator+"msp"+File.separator+"keystore";
public static String Org2_Usr_Admin_Cert=File.separator+"root"+File.separator+"IdeaProjects"+File.separator+"fabricProject"
+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"crypto-config"+File.separator+"peerOrganizations"
+File.separator+"org2.example.com"+ File.separator+"users"+File.separator+"Admin@org2.example.com"+File.separator+"msp"+File.separator+"admincerts"
+File.separator+"Admin@org2.example.com-cert.pem";
public static String Org2_Usr_Admin_PK_Base_Path= File.separator+"root"+File.separator+"IdeaProjects"+File.separator+"fabricProject"
+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"crypto-config"+File.separator+"peerOrganizations"
+File.separator+"org2.example.com"+ File.separator+"users"+File.separator+"Admin@org2.example.com"+File.separator+"msp"+File.separator+"keystore";
public static String ChannelName="mychannel";
public static String Admin="admin";
public static String Admin_Passwd="pass";
public static String OrdererName="orderer.example.com";
public static String OrdererUrl="grpcs://localhost:7050";
public static String Peer0_Org1_Name="peer0.org1.example.com";
public static String Peer0_Org1_Url="grpcs://localhost:7051";
public static String Peer1_Org1_Name="peer1.org1.example.com";
public static String Peer1_Org1_Url="grpc://localhost:8051";
public static String Peer0_Org2_Name="peer0.org2.example.com";
public static String Peer0_Org2_Url="grpc://localhost:9051";
public static String Peer1_Org2_Name="peer1.org2.example.com";
public static String Peer1_Org2_Url="grpc://localhost:10051";
public static String CA1_Name="ca-org1";
public static String CA1_Url="http://localhost:7057";
public static String CA1_Root_Cert="/root/IdeaProjects/fabricProject/src/main/resources/crypto-config/peerOrganizations/org1.example.com/ca/ca.org1.example.com-cert.pem";
public static String Org1_TLS_Root_Cert="/root/IdeaProjects/fabricProject/src/main/resources/crypto-config/peerOrganizations/org1.example.com/tlsca/tlsca.org1.example.com-cert.pem";
public static String Orderer_TLS_Root_Cert="/root/IdeaProjects/fabricProject/src/main/resources/crypto-config/ordererOrganizations/example.com/tlsca/tlsca.example.com-cert.pem";
public static String Channel_ConfigFile_Path=File.separator+"root"+File.separator+"IdeaProjects"+File.separator+"fabricProject"
+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"channel-artifacts"+File.separator+"channel.tx";
public static String Chaincode1_Name="mvp";
public static String Chaincode1_Version="1";
public static String Chaincode1_Root_Path="/root/IdeaProjects/fabricProject/src/main/resources/chaincode";
public static String Chaincode1_Path="chaincode_example02/go";
public static String Chaincode2_Name="haha";
public static String Chaincode2_Version="1";
public static String Chaincode2_Root_Path="/root/IdeaProjects/fabricProject/src/main/resources/chaincodetest";
public static String Chaincode2_Path="testcc/chaincode_example02/go";
}
2.在这个Fabric网络中 orderer2.example.com,
orderer3.example.com,orderer4.example.com,orderer4.example.com这四个排序服务节点都没有用的,只用到了orderer.example.com,crypto-config目录如下,:
2. 调用链码查询信息
QueryChaincodeOpenTls.java代码如下:
package org.edu.fabric.sdk.testtls;
import org.edu.fabric.sdk.config.ConfigUrl;
import org.edu.fabric.sdk.config.FactoryConfig;
import org.edu.fabric.sdk.impl.UserImpl;
import org.hyperledger.fabric.sdk.*;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.exception.ProposalException;
import org.hyperledger.fabric.sdk.exception.TransactionException;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Properties;
public class QueryChaincode {
public static void main(String args[]) throws IOException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, InvalidArgumentException, InstantiationException, NoSuchMethodException, CryptoException, ProposalException, TransactionException {
//这里的userContext使用的是cryptogen二进制文件生成的组织org1.example.com的管理员:Admin@org1.example.com,此外也可以使用CA节点重新去生成userContext
UserImpl userContext=new UserImpl();
userContext.setName(ConfigUrl.Admin);
userContext.setMspId(ConfigUrl.Org1_Msp);
Enrollment enrollment= FactoryConfig.getEnrollment(ConfigUrl.Org1_Usr_Admin_Cert,ConfigUrl.Org1_Usr_Admin_PK_Base_Path);
userContext.setEnrollment(enrollment);
CryptoSuite cryptoSuite=CryptoSuite.Factory.getCryptoSuite();
HFClient hfClient=HFClient.createNewInstance();
hfClient.setCryptoSuite(cryptoSuite);
hfClient.setUserContext(userContext);
//create peer ,orderer,Eventhub
String peerCert=new String(Files.readAllBytes(Paths.get("/root/IdeaProjects/fabricProject/src/main/resources/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/server.crt")),"UTF-8");
Properties peerProperties=new Properties();
peerProperties.put("pemBytes",peerCert.getBytes());
peerProperties.setProperty("sslProvider","openSSL");
peerProperties.setProperty("negotiationType","TLS");
peerProperties.setProperty("hostnameOverride", ConfigUrl.Peer0_Org1_Name);
/*
peerProperties.setProperty("clientKeyFile","");
peerProperties.setProperty()*/
Peer peer=hfClient.newPeer(ConfigUrl.Peer0_Org1_Name,ConfigUrl.Peer0_Org1_Url,peerProperties);
String ordererCert=new String(Files.readAllBytes(Paths.get("/root/IdeaProjects/fabricProject/src/main/resources/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.crt")),"UTF-8");
Properties ordererProperties=new Properties();
ordererProperties.put("pemBytes",ordererCert.getBytes());
ordererProperties.setProperty("sslProvider","openSSL");
ordererProperties.setProperty("negotiationType","TLS");
ordererProperties.setProperty("hostnameOverride",ConfigUrl.OrdererName);
Orderer orderer=hfClient.newOrderer(ConfigUrl.OrdererName,ConfigUrl.OrdererUrl,ordererProperties);
EventHub eventHub=hfClient.newEventHub(ConfigUrl.Peer0_Org1_Name,"grpcs://localhost:7053",peerProperties);
Channel channel=hfClient.newChannel(ConfigUrl.ChannelName);
channel.addPeer(peer);
channel.addOrderer(orderer);
channel.addEventHub(eventHub);
channel.initialize();
//create
QueryByChaincodeRequest queryByChaincodeRequest=hfClient.newQueryProposalRequest();
ChaincodeID chaincodeId=ChaincodeID.newBuilder().setName("mycc").build();
queryByChaincodeRequest.setChaincodeID(chaincodeId);
queryByChaincodeRequest.setFcn("query");
queryByChaincodeRequest.setArgs(new String[]{"a"});
Collection<ProposalResponse> responses=channel.queryByChaincode(queryByChaincodeRequest);
for(ProposalResponse res:responses){
if(res.getStatus().getStatus()!=200){
System.out.println("query fail:"+res.getMessage());
}else{
System.out.println(res.getStatus().toString());
byte[] mes=res.getChaincodeActionResponsePayload();
System.out.println(new String(mes));
}
}
}
}
3. 调用链码进行转账,InvokeChaincodeOpenTls.java代码如下:
package org.edu.fabric.sdk.testtls;
import org.edu.fabric.sdk.config.ConfigUrl;
import org.edu.fabric.sdk.config.FactoryConfig;
import org.edu.fabric.sdk.impl.UserImpl;
import org.hyperledger.fabric.sdk.*;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import org.hyperledger.fabric_ca.sdk.HFCAClient;
import org.hyperledger.fabric_ca.sdk.RegistrationRequest;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
public class InvokdeChaincodeOpenTls {
public static void main(String args[]) throws Exception {
//这里的userContext使用的是CA节点生成的userContext,此外也可以采用cryptogen二进制文件生成的组织org1.example.com的管理员:Admin@org1.example.com
//create hfcaClient
String CA1_Cert=new String(Files.readAllBytes(Paths.get(ConfigUrl.CA1_Root_Cert)),"UTF-8");
Properties properties=new Properties();
properties.put("pemBytes",CA1_Cert.getBytes());
properties.setProperty("allowAllHostNames","true");
HFCAClient hfcaClient=HFCAClient.createNewInstance(ConfigUrl.CA1_Name,ConfigUrl.CA1_Url,properties);
hfcaClient.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());
//create admin
UserImpl adminUserContext=new UserImpl();
adminUserContext.setName(ConfigUrl.Admin);
adminUserContext.setAffiliation(ConfigUrl.Org1);
adminUserContext.setMspId(ConfigUrl.Org1_Msp);
//create admin Enrollment
Enrollment adminEnrollment=hfcaClient.enroll(ConfigUrl.Admin,ConfigUrl.Admin_Passwd);
adminUserContext.setEnrollment(adminEnrollment);
//save adminUserContext
FileOutputStream fio=new FileOutputStream("/root/IdeaProjects/fabricProject/src/main/resources/adminContext/adminContext.txt");
ObjectOutputStream obj=new ObjectOutputStream(fio);
obj.writeObject(adminUserContext);
obj.close();
fio.close();
//create userContext,user1只能在CA节点处注册一次,可以把使用user1生成的userContext保存成本地文件,下次直接使用时直接读入,不能再重新由CA节点注册user1
UserImpl userContext=new UserImpl();
userContext.setName("user1");
userContext.setAffiliation(ConfigUrl.Org1);
userContext.setMspId(ConfigUrl.Org1_Msp);
//register user
RegistrationRequest registrationRequest=new RegistrationRequest("user1",ConfigUrl.Org1);
String enrollmentSecret =hfcaClient.register(registrationRequest,adminUserContext);
//enroll user
Enrollment userEnrollment=hfcaClient.enroll(userContext.getName(),enrollmentSecret);
userContext.setEnrollment(userEnrollment);
//save user
FileOutputStream fio1=new FileOutputStream("/root/IdeaProjects/fabricProject/src/main/resources/adminContext/userContext.txt");
ObjectOutputStream obj1=new ObjectOutputStream(fio1);
obj1.writeObject(userContext);
obj1.close();
fio1.close();
/* userContext也可以直接使用这个
UserImpl userContext=new UserImpl();
userContext.setName(ConfigUrl.Admin);
userContext.setMspId(ConfigUrl.Org1_Msp);
Enrollment enrollment= FactoryConfig.getEnrollment(ConfigUrl.Org1_Usr_Admin_Cert,ConfigUrl.Org1_Usr_Admin_PK_Base_Path);
userContext.setEnrollment(enrollment);*/
//create hfClient
CryptoSuite cryptoSuite=CryptoSuite.Factory.getCryptoSuite();
HFClient hfClient=HFClient.createNewInstance();
hfClient.setCryptoSuite(cryptoSuite);
hfClient.setUserContext(userContext);
//create peer ,orderer,Eventhub
String peerCert=new String(Files.readAllBytes(Paths.get("/root/IdeaProjects/fabricProject/src/main/resources/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/server.crt")),"UTF-8");
Properties peerProperties=new Properties();
peerProperties.put("pemBytes",peerCert.getBytes());
peerProperties.setProperty("sslProvider","openSSL");
peerProperties.setProperty("negotiationType","TLS");
peerProperties.setProperty("hostnameOverride",ConfigUrl.Peer0_Org1_Name);
Peer peer=hfClient.newPeer(ConfigUrl.Peer0_Org1_Name,ConfigUrl.Peer0_Org1_Url,peerProperties);
String ordererCert=new String(Files.readAllBytes(Paths.get("/root/IdeaProjects/fabricProject/src/main/resources/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.crt")),"UTF-8");
Properties ordererProperties=new Properties();
ordererProperties.put("pemBytes",ordererCert.getBytes());
ordererProperties.setProperty("sslProvider","openSSL");
ordererProperties.setProperty("negotiationType","TLS");
ordererProperties.setProperty("hostnameOverride",ConfigUrl.OrdererName);
Orderer orderer=hfClient.newOrderer(ConfigUrl.OrdererName,ConfigUrl.OrdererUrl,ordererProperties);
EventHub eventHub=hfClient.newEventHub(ConfigUrl.Peer0_Org1_Name,"grpcs://localhost:7053",peerProperties);
Channel channel=hfClient.newChannel(ConfigUrl.ChannelName);
channel.addPeer(peer);
channel.addOrderer(orderer);
channel.addEventHub(eventHub);
channel.initialize();
//create Transaction proposal Request
TransactionProposalRequest request=hfClient.newTransactionProposalRequest();
ChaincodeID chaincodeID=ChaincodeID.newBuilder().setName("mycc").build();
request.setChaincodeID(chaincodeID);
request.setFcn("invoke");
request.setArgs(new String[]{"a","b","22"});
// send Transaction Proposal request To ensoder peer
Collection<ProposalResponse> responses=channel.sendTransactionProposal(request);
//send Transaction Ensoder Result to orderer
channel.sendTransaction(responses);
}
}
4.相关.java文件
UserImpl.java文件如下:
package org.edu.fabric.sdk.impl;
import org.hyperledger.fabric.sdk.Enrollment;
import org.hyperledger.fabric.sdk.User;
import java.io.Serializable;
import java.util.Set;
public class UserImpl implements User, Serializable {
private String name;
private Set<String>roles;
private String account;
private String affiliation;
private Enrollment enrollment;
public UserImpl(){ }
public UserImpl(String name, Enrollment enrollment, String mspId) {
this.name = name;
this.enrollment = enrollment;
this.mspId = mspId;
}
public void setName(String name) {
this.name = name;
}
public void setRoles(Set<String> roles) {
this.roles = roles;
}
public void setAccount(String account) {
this.account = account;
}
public void setAffiliation(String affiliation) {
this.affiliation = affiliation;
}
public void setEnrollment(Enrollment enrollment) {
this.enrollment = enrollment;
}
public void setMspId(String mspId) {
this.mspId = mspId;
}
private String mspId;
@Override
public String getName() {
return this.name;
}
@Override
public Set<String> getRoles() {
return this.roles;
}
@Override
public String getAccount() {
return this.account;
}
@Override
public String getAffiliation() {
return this.affiliation;
}
@Override
public Enrollment getEnrollment() {
return this.enrollment;
}
@Override
public String getMspId() {
return this.mspId;
}
}
FactoryConfig.java文件如下:
package org.edu.fabric.sdk.config;
import org.edu.fabric.sdk.impl.EnrollmentImpl;
import org.hyperledger.fabric.sdk.Enrollment;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.security.CryptoPrimitives;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.PrivateKey;
public class FactoryConfig {
public static Enrollment getEnrollment(String certPath,String pkBasePath) throws IOException, IllegalAccessException, InstantiationException, ClassNotFoundException, CryptoException {
//get cert
byte [] certBytes= Files.readAllBytes(Paths.get(certPath));
//get pk
File[] files=new File(pkBasePath).listFiles();
String certName=files[0].getName();
String pkPath=pkBasePath+File.separator+certName;
byte [] pkBytes=Files.readAllBytes(Paths.get(pkPath));
CryptoPrimitives cryptoPrimitives=new CryptoPrimitives();
PrivateKey PK=cryptoPrimitives.bytesToPrivateKey(pkBytes);
return new EnrollmentImpl(PK,new String(certBytes,"UTF-8"));
}
}
EnrollmentImpl.java文件如下:
package org.edu.fabric.sdk.impl;
import org.hyperledger.fabric.sdk.Enrollment;
import java.security.PrivateKey;
public class EnrollmentImpl implements Enrollment {
private PrivateKey privateKey;
private String cert;
public EnrollmentImpl() {
}
public EnrollmentImpl(PrivateKey privateKey, String cert) {
this.privateKey = privateKey;
this.cert = cert;
}
@Override
public PrivateKey getKey() {
return this.privateKey;
}
@Override
public String getCert() {
return this.cert;
}
public void setPrivateKey(PrivateKey privateKey) {
this.privateKey = privateKey;
}
public void setCert(String cert) {
this.cert = cert;
}
}
参考文献:
[1]:https://blog.csdn.net/qq_27348837/article/details/95489720
[2]: https://developer.ibm.com/tutorials/hyperledger-fabric-java-sdk-for-tls-enabled-fabric-network/