Fabric-sdk-java鏈碼訪問快速上手【無痛】

在超級帳本Fabric區塊鏈中,應用經過節點的RPC協議接口訪問鏈碼。Java應用可使用官方提供的Fabric-sdk-java開發包來實現對鏈碼的訪問,開發包封裝了Fabric區塊鏈的GRPC鏈碼訪問協議,有利於開發人員聚焦於業務邏輯。不過Fabric-sdk-java的文檔質量保持了Hyperledger Fabric產品一向的不知所云,看起來實在是使人捉急。本文將嘗試編寫一個最簡單的能夠訪問Fabric鏈碼的Java應用,來幫助你快速上手Farbic區塊鏈的Java應用開發。java

若是但願快速掌握Fabric區塊鏈的鏈碼及應用開發,建議訪問匯智網的在線互動課程:網絡

基本原理

在Fabric區塊鏈中,應用經過節點的RPC協議接口訪問鏈碼:app

fabric-sdk-java

相似於Shim API對鏈碼通訊協議的封裝,Fabric Java SDK提供了 對節點RPC協議 接口的封裝,其入口類爲HFClient,對鏈碼的查詢和交易操做則 封裝在Channel類中:ide

java sdk brief

因爲Fabric是許可制區塊鏈,所以應用也須要持有證書和私鑰以表徵本身的身份,HFClient實例 依賴於User接口的實現對象 來訪問一個特定身份的證書和私鑰,所以在訪問 鏈碼以前,咱們須要首先定義一個簡單的User接口實現類。區塊鏈

實現User接口

HFClient實例訪問Fabric網絡的身份使用User接口實現對象來表徵,所以咱們須要定義一個簡單的 User接口實現類LocalUserui

user impl

容易理解,一個用戶的身份是由它的證書來標識的,同時交易還須要證書對應的私鑰,所以LocalUser 的核心邏輯就是利用指定的證書和私鑰PEM文件知足User接口的要求。this

首先按照User接口的要求完成類LocalUser的骨架:3d

import org.hyperledger.fabric.sdk.User;
import org.hyperledger.fabric.sdk.security.CryptoPrimitives;

public class LocalUser implements User{             //實現User接口
  private String name;
  private String mspId;
  private Enrollment enrollment;

  LocalUser(String name,String mspId){
    this.name = name;
    this.mspId = mspId;
  }

  private Enrollment loadFromPemFile(String keyFile,String certFile){ /*見下文說明*/ }

  @Override public String getName(){ return name; }
  @Override public String getMspId() { return mspId}
  @Override public Enrollment getEnrollment() { return enrollment; }
  @Override public String getAccount() { return null; }
  @Override public String getAffiliation() { return null; }
}

在Fabric Java SDK中,Enrollment接口用來提供對用戶的私鑰和證書的訪問, 而且預置了一個適合 X509證書的實現類X509Enrollment,所以咱們能夠從本地 MSP目錄中的PEM文件中載入用戶私鑰和簽名證書:code

private Enrollment loadFromPemFile(String keyFile,String certFile) throws Exception{
  byte[] keyPem = Files.readAllBytes(Paths.get(keyFile));     //載入私鑰PEM文本
  byte[] certPem = Files.readAllBytes(Paths.get(certFile));   //載入證書PEM文本
  CryptoPrimitives suite = new CryptoPrimitives();            //載入密碼學套件
  PrivateKey privateKey = suite.bytesToPrivateKey(keyPem);    //將PEM文本轉換爲私鑰對象
  return new X509Enrollment(privateKey,new String(certPem));  //建立並返回X509Enrollment對象
}

訪問鏈碼

有了User接口實現類,接下來只要建立一個HFClient實例,而後獲取通道對象, 就能夠查詢鏈碼,或者提交鏈碼交易了。orm

完整的實現代碼以下:

package com.hubwiz.demo;

import org.hyperledger.fabric.sdk.User;
import org.hyperledger.fabric.sdk.HFClient;
import org.hyperledger.fabric.sdk.Channel;
import org.hyperledger.fabric.sdk.Peer;
import org.hyperledger.fabric.sdk.Orderer;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import org.hyperledger.fabric.sdk.ChaincodeID;
import org.hyperledger.fabric.sdk.QueryByChaincodeRequest;
import org.hyperledger.fabric.sdk.ProposalResponse;
import org.hyperledger.fabric.sdk.TransactionProposalRequest;
import org.hyperledger.fabric.sdk.BlockEvent.TransactionEvent;

import java.util.Collection;
import java.util.concurrent.CompletableFuture;

public class App{
  public static void main(String[] args) throws Exception{
    System.out.println("counter app");
    
    //建立User實例
    String keyFile = "../solo-network/msp/keystore/user-key.pem";
    String certFile = "../solo-network/msp/signcerts/user-cert.pem";
    LocalUser user = new LocalUser("admin","SampleOrg",keyFile,certFile);
    
    //建立HFClient實例
    HFClient client = HFClient.createNewInstance();
    client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());
    client.setUserContext(user);
    
    //建立通道實例
    Channel channel = client.newChannel("ch1");
    Peer peer = client.newPeer("peer1`","grpc://127.0.0.1:7051");
    channel.addPeer(peer);
    Orderer orderer = client.newOrderer("orderer1","grpc://127.0.0.1:7050");
    channel.addOrderer(orderer);
    channel.initialize();
    
    //查詢鏈碼
    QueryByChaincodeRequest req = client.newQueryProposalRequest();
    ChaincodeID cid = ChaincodeID.newBuilder().setName("counter-cc").build();
    req.setChaincodeID(cid);
    req.setFcn("value");
    ProposalResponse[] rsp = channel.queryByChaincode(req).toArray(new ProposalResponse[0]);
    System.out.format("rsp message => %s\n",rsp[0].getProposalResponse().getResponse().getPayload().toStringUtf8());

    //提交鏈碼交易
    TransactionProposalRequest req2 = client.newTransactionProposalRequest();
    req2.setChaincodeID(cid);
    req2.setFcn("inc");
    req2.setArgs("10");
    Collection<ProposalResponse> rsp2 = channel.sendTransactionProposal(req2);
    TransactionEvent event = channel.sendTransaction(rsp2).get();
    System.out.format("txid: %s\n", event.getTransactionID());
    System.out.format("valid: %b\n", event.isValid());
  }
}

匯智網原創,轉載請代表出處

相關文章
相關標籤/搜索