《Netkiller Blockchain 手札》Hyperledger Fabric Java SDK Demo 原 薦

Netkiller Blockchain 手札

Mr. Neo Chan, 陳景峯(BG7NYT)



中國廣東省深圳市望海路半島城邦三期
518067
+86 13113668890

<[email protected]>

文檔始創於2018-02-10

版權 © 2018 Netkiller(Neo Chan). All rights reserved.

 

版權聲明

轉載請與作者聯繫,轉載時請務必標明文章原始出處和作者信息及本聲明。

http://www.netkiller.cn
http://netkiller.github.io
http://netkiller.sourceforge.net
微信訂閱號 netkiller-ebook (微信掃描二維碼)
QQ:13721218 請註明“讀者”
QQ羣:128659835 請註明“讀者”

 

2018-06-01

內容摘要

這一部關於區塊鏈開發及運維的電子書。

爲什麼會寫區塊鏈電子書?因爲2018年是區塊鏈年,區塊鏈是一個風口,前幾個風口我都錯過了。例如web2.0, 雲, 大數據等等,都從身旁擦肩而過。所以我要抓住這次。

這本電子書是否會出版(紙質圖書)? 不會,因爲互聯網技術更迭太快,紙質書籍的內容無法實時更新,一本書動輒百元,很快就成爲垃圾,你會發現目前市面的上區塊鏈書籍至少是一年前寫的,內容已經過時,很多例子無法正確運行。所以我不會出版,電子書的內容會追逐技術發展,及時跟進軟件版本的升級,做到內容最新,至少是主流。

這本電子書與其他區塊鏈書籍有什麼不同?市面上大部分區塊鏈書籍都是用2/3去講區塊鏈原理,只要不到 1/3 的乾貨,乾貨不夠理論來湊,通篇將理論或是大談特談區塊鏈行業,這些內容更多是頭腦風暴,展望區塊鏈,均無法落地實施。本書與那些書籍完全不同,不講理論和原理,面向應用落地,注重例子,均是乾貨。

寫作原則,無法落地的項目作者絕對不會寫。凡是寫入電子的內容均具備可操作,可落地。

電子書更新頻率?每天都會有新內容加入,更新頻率最遲不會超過一週,更新內容請關注 https://github.com/netkiller/netkiller.github.io/commits/master

本文采用碎片化寫作,原文會不定期更新,請儘量閱讀原文。 http://www.netkiller.cn/blockchain/index.html

您的打賞是我的寫作動力: http://www.netkiller.cn/blockchain/donations.html

接受 ETH 捐贈: 0x3e827461Cc53ed7c75A29187CfF39629FCAE3661

 

39.1.6. Fabric Java SDK Demo

 

39.1.6.1. Maven pom.xml 文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>cn.netkiller</groupId>
	<artifactId>fabric-sdk-java</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.hyperledger.fabric-sdk-java/fabric-sdk-java -->
		<dependency>
			<groupId>org.hyperledger.fabric-sdk-java</groupId>
			<artifactId>fabric-sdk-java</artifactId>
			<version>1.2.1</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>apache-log4j-extras</artifactId>
			<version>1.1</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.16</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.16</version>
		</dependency>
		<!-- <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> </dependency> -->
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-api</artifactId>
			<version>RELEASE</version>
		</dependency>

	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.6.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
				</configuration>
				<executions>
					<execution>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

39.1.6.2. chaincode_example02.go

Chaincode 是 Hyperledger Fabric官方提供的

