Fabric

编程入门 行业动态 更新时间:2024-10-27 18:29:44

Fabric-java-sdk 1.4.1 TLS 通信 访问Fabric网络

1.配置文件部分

Fabric 1.4网络,采用solo模式,背书策略是: ‘OR (’’‘Org1MSP.peer’’’,’’‘Org2MSP.peer’’’)’

不采用 tls通信:
Peer0_Org1_Name=“peer0.1.example.”;
Peer0_Org1_Url=“grpc://localhost:7051”;
OrdererName=“orderer.example.”;
OrdererUrl=“grpcs://localhost:7050”;
采用 tls通信:
Peer0_Org1_Name=“peer0.1.example.”;
Peer0_Org1_Url=“grpcs://localhost:7051”;
OrdererName=“orderer.example.”;
OrdererUrl=“grpcs://localhost:7050”;

整个配置文件ConfigUrl.java如下:

package .edu.fabric.sdk.config;import .google.protobuf.piler.PluginProtos;import java.io.File;
import java.nio.file.FileAlreadyExistsException;public class ConfigUrl {//private static String Org1_Admin_name="";public static String Org1="1";public static String Org1_Msp="Org1MSP";public static String Org2="2";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+"1.example."+ File.separator+"users"+File.separator+"Admin@1.example."+File.separator+"msp"+File.separator+"admincerts"+File.separator+"Admin@1.example.-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+"1.example."+ File.separator+"users"+File.separator+"Admin@1.example."+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+"2.example."+ File.separator+"users"+File.separator+"Admin@2.example."+File.separator+"msp"+File.separator+"admincerts"+File.separator+"Admin@2.example.-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+"2.example."+ File.separator+"users"+File.separator+"Admin@2.example."+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.";public static String OrdererUrl="grpcs://localhost:7050";public static String Peer0_Org1_Name="peer0.1.example.";public static String Peer0_Org1_Url="grpcs://localhost:7051";public static String Peer1_Org1_Name="peer1.1.example.";public static String Peer1_Org1_Url="grpc://localhost:8051";public static String Peer0_Org2_Name="peer0.2.example.";public static String Peer0_Org2_Url="grpc://localhost:9051";public static String Peer1_Org2_Name="peer1.2.example.";public static String Peer1_Org2_Url="grpc://localhost:10051";public static String CA1_Name="ca-1";public static String CA1_Url="localhost:7057";public static String CA1_Root_Cert="/root/IdeaProjects/fabricProject/src/main/resources/crypto-config/peerOrganizations/1.example./ca/ca.1.example.-cert.pem";public static String Org1_TLS_Root_Cert="/root/IdeaProjects/fabricProject/src/main/resources/crypto-config/peerOrganizations/1.example./tlsca/tlsca.1.example.-cert.pem";public static String Orderer_TLS_Root_Cert="/root/IdeaProjects/fabricProject/src/main/resources/crypto-config/ordererOrganizations/example./tlsca/tlsca.example.-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="test/chaincode_example02/go";
}

2.在这个Fabric网络中 orderer2.example.,
orderer3.example.,orderer4.example.,orderer4.example.这四个排序服务节点都没有用的,只用到了orderer.example.,crypto-config目录如下,:

2. 调用链码查询信息

QueryChaincodeOpenTls.java代码如下:

