转载

原 荐 Hyperledger Fabric Java SDK Demo

Netkiller Blockchain 手札

Mr. Neo Chan, 陈景峯(BG7NYT)

中国广东省深圳市望海路半岛城邦三期

518067

+86 13113668890

<netkiller@msn.com>

文档始创于2018-02-10

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

版权声明

转载请与作者联系,转载时请务必标明文章原始出处和作者信息及本声明。

原 荐 Hyperledger Fabric Java SDK Demo
http://www.netkiller.cn
http://netkiller.github.io
http://netkiller.sourceforge.net
原 荐 Hyperledger Fabric Java SDK Demo
微信订阅号 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
原文  https://my.oschina.net/neochen/blog/2209277
正文到此结束
Loading...