/*
Copyright IBM Corp. 2016 All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

		 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

//WARNING - this chaincode's ID is hard-coded in chaincode_example04 to illustrate one way of
//calling chaincode from a chaincode. If this example is modified, chaincode_example04.go has
//to be modified as well with the new ID of chaincode_example02.
//chaincode_example05 show's how chaincode ID can be passed in as a parameter instead of
//hard-coding.

import (
	"fmt"
	"strconv"

	"github.com/hyperledger/fabric/core/chaincode/shim"
	pb "github.com/hyperledger/fabric/protos/peer"
)

// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}

func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
	fmt.Println("ex02 Init")
	_, args := stub.GetFunctionAndParameters()
	var A, B string    // Entities
	var Aval, Bval int // Asset holdings
	var err error

	if len(args) != 4 {
		return shim.Error("Incorrect number of arguments. Expecting 4")
	}

	// Initialize the chaincode
	A = args[0]
	Aval, err = strconv.Atoi(args[1])
	if err != nil {
		return shim.Error("Expecting integer value for asset holding")
	}
	B = args[2]
	Bval, err = strconv.Atoi(args[3])
	if err != nil {
		return shim.Error("Expecting integer value for asset holding")
	}
	fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)

	// Write the state to the ledger
	err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
	if err != nil {
		return shim.Error(err.Error())
	}

	err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
	if err != nil {
		return shim.Error(err.Error())
	}

	return shim.Success(nil)
}

func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
	fmt.Println("ex02 Invoke")
	function, args := stub.GetFunctionAndParameters()
	if function == "invoke" {
		// Make payment of X units from A to B
		return t.invoke(stub, args)
	} else if function == "delete" {
		// Deletes an entity from its state
		return t.delete(stub, args)
	} else if function == "query" {
		// the old "Query" is now implemtned in invoke
		return t.query(stub, args)
	}

	return shim.Error("Invalid invoke function name. Expecting \"invoke\" \"delete\" \"query\"")
}

// Transaction makes payment of X units from A to B
func (t *SimpleChaincode) invoke(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	var A, B string    // Entities
	var Aval, Bval int // Asset holdings
	var X int          // Transaction value
	var err error

	if len(args) != 3 {
		return shim.Error("Incorrect number of arguments. Expecting 3")
	}

	A = args[0]
	B = args[1]

	// Get the state from the ledger
	// TODO: will be nice to have a GetAllState call to ledger
	Avalbytes, err := stub.GetState(A)
	if err != nil {
		return shim.Error("Failed to get state")
	}
	if Avalbytes == nil {
		return shim.Error("Entity not found")
	}
	Aval, _ = strconv.Atoi(string(Avalbytes))

	Bvalbytes, err := stub.GetState(B)
	if err != nil {
		return shim.Error("Failed to get state")
	}
	if Bvalbytes == nil {
		return shim.Error("Entity not found")
	}
	Bval, _ = strconv.Atoi(string(Bvalbytes))

	// Perform the execution
	X, err = strconv.Atoi(args[2])
	if err != nil {
		return shim.Error("Invalid transaction amount, expecting a integer value")
	}
	Aval = Aval - X
	Bval = Bval + X
	fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)

	// Write the state back to the ledger
	err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
	if err != nil {
		return shim.Error(err.Error())
	}

	err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
	if err != nil {
		return shim.Error(err.Error())
	}

	return shim.Success(nil)
}

// Deletes an entity from state
func (t *SimpleChaincode) delete(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	if len(args) != 1 {
		return shim.Error("Incorrect number of arguments. Expecting 1")
	}

	A := args[0]

	// Delete the key from the state in ledger
	err := stub.DelState(A)
	if err != nil {
		return shim.Error("Failed to delete state")
	}

	return shim.Success(nil)
}

// query callback representing the query of a chaincode
func (t *SimpleChaincode) query(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	var A string // Entities
	var err error

	if len(args) != 1 {
		return shim.Error("Incorrect number of arguments. Expecting name of the person to query")
	}

	A = args[0]

	// Get the state from the ledger
	Avalbytes, err := stub.GetState(A)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get state for " + A + "\"}"
		return shim.Error(jsonResp)
	}

	if Avalbytes == nil {
		jsonResp := "{\"Error\":\"Nil amount for " + A + "\"}"
		return shim.Error(jsonResp)
	}

	jsonResp := "{\"Name\":\"" + A + "\",\"Amount\":\"" + string(Avalbytes) + "\"}"
	fmt.Printf("Query Response:%s\n", jsonResp)
	return shim.Success(Avalbytes)
}

func main() {
	err := shim.Start(new(SimpleChaincode))
	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}

39.1.6.3. bcs-whbsxu-sdk-config.yaml

name: "global-trade-network"

x-type: "hlfv1"
x-loggingLevel: info

description: "The network to be in if you want to stay in the global trade business"

version: 1.0.0

client:

  organization: 23e50b60552eb5b6f32d3c1563305dd4530dc2f0

  logging:
    level: info

  peer:
    timeout:
      connection: 10s
      queryResponse: 45s
      executeTxResponse: 120s
  eventService:
    timeout:
      connection: 10s
      registrationResponse: 50s
  orderer:
    timeout:
      connection: 10s
      response: 45s

  cryptoconfig:
    path: /opt/gopath/src/github.com/hyperledger/fabric

  credentialStore:
    path: "/tmp/hfc-kvs"

    cryptoStore:
      path: /tmp/msp

    wallet: wallet-name

  BCCSP:
    security:
     enabled: true
     default:
      provider: "SW"
     hashAlgorithm: "SHA2"
     softVerify: true
     ephemeral: false
     level: 256

channels:
  
  artbank:
    orderers:
      
      - orderer-c18fb08fe08fca399fa6baf66bee2f59e50fcea5-0.orderer-c18fb08fe08fca399fa6baf66bee2f59e50fcea5.default.svc.cluster.local
      
    peers:
      
      peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0-0.peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0.default.svc.cluster.local:
        endorsingPeer: true
        chaincodeQuery: true
        ledgerQuery: true
        eventSource: true
      
      peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0-1.peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0.default.svc.cluster.local:
        endorsingPeer: true
        chaincodeQuery: true
        ledgerQuery: true
        eventSource: true
      
    chaincodes:
      - example:1.0
  
organizations:
  
  23e50b60552eb5b6f32d3c1563305dd4530dc2f0:
    mspid: 23e50b60552eb5b6f32d3c1563305dd4530dc2f0MSP

    cryptoPath:  /opt/fabric/23e50b60552eb5b6f32d3c1563305dd4530dc2f0.peer/msp
    tlsCryptoKeyPath: /opt/fabric/23e50b60552eb5b6f32d3c1563305dd4530dc2f0.peer/tls/server.key
    tlsCryptoCertPath: /opt/fabric/23e50b60552eb5b6f32d3c1563305dd4530dc2f0.peer/tls/server.crt

    peers:
      
      - peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0-0.peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0.default.svc.cluster.local
      
      - peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0-1.peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0.default.svc.cluster.local
      
    certificateAuthorities:
      - ca-org1
  
  ordererorg:
      mspID: "c18fb08fe08fca399fa6baf66bee2f59e50fcea5MSP"

      cryptoPath: /opt/fabric/c18fb08fe08fca399fa6baf66bee2f59e50fcea5.orderer/msp
orderer-eip: 49.4.15.203
orderers:
  
  orderer-c18fb08fe08fca399fa6baf66bee2f59e50fcea5-0.orderer-c18fb08fe08fca399fa6baf66bee2f59e50fcea5.default.svc.cluster.local:
    url: grpcs://49.4.15.203:30805

    grpcOptions:
      ssl-target-name-override: orderer-c18fb08fe08fca399fa6baf66bee2f59e50fcea5-0.orderer-c18fb08fe08fca399fa6baf66bee2f59e50fcea5.default.svc.cluster.local
      grpc-max-send-message-length: 15
      sslProvider: openSSL
      negotiationType: TLS
      hostnameOverride: orderer-c18fb08fe08fca399fa6baf66bee2f59e50fcea5-0.orderer-c18fb08fe08fca399fa6baf66bee2f59e50fcea5.default.svc.cluster.local

    tlsCACerts:
      path: /opt/fabric/c18fb08fe08fca399fa6baf66bee2f59e50fcea5.orderer/msp/tlscacerts/tlsca.c18fb08fe08fca399fa6baf66bee2f59e50fcea5-cert.pem
  
peer-eip: 49.4.15.203
peers:
  
  peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0-0.peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0.default.svc.cluster.local:
    url: grpcs://49.4.15.203:30605

    eventUrl: grpcs://49.4.15.203:30705

    grpcOptions:
      ssl-target-name-override: peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0-0.peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0.default.svc.cluster.local
      grpc.http2.keepalive_time: 15
      sslProvider: openSSL
      negotiationType: TLS
      hostnameOverride: peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0-0.peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0.default.svc.cluster.local

    tlsCACerts:
      path: /opt/fabric/23e50b60552eb5b6f32d3c1563305dd4530dc2f0.peer/msp/tlscacerts/tlsca.23e50b60552eb5b6f32d3c1563305dd4530dc2f0-cert.pem
  
  peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0-1.peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0.default.svc.cluster.local:
    url: grpcs://49.4.15.203:30606

    eventUrl: grpcs://49.4.15.203:30706

    grpcOptions:
      ssl-target-name-override: peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0-1.peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0.default.svc.cluster.local
      grpc.http2.keepalive_time: 15
      sslProvider: openSSL
      negotiationType: TLS
      hostnameOverride: peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0-1.peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0.default.svc.cluster.local

    tlsCACerts:
      path: /opt/fabric/23e50b60552eb5b6f32d3c1563305dd4530dc2f0.peer/msp/tlscacerts/tlsca.23e50b60552eb5b6f32d3c1563305dd4530dc2f0-cert.pem
  
certificateAuthorities:
  ca-org1:
    url: https://ca_peerOrg1:7054
    httpOptions:
      verify: true
    tlsCACerts:
      path: $GOPATH/src/github.com/hyperledger/fabric-sdk-go/test/api-server/tls/fabricca/certs/ca_root.pem
      client:
       keyfile: $GOPATH/src/github.com/hyperledger/fabric-sdk-go/test/api-server/tls/fabricca/certs/client/client_fabric_client-key.pem
       certfile: $GOPATH/src/github.com/hyperledger/fabric-sdk-go/test/api-server/tls/fabricca/certs/client/client_fabric_client.pem

    registrar:
      enrollId: admin
      enrollSecret: adminpw
    caName: ca-org1

39.1.6.4. FabricHelper.java

package cn.netkiller.fabric;


import org.apache.commons.io.IOUtils;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.hyperledger.fabric.sdk.*;
import org.hyperledger.fabric.sdk.NetworkConfig.OrgInfo;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.security.PrivateKey;
import java.util.*;
import java.util.concurrent.TimeUnit;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonValue;

import static java.nio.charset.StandardCharsets.UTF_8;

public class FabricHelper {
    private Logger logger = LoggerFactory.getLogger(FabricHelper.class);

	private String ymlFileName = "./huawei.yaml";
	private String channelName;
	private String chaincodeName;
	private String accessKey;
    private Map<String, HFClient> clientMap;
    private Map<String, Channel> channelMap;
    private FabricHelper() {
        channelMap = new HashMap<>();
        clientMap = new HashMap<>();
    }

    private static class Holder {
        private static FabricHelper instance = new FabricHelper();
    }

    public static FabricHelper getInstance(){
        return Holder.instance;
    }

    public void setConfigCtx(String configPath) {
        if (configPath == null || configPath.equals("")) {
            logger.error("config path is empty! please input correct ymal path!");
        }
        this.ymlFileName = configPath;
        try {
            InputStream stream = new FileInputStream(new File(this.ymlFileName));
            Yaml yaml = new Yaml();
            Map<String, Object> confYaml = yaml.load(stream);
            JsonObject confJson = Json.createObjectBuilder(confYaml).build();

            this.accessKey = confJson.getJsonObject("client").getString("organization");

            JsonObject channels = confJson.getJsonObject("channels");
            //因爲只有一個channel 所以只需獲取鍵名即可
            String chanNameTemp = channels.keySet().toString();
            this.channelName = chanNameTemp.substring(chanNameTemp.indexOf("[") + 1, chanNameTemp.indexOf("]"));

            // 因爲只有一個chaincode 所以只需取chaincode數組的第一個
            String codeNameTemp = channels.getJsonObject(this.channelName).getJsonArray("chaincodes").getString(0);
            this.chaincodeName = codeNameTemp.substring(0, codeNameTemp.indexOf(":"));
        }
        catch (Exception e)
        {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }
    
    public FabricHelper setConfigPath(String configPath){
    	this.ymlFileName=configPath;
    	return this;
    }
    
    public FabricHelper setChaincodeName(String chaincodeName) {
    	this.chaincodeName=chaincodeName;
    	return this;
    }
    	
    public FabricHelper setChannelName(String channelName) {
    	this.channelName=channelName;
    	return this;
    }
    
    public FabricHelper setAccessKey(String accesskey) {
    	this.accessKey=accesskey;
    	return this;
    }

    private NetworkConfig loadfromYamlFile(String fileName) {
        try {
            return NetworkConfig.fromYamlFile(new File(fileName));
            
        } catch (Exception e) {
            String msg = "can't load yaml file: " + fileName;
            logger.error(msg, e);
            return null;
        }
    }

    private Channel buildChannel(String channelName, NetworkConfig networkConfig, HFClient client) {
        try {
            FabricUser user = genFabricUser(accessKey);
            client.setUserContext(user);
            Channel channel = client.loadChannelFromConfig(channelName, networkConfig);
            channel.initialize();
            return channel;
        } catch (Exception e) {
            String msg = "can't construct channel: " + networkConfig.getClientOrganization();
            logger.error(msg, e);
            return null;
        }
    }

    private HFClient getClient(String orgName) {
        HFClient client = clientMap.get(orgName);
        if (client == null) {
            synchronized (clientMap) {
            	client = clientMap.get(orgName);
            	if (client != null) {
            		return client;
            	}
            	
                client = HFClient.createNewInstance();
                try {
                    client.setCryptoSuite(getCryptoSuite());
                    clientMap.put(orgName, client);
                } catch (Exception e) {
                    String msg = "can't construct client: " + orgName;
                    logger.error(msg, e);
                    System.out.println(msg);
                    return null;
                }
            }
        }

        return client;
    }
    
    private CryptoSuite getCryptoSuite() throws java.lang.IllegalAccessException, java.lang.InstantiationException, java.lang.ClassNotFoundException, org.hyperledger.fabric.sdk.exception.CryptoException, org.hyperledger.fabric.sdk.exception.InvalidArgumentException, java.lang.NoSuchMethodException, java.lang.reflect.InvocationTargetException, FileNotFoundException{
    	CryptoSuite cs = null;
    	InputStream stream = new FileInputStream(this.ymlFileName);
		Map<String, Object> map = new Yaml().load(stream);
		JsonObject root = Json.createObjectBuilder(map).build();
        String hashAlgo =root.getJsonObject("client").getJsonObject("BCCSP").getJsonObject("security").getString("hashAlgorithm"); 
        //for sm Algorithm
    	if (hashAlgo.equals("SM3")){
    		Properties properties = new Properties();
            properties.setProperty("org.hyperledger.fabric.sdk.hash_algorithm", "SM3");
            properties.setProperty("org.hyperledger.fabric.sdk.crypto.default_signature_userid", "1234567812345678");
    		cs = CryptoSuite.Factory.getCryptoSuite(properties);
    	}else{
    		cs = CryptoSuite.Factory.getCryptoSuite();
    	}
    	return cs;
    }
    
    private Channel getChannel(String accessKey, HFClient client) {
        Channel channel = channelMap.get(accessKey);
        if (channel == null) {
            synchronized (channelMap) {
            	channel = channelMap.get(accessKey);
            	if (channel != null) {
            	   return channel;
            	}
            	
            	NetworkConfig networkConfig = loadfromYamlFile(ymlFileName);
                if (networkConfig == null) {
                    return null;
                }

                try {
                	  
                    networkConfig.getOrdererNames().forEach(item -> {
                        try {
                        	Properties p = networkConfig.getOrdererProperties(item);
                        	p.setProperty("hostnameOverride", item);
                            p.setProperty("clientCertFile", GetTlsCert(ymlFileName, "ordererorg"));
                            p.setProperty("clientKeyFile",  GetTlsKey(ymlFileName, "ordererorg"));
                            networkConfig.setOrdererProperties(item, p);
                        } catch (InvalidArgumentException e) {
                            throw new RuntimeException(e);
                        }
                    });

                    networkConfig.getPeerNames().forEach(item -> {
                        try {
                        	Properties p = networkConfig.getPeerProperties(item);
                        	String orgId = getOrgIdByPeer(networkConfig,item);
                        	p.setProperty("hostnameOverride", item);
                            p.setProperty("clientCertFile", GetTlsCert(ymlFileName, orgId));
                            p.setProperty("clientKeyFile",  GetTlsKey(ymlFileName, orgId));
                            networkConfig.setPeerProperties(item, p);
                        } catch (InvalidArgumentException e) {
                            throw new RuntimeException(e);
                        }
                    });

                    
                    networkConfig.getEventHubNames().forEach(item -> {
                        try {
                        	Properties p = networkConfig.getEventHubsProperties(item);
                        	String orgId = getOrgIdByPeer(networkConfig,item);
                        	p.setProperty("hostnameOverride", item);
                            p.setProperty("clientCertFile", GetTlsCert(ymlFileName, orgId));
                            p.setProperty("clientKeyFile",  GetTlsKey(ymlFileName, orgId));
                            networkConfig.setEventHubProperties(item, p);
                        } catch (InvalidArgumentException e) {
                            throw new RuntimeException(e);
                        }
                    });

                    networkConfig.getChannelNames().forEach( item -> {
                    		if (channelName!="" ){
                    				channelName = item;
                    		}
                    });
                    
                } catch (Exception e) {
                    String msg = "can't get channel: " + accessKey;
                    logger.error(msg, e);
                    return null;
                }

                channel = buildChannel(channelName, networkConfig, client);
                if (channel != null) {
                    channelMap.put(accessKey, channel);
                }
            }
        }

        return channel;
    }
    
    private String getCryptoPath(String configFile, String orgId) {
		JsonObject root = null;
		try {
			InputStream stream = new FileInputStream(configFile);
			Yaml yaml = new Yaml();
			Map<String, Object> map = yaml.load(stream);
			root = Json.createObjectBuilder(map).build();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		JsonObject orgs = root.getJsonObject("organizations");
		for (Map.Entry<String, JsonValue> o : orgs.entrySet()) {
			if (orgId.equals(o.getKey())) {
				JsonObject v = (JsonObject) o.getValue();
				return v.getString("cryptoPath");
			}
		}
		return "";
	}
	
    private String GetTlsCert(String configFile, String orgId){
		String msp = getCryptoPath(configFile, orgId);
		int index = msp.lastIndexOf("msp");
		String ret = msp.substring(0, index)+"tls/server.crt";
		logger.debug("tls cert for " + orgId +",path:"+ ret);
		return ret;
	}
	
	private String GetTlsKey(String configFile, String orgId){
		String msp = getCryptoPath(configFile, orgId);
		int index = msp.lastIndexOf("msp");
		String ret = msp.substring(0, index)+"tls/server.key";
		logger.debug("tls key for " + orgId +",path:"+ ret);
		return ret;
	}
	
	private String getOrgIdByPeer(NetworkConfig config, String peerName){
		for ( OrgInfo o : config.getOrganizationInfos()) {
			for (String p : o.getPeerNames()){
				if ( p.equals(peerName) ){
					return o.getName();
				}
			}
		}
		return "";
	}
	
	private FabricUser genFabricUser(String accessKey) {
		FabricUser user = new FabricUser(accessKey); 
		String msp = getCryptoPath(this.ymlFileName, accessKey);
		String adminPrivateKeyString = extractPemString(msp,"keystore");
		String signedCert = extractPemString(msp, "signcerts");
		
		PrivateKey privateKey = null;
        try {
            privateKey = getPrivateKeyFromString(adminPrivateKeyString);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        
        final PrivateKey privateKeyFinal = privateKey;
		user.setEnrollment(new Enrollment() {
            @Override
            public PrivateKey getKey() {
                return privateKeyFinal;
            }

            @Override
            public String getCert() {
                return signedCert;
            }
        });
		return user;
	}
	
	private String extractPemString(String path, String sub){
		    String pemString = ""; 	
            File dir = new File(path + "/" + sub ); 
            if (!dir.exists()){
            	logger.error("directory is not exist. path:" + dir);
            	return "";
            }
            
            for (File f : dir.listFiles()){
				try {
					FileInputStream  stream = new FileInputStream(f);
					pemString = IOUtils.toString(stream, "UTF-8");
	            	return pemString;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
        return pemString;
    }
	private static PrivateKey getPrivateKeyFromString(String data)
            throws IOException {
        final Reader pemReader = new StringReader(data);
        final PrivateKeyInfo pemPair;
        try (PEMParser pemParser = new PEMParser(pemReader)) {
            pemPair = (PrivateKeyInfo) pemParser.readObject();
        }
        return new JcaPEMKeyConverter().getPrivateKey(pemPair);
    }
	
	
    public boolean invokeBlockchain(String method, String[] args) {
        HFClient client = getClient(accessKey);
        if (client == null) {
        	return false;
        }

        Channel channel = getChannel(accessKey, client);
        if (channel == null) {
            return false;
        }

        Collection<ProposalResponse> successful = new LinkedList<>();
        Collection<ProposalResponse> failed = new LinkedList<>();

        try {
            TransactionProposalRequest req = client.newTransactionProposalRequest();
            ChaincodeID cid = ChaincodeID.newBuilder().setName(chaincodeName).build();
            req.setChaincodeID(cid);
            req.setFcn(method);
            req.setArgs(args);

            Map<String, byte[]> tm2 = new HashMap<>();
            tm2.put("HyperLedgerFabric", "TransactionProposalRequest:JavaSDK".getBytes(UTF_8));
            tm2.put("method", "TransactionProposalRequest".getBytes(UTF_8));
            tm2.put("result", ":)".getBytes(UTF_8));  /// This should be returned see chaincode.
            req.setTransientMap(tm2);

            Collection<ProposalResponse> resps = channel.sendTransactionProposal(req);

            for (ProposalResponse response : resps) {
                if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
                    successful.add(response);
                } else {
                    failed.add(response);
                }
            }

            // Check that all the proposals are consistent with each other. We should have only one set
            // where all the proposals above are consistent.
            Collection<Set<ProposalResponse>> proposalConsistencySets = SDKUtils.getProposalConsistencySets(resps);
            if (proposalConsistencySets.size() != 1) {
                logger.error("Expected only one set of consistent proposal responses but got {}: {}" + proposalConsistencySets.size(), args.toString());
                return false;
            }

            if (failed.size() > 0) {
                ProposalResponse firstTransactionProposalResponse = failed.iterator().next();
                logger.error("Not enough endorsers for {}: {}. endorser error: {}, Was verified: {}",  args, failed.size(),
                        firstTransactionProposalResponse.getMessage(), firstTransactionProposalResponse.isVerified());
                return false;
            }

            BlockEvent.TransactionEvent transactionEvent = channel.sendTransaction(successful).get(30, TimeUnit.SECONDS);
            if (transactionEvent.isValid()) {
                logger.info("Finished transaction with transaction id {}: {}", transactionEvent.getTransactionID(), args);
                return true;
            } else {
                logger.error("can't commit result: {}", args.toString());
                return false;
            }
        } catch (Exception e) {
            String msg = "can't put record to blockchain: " + args;
            logger.error(msg, e);
            return false;
        }
    }

    public String queryBlockchain(String method, String[] params) {
        HFClient client = getClient(accessKey);
        if (client == null) {
            return "{1}";
        }

        Channel channel = getChannel(accessKey, client);
        if (channel == null)  {
            return "{2}";
        }

        try {
            
            QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
            queryByChaincodeRequest.setArgs(params);
            queryByChaincodeRequest.setFcn(method);
            queryByChaincodeRequest.setChaincodeID(ChaincodeID.newBuilder().setName(chaincodeName).build());

            Map<String, byte[]> tm2 = new HashMap<>();
            tm2.put("HyperLedgerFabric", "QueryByChaincodeRequest:JavaSDK".getBytes(UTF_8));
            tm2.put("method", "QueryByChaincodeRequest".getBytes(UTF_8));
            queryByChaincodeRequest.setTransientMap(tm2);

            String payload = null;
            Collection<ProposalResponse> queryProposals = channel.queryByChaincode(queryByChaincodeRequest, channel.getPeers());
            for (ProposalResponse proposalResponse : queryProposals) {
                if (!proposalResponse.isVerified() || proposalResponse.getStatus() != ProposalResponse.Status.SUCCESS) {
                    logger.error("Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() +
                            ". Messages: " + proposalResponse.getMessage()
                            + ". Was verified : " + proposalResponse.isVerified());
                } else {
                    payload = proposalResponse.getProposalResponse().getResponse().getPayload().toStringUtf8();
                    logger.info("Query payload from peer {} returned {}", proposalResponse.getPeer().getName(), payload);
                    break;
                }
            }

            return !payload.equals("null") ? payload : "{}";
        } catch (Exception e) {
            String msg = "can't query record from blockchain. condition: " +  accessKey + "," + params;
            logger.error(msg);
            return "{3}";
        }
    }
}

39.1.6.5. FabricUser.java

package cn.netkiller.fabric;

import java.util.Set;

import org.hyperledger.fabric.sdk.Enrollment;
import org.hyperledger.fabric.sdk.User;

public class FabricUser implements User {

	public void setName(String name) {
		this.name = name;
	}

	protected String name;
	protected String enrollSecret;
	protected String mspid;
	private Set<String> roles;
	private String account;
	private String affiliation;
	private Enrollment enrollment;

	public void setEnrollSecret(String enrollSecret) {
		this.enrollSecret = enrollSecret;
	}

	public String getMspid() {
		return mspid;
	}

	public void setMspid(String mspid) {
		this.mspid = mspid;
	}

	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 FabricUser(String accessKey) {
		this.name = accessKey;
		this.mspid = accessKey + "MSP";
	}

	public String getEnrollSecret() {
		return enrollSecret;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public Set<String> getRoles() {
		return roles;
	}

	@Override
	public String getAccount() {
		return account;
	}

	@Override
	public String getAffiliation() {
		return affiliation;
	}

	@Override
	public Enrollment getEnrollment() {
		return enrollment;
	}

	public String getMspId() {
		return mspid;
	}

}

39.1.6.6. Main.java

package cn.netkiller.fabric;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CountDownLatch;

/**
 * run this main method and check result
 */
