Home | 简体中文 | 繁体中文 | 杂文 | 知乎专栏 | 51CTO学院 | CSDN程序员研修院 | Github | OSChina 博客 | 腾讯云社区 | 阿里云栖社区 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏多维度架构

第 39 章 BaaS (Blockchain as a Service) 平台

目录

39.1. Huawei BCS
39.1.1. 创建 BCS 服务
39.1.2. 管理通道
39.1.3. 安装链码
39.1.4. 下载 SDK 配置
39.1.5. 配置 SDK 文件
39.1.6. Fabric Java SDK Demo
39.1.6.1. Maven pom.xml 文件
39.1.6.2. chaincode_example02.go
39.1.6.3. bcs-whbsxu-sdk-config.yaml
39.1.6.4. FabricHelper.java
39.1.6.5. FabricUser.java
39.1.6.6. Main.java
39.1.6.7. 运行结果

39.1. Huawei BCS

华为的 Hyperledger Fabric BaaS 尚处在测试阶段,申请地址是 https://www.huaweicloud.com/product/bcs.html 服务可以免费申请,但是需要

39.1.1. 创建 BCS 服务

打开网址 https://www.huaweicloud.com/product/bcs.html

点击按钮 “立即体验”

点击“购买区块链服务”按钮

共识策略选择 Kafka(CFT), 输入链代码初始管理密码。

这里可以创建通道,也可以略过,后面可以创建。

经过一段时间初始化云主机,最终完成 BCS 创建。

39.1.2. 管理通道

创建通道,输入通道名称和描述,点击确定按钮。

创建好的通道,会显示“暂无节点加入”,点击右边 “加入节点” 连接

选择加入组织的数量

节点添加完毕

39.1.3. 安装链码

首先将 chaincode 源码压缩成 zip 文件

			
neo@MacBook-Pro ~/chaincode % zip token.zip token.go
  adding: token.go (deflated 82%)
  
neo@MacBook-Pro ~/chaincode % ls token.*
token.go  token.zip			
			
		

点击右边 “链代码管理” 按钮

进入链码管理界面

Organization 选择组织, Peer 选择节点,点击 “Install Chaincode” 按钮。

输入连码名称、版本、并上传 链码对应的 zip 文件。

链码安装成功

实例化链码

输入调用的函数,和传递的参数,点击 OK 按钮

执行成功

39.1.4. 下载 SDK 配置

首先下载证书

点击左侧 V 符号,展开项目可以看到下载证书。点击 order 和 organization 后面的 "下载管理员证书"

选择 “下载 SDK 配置”

链代码名称是之前安装链码时输入的名称

链代码版本是当前的链码版本

证书存放根路径填写: /Users/neo/fabric/crypto (这里是本地证书路径,java / golang sdk 程序会访问这些证书。)

点击下载按钮后得到一个 bcs-itetze-sdk-config.zip 文件,解压开 bcs-itetze-sdk-config.yaml

39.1.5. 配置 SDK 文件

准备证书,下载 bcs-itetze-orderer-admin.zip 和 organization-admin.zip 两个证书压缩包。

bcs-itetze-orderer-admin.zip 文件解压后放置到 /Users/neo/fabric/crypto/ 目录中

organization-admin.zip 解压放置到 /Users/neo/fabric/crypto/ 目录

			
neo@MacBook-Pro ~ % cd fabric/crypto 

neo@MacBook-Pro ~/fabric/crypto % pwd
/Users/neo/fabric/crypto

neo@MacBook-Pro ~/fabric/crypto % ls 
266d0f487933503a48f0ab728b85d5b469cb2b79.peer-266d0f487933503a48f0ab728b85d5b469cb2b79.default.svc.cluster.local
7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local
			
		

打开 bcs-itetze-sdk-config.yaml 文件,下面是 SDK 配置文件的内容。

			
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: 266d0f487933503a48f0ab728b85d5b469cb2b79

  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:
  
  example:
    orderers:
      
      - orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-0.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local
      
      - orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-1.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local
      
      - orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-2.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local
      
      - orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-3.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local
      
      - orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-4.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local
      
    peers:
      
      peer-266d0f487933503a48f0ab728b85d5b469cb2b79-3.peer-266d0f487933503a48f0ab728b85d5b469cb2b79.default.svc.cluster.local:
        endorsingPeer: true
        chaincodeQuery: true
        ledgerQuery: true
        eventSource: true
      
    chaincodes:
      - example02:1.0
  
organizations:
  
  266d0f487933503a48f0ab728b85d5b469cb2b79:
    mspid: 266d0f487933503a48f0ab728b85d5b469cb2b79MSP

    cryptoPath:  /Users/neo/fabric/crypto/266d0f487933503a48f0ab728b85d5b469cb2b79.peer-266d0f487933503a48f0ab728b85d5b469cb2b79.default.svc.cluster.local/msp
    tlsCryptoKeyPath: /Users/neo/fabric/crypto/266d0f487933503a48f0ab728b85d5b469cb2b79.peer-266d0f487933503a48f0ab728b85d5b469cb2b79.default.svc.cluster.local/tls/server.key
    tlsCryptoCertPath: /Users/neo/fabric/crypto/266d0f487933503a48f0ab728b85d5b469cb2b79.peer-266d0f487933503a48f0ab728b85d5b469cb2b79.default.svc.cluster.local/tls/server.crt

    peers:
      
      - peer-266d0f487933503a48f0ab728b85d5b469cb2b79-3.peer-266d0f487933503a48f0ab728b85d5b469cb2b79.default.svc.cluster.local
      
    certificateAuthorities:
      - ca-org1

    adminPrivateKey:
      pem: "-----BEGIN PRIVATE KEY----- <etc>"
    signedCert:
      path: "/tmp/somepath/signed-cert.pem"
  
  ordererorg:
      mspID: "7d8abfe15c3f1389f0468d90e27a382d0bd90b3fMSP"

      cryptoPath: /Users/neo/fabric/crypto/7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local/msp