package .edu.fabric.sdk.testtls;import .edu.fabric.sdk.config.ConfigUrl;
import .edu.fabric.sdk.config.FactoryConfig;
import .edu.fabric.sdk.impl.UserImpl;
import .hyperledger.fabric.sdk.*;
import .hyperledger.fabric.sdk.exception.CryptoException;
import .hyperledger.fabric.sdk.exception.InvalidArgumentException;
import .hyperledger.fabric.sdk.exception.ProposalException;
import .hyperledger.fabric.sdk.exception.TransactionException;
import .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, IllegalAessException, InvocationTargetException, InvalidArgumentException, InstantiationException, NoSuchMethodException, CryptoException, ProposalException, TransactionException {//这里的userContext使用的是cryptogen二进制文件生成的组织1.example.的管理员:Admin@1.example.,此外也可以使用CA节点重新去生成userContextUserImpl 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,EventhubString peerCert=new String(Files.readAllBytes(Paths.get("/root/IdeaProjects/fabricProject/src/main/resources/crypto-config/peerOrganizations/1.example./peers/peer0.1.example./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./orderers/orderer.example./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();//createQueryByChaincodeRequest queryByChaincodeRequest=hfClient.newQueryProposalRequest();ChaincodeID chaincodeId=ChaincodeID.newBuilder().setName("my").build();queryByChaincodeRequest.setChaincodeID(chaincodeId);queryByChaincodeRequest.setF("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 .edu.fabric.sdk.testtls;import .edu.fabric.sdk.config.ConfigUrl;
import .edu.fabric.sdk.config.FactoryConfig;
import .edu.fabric.sdk.impl.UserImpl;
import .hyperledger.fabric.sdk.*;
import .hyperledger.fabric.sdk.security.CryptoSuite;
import .hyperledger.fabric_ca.sdk.HFCAClient;
import .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二进制文件生成的组织1.example.的管理员:Admin@1.example.//create hfcaClientString 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 adminUserImpl adminUserContext=new UserImpl();adminUserContext.setName(ConfigUrl.Admin);adminUserContext.setAffiliation(ConfigUrl.Org1);adminUserContext.setMspId(ConfigUrl.Org1_Msp);//create admin EnrollmentEnrollment adminEnrollment=hfcaClient.enroll(ConfigUrl.Admin,ConfigUrl.Admin_Passwd);adminUserContext.setEnrollment(adminEnrollment);//save adminUserContextFileOutputStream 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节点注册user1UserImpl userContext=new UserImpl();userContext.setName("user1");userContext.setAffiliation(ConfigUrl.Org1);userContext.setMspId(ConfigUrl.Org1_Msp);//register userRegistrationRequest registrationRequest=new RegistrationRequest("user1",ConfigUrl.Org1);String enrollmentSecret =hfcaClient.register(registrationRequest,adminUserContext);//enroll userEnrollment userEnrollment=hfcaClient.enroll(userContext.getName(),enrollmentSecret);userContext.setEnrollment(userEnrollment);//save userFileOutputStream 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 hfClientCryptoSuite cryptoSuite=CryptoSuite.Factory.getCryptoSuite();HFClient hfClient=HFClient.createNewInstance();hfClient.setCryptoSuite(cryptoSuite);hfClient.setUserContext(userContext);//create peer ,orderer,EventhubString peerCert=new String(Files.readAllBytes(Paths.get("/root/IdeaProjects/fabricProject/src/main/resources/crypto-config/peerOrganizations/1.example./peers/peer0.1.example./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./orderers/orderer.example./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 RequestTransactionProposalRequest request=hfClient.newTransactionProposalRequest();ChaincodeID chaincodeID=ChaincodeID.newBuilder().setName("my").build();request.setChaincodeID(chaincodeID);request.setF("invoke");request.setArgs(new String[]{"a","b","22"});// send Transaction Proposal request To ensoder peerCollection<ProposalResponse> responses=channel.sendTransactionProposal(request);//send Transaction Ensoder Result to ordererchannel.sendTransaction(responses);}
}

4.相关.java文件

UserImpl.java文件如下:

package .edu.fabric.sdk.impl;import .hyperledger.fabric.sdk.Enrollment;
import .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 aount;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 setAount(String aount) {this.aount = aount;}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;@Overridepublic String getName() {return this.name;}@Overridepublic Set<String> getRoles() {return this.roles;}@Overridepublic String getAount() {return this.aount;}@Overridepublic String getAffiliation() {return this.affiliation;}@Overridepublic Enrollment getEnrollment() {return this.enrollment;}@Overridepublic String getMspId() {return this.mspId;}
}

FactoryConfig.java文件如下:

package .edu.fabric.sdk.config;import .edu.fabric.sdk.impl.EnrollmentImpl;
import .hyperledger.fabric.sdk.Enrollment;
import .hyperledger.fabric.sdk.exception.CryptoException;
import .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, IllegalAessException, InstantiationException, ClassNotFoundException, CryptoException {//get certbyte [] certBytes= Files.readAllBytes(Paths.get(certPath));//get pkFile[] 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 .edu.fabric.sdk.impl;import .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;}@Overridepublic PrivateKey getKey() {return this.privateKey;}@Overridepublic String getCert() {return this.cert;}public void setPrivateKey(PrivateKey privateKey) {this.privateKey = privateKey;}public void setCert(String cert) {this.cert = cert;}
}

参考文献:
[1]:blog.csdn.net/qq_27348837/article/details/95489720
[2]: developer.ibm./tutorials/hyperledger-fabric-java-sdk-for-tls-enabled-fabric-network/

更多推荐

Fabric

本文发布于:2023-05-29 23:13:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/355168.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Fabric

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!