public class Main {
	private static Logger logger = LoggerFactory.getLogger(Main.class);

	public static void main(String args[]) throws Exception {
		FabricHelper helper = FabricHelper.getInstance();
		helper.setConfigCtx("/Users/neo/workspace/fabric-sdk-java/src/main/resources/fixture/config/bcs-whbsxu-sdk-config.yaml");
		LoopInvoke(1);
		// StartMultiTask(1,1);
	}

	public static void LoopInvoke(int loop) throws Exception {
		FabricHelper helper = FabricHelper.getInstance();
		for (int i = 0; i < loop; i++) {
			helper.invokeBlockchain("invoke", new String[] { "a", "b", "100" });
			String a = helper.queryBlockchain("query", new String[] { "a" });
			String b = helper.queryBlockchain("query", new String[] { "b" });
			logger.info("after invoke  a=" + a + ", invoke b=" + b);
		}
	}

	// StartMultiTask(1, 1);
	public static void StartMultiTask(int threadNumber, int loop) throws InterruptedException {
		final CountDownLatch countDownLatch = new CountDownLatch(threadNumber);
		for (int i = 0; i < threadNumber; i++) {
			final int threadID = i;
			new Thread() {
				public void run() {
					try {
						LoopInvoke(loop);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					logger.info("threadID:[%s] finished!!", threadID);
					countDownLatch.countDown();
				}
			}.start();
		}

		countDownLatch.await();
		logger.info("main thread finished!!");
	}
}

39.1.6.7. 運行結果

2018-09-26 09:58:19,065 WARN [org.hyperledger.fabric.sdk.helper.Config] - Failed to load any configuration from: config.properties. Using toolkit defaults
2018-09-26 09:58:24,254 INFO [cn.netkiller.fabric.FabricHelper] - Finished transaction with transaction id f969f5785acaeab87c8471190ece5231adb54575410293bdcd5f00d227eb24b7: [a, b, 100]
2018-09-26 09:58:24,322 INFO [cn.netkiller.fabric.FabricHelper] - Query payload from peer peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0-0.peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0.default.svc.cluster.local returned -500
2018-09-26 09:58:24,386 INFO [cn.netkiller.fabric.FabricHelper] - Query payload from peer peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0-0.peer-23e50b60552eb5b6f32d3c1563305dd4530dc2f0.default.svc.cluster.local returned 800
2018-09-26 09:58:24,386 INFO [cn.netkiller.fabric.Main] - after invoke  a=-500, invoke b=800

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章