#orderer eip: 49.4.85.126
orderers:
  
  orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-0.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local:
    url: grpcs://orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-0.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local:30805

    grpcOptions:
      ssl-target-name-override: orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-0.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local
      grpc-max-send-message-length: 15

    tlsCACerts:
      path: /Users/neo/fabric/crypto/7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local/msp/tlscacerts/tlsca.7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-cert.pem
  
  orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-1.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local:
    url: grpcs://orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-1.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local:30806

    grpcOptions:
      ssl-target-name-override: orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-1.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local
      grpc-max-send-message-length: 15

    tlsCACerts:
      path: /Users/neo/fabric/crypto/7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local/msp/tlscacerts/tlsca.7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-cert.pem
  
  orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-2.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local:
    url: grpcs://orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-2.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local:30807

    grpcOptions:
      ssl-target-name-override: orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-2.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local
      grpc-max-send-message-length: 15

    tlsCACerts:
      path: /Users/neo/fabric/crypto/7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local/msp/tlscacerts/tlsca.7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-cert.pem
  
  orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-3.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local:
    url: grpcs://orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-3.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local:30808

    grpcOptions:
      ssl-target-name-override: orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-3.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local
      grpc-max-send-message-length: 15

    tlsCACerts:
      path: /Users/neo/fabric/crypto/7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local/msp/tlscacerts/tlsca.7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-cert.pem
  
  orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-4.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local:
    url: grpcs://orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-4.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local:30809

    grpcOptions:
      ssl-target-name-override: orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-4.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local
      grpc-max-send-message-length: 15

    tlsCACerts:
      path: /Users/neo/fabric/crypto/7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local/msp/tlscacerts/tlsca.7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-cert.pem
  
#peer eip: 49.4.85.126
peers:
  
  peer-266d0f487933503a48f0ab728b85d5b469cb2b79-3.peer-266d0f487933503a48f0ab728b85d5b469cb2b79.default.svc.cluster.local:
    url: grpcs://peer-266d0f487933503a48f0ab728b85d5b469cb2b79-3.peer-266d0f487933503a48f0ab728b85d5b469cb2b79.default.svc.cluster.local:30608

    eventUrl: grpcs://peer-266d0f487933503a48f0ab728b85d5b469cb2b79-3.peer-266d0f487933503a48f0ab728b85d5b469cb2b79.default.svc.cluster.local:30708

    grpcOptions:
      ssl-target-name-override: peer-266d0f487933503a48f0ab728b85d5b469cb2b79-3.peer-266d0f487933503a48f0ab728b85d5b469cb2b79.default.svc.cluster.local
      grpc.http2.keepalive_time: 15

    tlsCACerts:
      path: /Users/neo/fabric/crypto/266d0f487933503a48f0ab728b85d5b469cb2b79.peer-266d0f487933503a48f0ab728b85d5b469cb2b79.default.svc.cluster.local/msp/tlscacerts/tlsca.266d0f487933503a48f0ab728b85d5b469cb2b79-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
			
		

配置 organizations 证书

			
    adminPrivateKey:
      pem: "-----BEGIN PRIVATE KEY----- <etc>"
      path: "/Users/neo/fabric/crypto/266d0f487933503a48f0ab728b85d5b469cb2b79.peer-266d0f487933503a48f0ab728b85d5b469cb2b79.default.svc.cluster.local/msp/keystore"
    signedCert:
      path: "/Users/neo/fabric/crypto/266d0f487933503a48f0ab728b85d5b469cb2b79.peer-266d0f487933503a48f0ab728b85d5b469cb2b79.default.svc.cluster.local/msp/signcerts/Admin@266d0f487933503a48f0ab728b85d5b469cb2b79.peer-266d0f487933503a48f0ab728b85d5b469cb2b79.default.svc.cluster.local-cert.pem"
			
		

找到 peers 和 orderers 的主机名

			
#peer eip: 49.4.85.126
peers:
  
  peer-266d0f487933503a48f0ab728b85d5b469cb2b79-3.peer-266d0f487933503a48f0ab728b85d5b469cb2b79.default.svc.cluster.local:
  
#orderer eip: 49.4.85.126
orderers:
  
  orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-0.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local:			
			
		

打开 /etc/hosts 文件,添加主机解析地址

			
49.4.85.126     peer-266d0f487933503a48f0ab728b85d5b469cb2b79-3.peer-266d0f487933503a48f0ab728b85d5b469cb2b79.default.svc.cluster.local

49.4.85.126     orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-0.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local
49.4.85.126     orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-1.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local
49.4.85.126     orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-2.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local
49.4.85.126     orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-3.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local
49.4.85.126     orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f-4.orderer-7d8abfe15c3f1389f0468d90e27a382d0bd90b3f.default.svc.cluster.local
			
		

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