Fabric 1.3新功能介绍及环境搭建

第一部分:新功能介绍

功能1. 使用Identity Mixer实现MSP(Membership Service Prodiver)

       这是一种通过使用零知识证明来保持身份匿名和不可链接的方法。工具idexmigen可以在测试环境中生成Identity Mixer凭证。

1.1零知识证明

     零知识证明,英文名为Zero-Knowledge Proof,是由S.Goldwasser、S.Micali以及C.Rackoff在20世纪80年代初提出的。它指的是证明者(被验证者)能够在不向验证者提供任何有用的信息的情况下,使验证者相信某个论断是正确的。

零知识证明实质上是一种涉及两方或更多方的协议,即两方或更多方完成一项任务所需采取的一系列步骤。

1.2 什么是Idemix?

       Idemix是一个加密协议套件,它提供强大的身份验证以及隐私保护功能,如匿名,无需揭示交易者身份即可进行交易,以及不可链接性,即单个身份发送多个交易的能力,而不会泄露交易是通过相同的身份发送的。

Idemix流中涉及三个参与者:用户,发行者和 验证者。

发行者证明将一组用户的属性以数字证书的形式发布,以下称为“凭证”。

用户稍后生成拥有凭证的“ 零知识证明 ”,并且能够选择性地公开用户选择显示的属性。它不会向验证者,发行者或任何其他人显示其他信息。

1.3 如何将Idemix与Hyperledger Fabric一起使用

要在Hyperledger Fabric中使用Idemix,需要以下三个基本步骤:

发行者:Fabric CA 或者 idemixgen

验证者:Idemix MSP 

用户  :java SDK类org.hyperledger.fabric_ca.sdk.HFCAClient
(例如:IdemixEnrollment idemixEnrollment = hfcaClient.idemixEnroll(x509enrollment, "idemixMSPID1"))

1.3.1 Fabric-ca的安装过程

Fabric-ca在Ubuntu和Centos上面的安装

第一步:安装系统组件包

         sudo apt install libtool libltdl-dev

如果在Centos上面安装,则需要执行命令 yum install libtool libltdl-dev,其他的步骤相同。

第二步:下载源代码并编译

         cd $GOPATH/src/github.com/hyperledger

         git clone http://gerrit.hyperledger.org/r/fabric-ca

         cd $GOPATH/src/github.com/hyperledger/fabric-ca

               查看版本:

               cd fabric-ca/

               git branch -a (切换如:git checkout release-1.3)

         make fabric-ca-server

                   报错:

                   [root@localhost fabric-ca]# make fabric-ca-server

                   Building fabric-ca-server in bin directory ...

                   # github.com/hyperledger/fabric-ca/vendor/github.com/miekg/pkcs11

                   vendor/github.com/miekg/pkcs11/pkcs11.go:26:18: fatal error: ltdl.h: No such file or                 directory

                 #include <ltdl.h>

                  ^

                   compilation terminated.

                   make: *** [bin/fabric-ca-server] 错误 2

解决:

         如果在ubunt操作系统中,只需安装:apt install libltdl3-dev

         如果在centos操作系统中,只需安装:yum install libtool-ltdl-devel

         make fabric-ca-server

         make fabric-ca-client

第三步:安装编译好的可执行文件

         cd  $GOPATH/src/github.com/hyperledger/fabric-ca/bin

         cp $GOPATH/src/github.com/hyperledger/fabric-ca/bin/* /usr/local/bin

         chmod -R 775  /usr/local/bin/fabric-ca-server

         chmod -R 775  /usr/local/bin/fabric-ca-client

第四步骤:检查

         fabric-ca-server version

         fabric-ca-server version

显示版本信息为安装正确。

2.fabric-ca-server的初始化

1.3.2 Fabric-ca-server的初始化

第一步:创建文件夹

mkdir -p /opt/hyperledger/fabric-ca-server

cd $GOPATH/src/github.com/hyperledger/fabric-ca

第二步:服务器初始化

fabric-ca-server服务器初始化的命令如下:

fabric-ca-server init -b admin:adminpw

-b 参数后面的是fabric-ca-server服务器管理账号的用户名和密码

启动fabric-ca-server:

fabric-ca-server start -H /opt/hyperledger/fabric-ca --boot  admin:adminpw

1.3.3  Identity Mixer MSP配置生成器(idemixgen)

Fabric CA (version 1.3 or later)在Fabric-ca-sever初始化的目录下会生成IssuerPublicKey和IssuerRevocationPublicKey,会在下一步使用。

1.3.4 CA密钥生成

cd $GOPATH/src/github.com/hyperledger/fabric-ca

idemixgen ca-keygen

会在fabric-ca下生成msp目录等

1.3.5 添加默认签名者

生成ca和msp目录后 ,可以将目录中指定的默认签名者添加到配置

命令例如:idemixgen signerconfig -u OrgUnit1 --admin -e "johndoe" -r 1234
(签名者是组织单元“OrgUnit1”的成员,注册标识为“johndoe”,撤销句柄为“1234”,这是一个管理员)
$ idemixgen signerconfig -h
usage: idemixgen signerconfig [<flags>]
 
Generate a default signer for this Idemix MSP
 
Flags:
    -h, --help               Show context-sensitive help (also try --help-long and --help-man).
    -u, --org-unit=ORG-UNIT  The Organizational Unit of the default signer
    -a, --admin              Make the default signer admin
    -e, --enrollment-id=ENROLLMENT-ID
                             The enrollment id of the default signer
    -r, --revocation-handle=REVOCATION-HANDLE
                             The handle used to revoke this signer

功能2. 设置密钥级背书策略

允许每个密钥级的背书策略覆盖默认的链码级背书策略。

在Fabric1.3版本之前常见的背书策略是:

实例化或者升级chaincode代码时设置的,例如:

peer chaincode instantiate -C <channelid> -n mycc -P "AND('Org1.peer', 'Org2.peer')"
 

peer chaincode instantiate -o  orderer.qklszzn.com:7050 -C roberttestchannel -n r_test_cc6 -v 1.0 -c '{"Args":["init","a","100","b","200"]}' -P "OR      ('Org1MSP.member','Org2MSP.member')"

如果未指定,默认背书策略:
 “OR('Org1.member','Org2.member')”。意思是组织1或组织2的任何成员
  • 'Org0.admin':Org0的任何管理员
  • 'Org1.member':Org1的任何成员
  • 'Org1.client':Org1的任何客户端
  • 'Org1.peer':Org1的任何peer节点

在Fabric1.3版本中 shim API 提供了设置和获取背书策略的方法

SetStateValidationParameter(key string, ep []byte) error
GetStateValidationParameter(key string) ([]byte, error)

对于私有数据有如下方法:

SetPrivateDataValidationParameter(collection, key string, ep []byte) error
GetPrivateDataValidationParameter(collection, key string) ([]byte, error)

为了帮助设置背书策略并将其编组为验证参数字节数组,shim提供了便利功能,允许智能合约开发人员根据组织的MSP标识符处理背书策略:

type KeyEndorsementPolicy interface {
    // Policy returns the endorsement policy as bytes
    Policy() ([]byte, error)
 
    // AddOrgs adds the specified orgs to the list of orgs that are required
    // to endorse
    AddOrgs(roleType RoleType, organizations ...string) error
 
    // DelOrgs delete the specified channel orgs from the existing key-level endorsement
    // policy for this KVS key. If any org is not present, an error will be returned.
    DelOrgs([]string) error
 
    // DelAllOrgs removes any key-level endorsement policy from this KVS key.
    DelAllOrgs() error
 
    // ListOrgs returns an array of channel orgs that are required to endorse changes
    ListOrgs() ([]string, error)
}

用法:

要为密钥设置背书策略,其中需要两个特定组织来背书密钥更改,将两个组织MSPIDs传递给AddOrgs(),然后调用Policy()以构造背书策略字节数组,传递给SetStateValidationParameter()。

功能3. 使用分页查询CouchDB状态数据库

客户端现在可以从智能合约查询中浏览结果集,从而可以支持具有高性能的大型结果集。

分页是通过指定pagesize(单页数据条数)和bookmark(查询起始点),代码如下:

func (t *SimpleChaincode) queryMarblesWithPagination(stub shim.ChaincodeStubInterface, args []string) pb.Response {
 
      //   0
      // "queryString"
      if len(args) < 3 {
              return shim.Error("Incorrect number of arguments. Expecting 3")
      }
 
      queryString := args[0]
      //return type of ParseInt is int64
      pageSize, err := strconv.ParseInt(args[1], 10, 32)
      if err != nil {
              return shim.Error(err.Error())
      }
      bookmark := args[2]
 
      queryResults, err := getQueryResultForQueryStringWithPagination(stub, queryString, int32(pageSize), bookmark)
      if err != nil {
              return shim.Error(err.Error())
      }
      return shim.Success(queryResults)
}

功能4. Chaincode为开发人员

作为对用Go和node编写的智能合约的当前Fabric支持的补充。现在支持Java,1.3版本将明确可用java进行智能合约的编写。

功能5. 基于peer节点通道的事件服务

基于peer通道的事件服务本身并不是新概念(它首次出现在v1.1中),但是v1.3版本标志着旧事件中心的结束。在升级到v1.3之前,使用旧事件中心的应用程序必须切换到新的基于peer通道的事件服务。

在Fabric1.1和1.2的版本中 core.yaml中有EventHub相关配置,如下

    # EventHub related configuration

    events:

        # The address that the Event service will be enabled on the peer

        address: 0.0.0.0:7053

        # total number of events that could be buffered without blocking send

        buffersize: 100

        # timeout duration for producer to send an event.

        # if < 0, if buffer full, unblocks immediately and not send

        # if 0, if buffer full, will block and guarantee the event will be sent out

        # if > 0, if buffer full, blocks till timeout

        timeout: 10ms

        # timewindow is the acceptable difference between the peer's current

        # time and the client's time as specified in a registration event

        timewindow: 15m

        # Keepalive settings for peer server and clients

        keepalive:

            # MinInterval is the minimum permitted time in seconds which clients

            # can send keepalive pings.  If clients send pings more frequently,

            # the events server will disconnect them

            minInterval: 60s

在1.3的版本,却没有了EventHub相关配置。

但是并不影响使用,依然可以通过

 private static EventHub eventHub;

 private static PeerEvents.Event goodEventBlock;

eventHub = new EventHub("test", "grpc://lh:99", null, null);
goodEventBlock = PeerEvents.Event.newBuilder().setBlock(blockBuilder).build();
BlockEvent be = new BlockEvent(eventHub, goodEventBlock);
channel.registerBlockListener(blockEvent -> {
    log.debug("========================Event事件监听========================");
       try {
           org.getBlockListener().received(execBlockInfo(blockEvent));
                } catch (Exception e) {
                    e.printStackTrace();
                    org.getBlockListener().received(getFailFromString(e.getMessage()));
   }
log.debug("========================Event事件监听结束========================");
});

 

 

 

 

 

 

第二部分:Fabric1.3环境搭建

第一章 准备阶段

1.1 win7 64位操作系统

1.2 虚拟机镜像:CentOS-7-x86_64-LiveGNOME-1804.iso

1.3 产品:VMware® Workstation 12 Pro  版本:12.5.9 build-7535481

第二章 虚拟机环境准备阶段

2.1 开启SSH服务

              systemctl start sshd service

              随系统一起启动SSH服务

              systemctl enable  sshd.service

2.2 yum install update

2.3 CentOS升内核至最新

2.4 yum -y install zip unzip

2.5 yum install perl openssh git

2.6 yum -y install wget

2.7 下载golang

wget https://storage.googleapis.com/golang/go1.10.linux-amd64.tar.gz

2.8 sudo tar -C /usr/local -xzf go1.11.2.linux-amd64.tar.gz

2.9 sudo vi /etc/profile                  

                     export GOROOT=/usr/local/go

                     export PATH=$PATH:$GOROOT/bin

                     export GOPATH=/opt/gopath

2.10 source  /etc/profile

2.11 yum install docker python-pip

2.12 下载pip

wget"https://pypi.python.org/packages/source/p/pip/pip-1.5.4.tar.gz#md5=834b2904f92d46aaa333267fb1c922bb" --no-check-certificate

 或者 

curl "https://bootstrap.pypa.io/get-pip.py" -o "get-pip.py" python get-pip.py

2.13 tar -C /usr/local -axf pip-1.5.4.tar.gz

2.14 cd /usr/local/pip-1.5.4/

2.15 python setup.py install

2.16 yum install docker python-pip

2.17 pip install --upgrade pip

2.18 pip install docker-compose

2.19 sudo service docker start

2.20 sudo yum install gcc

2.21 导入镜像

                               docker pull hyperledger/fabric-baseimage:latest 

                               docker pull hyperledger/fabric-baseos:latest

                               docker pull hyperledger/fabric-ccenv:latest

安装java智能合约还需要导入两个镜像:

               docker pull docker.io/hyperledger/fabric-javaenv:amd64-1.3.0

               docker pull docker.io/hyperledger/fabric-tools: latest                                           

docker 镜像导入导出命令参考

docker save -o nginx.tar nginx:latest

docker load -i nginx.tar

第三章 区块链环境搭建

第一步:创建目录并下载代码

mkdir -p $GOPATH/src/github.com/hyperledger

cd $GOPATH/src/github.com/hyperledger

git clone https://github.com/hyperledger/fabric

 

 

 

查看版本:

cd fabric/

git branch -a (切换如:git checkout release-1.2)

第二步:安装相关依赖软件

go get github.com/golang/protobuf/protoc-gen-go

mkdir -p $GOPATH/src/github.com/hyperledger/fabric/build/docker/gotools/bin

cp  $GOPATH/bin/protoc-gen-go $GOPATH/src/github.com/hyperledger/fabric/build/docker/gotools/bin

注意:go get 之后编译好的文件会存放到环境变量$GOBIN对应的目录中,如果没有设置$GOBIN的值,系统默认将生成的文体存放到$GOPATH/bin下面.

第三步:编译Fabric的模块

进入到Fabirc源码所在的文件夹,执行以下命令可以一次完成Fabric5个主要模块的编译过程,具体的命令如下所示:

cd $GOPATH/src/github.com/hyperledger/fabric

make release

make docker(可能报错,但是不影响)

对于Macos系统,在编译之前需要进行以下设置:

  • 打开文件$GOPATH/src/github.com/hyperledger/fabric/Makefile
  • 找到其中的第一个GO_LDFLAGS字符串的位置,在该字符串所在行的在行的末尾加上字符串-s
  • 保存文件Makefile

上述命令执行完成之后,会自动将将编译好的二进制文件存放在以下路径中:

  • Ubuntu和Centos系统的存放路径

$GOPATH/src/github.com/hyperledger/fabric/release/linux-amd64/bin

  • Macos系统的存放路径

$GOPATH/src/github.com/hyperledger/fabric/release/darwin-amd64/bin

第四步:Fabric模块的安装

编译完成之后,这些模块已经已经可以被运行了,但是目前只能在编译文件所在的文件夹中运行这些模块,这样是非常不方便的。为了更加方便的使用这些模块,可以通过下面的命令将这些模块的可执行文件复制到系统目录中,这样在系统中的任何路径下面都运行这些可执行这些模块。

Ubuntu和Centos将Fabric模块编译后的文件复制到系统文件夹中的方法如下:

cp $GOPATH/src/github.com/hyperledger/fabric/release/linux-amd64/bin/* /usr/local/bin

Macos上面将Fabric模块编译后的文件复制到系统文件夹中的方法如下:

cp $GOPATH/src/github.com/hyperledger/fabric/release/darwin-amd64/bin/* /usr/local/bin

复制成功之后通过以下命令修改文件的执行权限,否则无法执行。

sudo chmod -R 775  /usr/local/bin/configtxgen

sudo chmod -R 775  /usr/local/bin/configtxlator

sudo chmod -R 775  /usr/local/bin/cryptogen

sudo chmod -R 775  /usr/local/bin/peer

sudo chmod -R 775  /usr/local/bin/orderer

通过上面这些命令之后,可以在系统的任何路径下面运行这些模块了。下面通过一组命令来进检查安装过程是否成功。

第五步: 检查安装步骤

采用 version 命令行选项

Fabric的模块

模块名称

功能

peer

主节点模块,负责存储区块链数据,运行维护链码

orderer

交易打包、排序模块

cryptogen

组织和证书生成模块

configtxgedn

区块和交易生成模块

configtxlator

区块和交易解析模块

快速启动Fabric一个Fabric应用

生成Fabric需要的证书文件

本例中我们将配置文件和生成的证书文件放在文件夹/opt/hyperledger/fabricconfig中。

创建存放证书的文件夹的命令如下所示:

mkdir -p /opt/hyperledger/fabricconfig

cryptogen提供了一个命令可以获取cryptogen模块所需要的配置文件的样式,该命令如下所示:

cryptogen showtemplate

可以把上述命令生成的内容复制到一个文件中稍加修改即可使用。

本例中我们所使用的配置文件的内容如下所示:

OrdererOrgs:

  - Name: Orderer

    Domain: qklszzn.com

    Specs:

      - Hostname: orderer

PeerOrgs:

  - Name: Org1

    Domain: org1.qklszzn.com

    Template:

      Count: 2

    Users:

      Count: 3

  - Name: Org2

    Domain: org2.qklszzn.com

    Template:

      Count: 2

    Users:

      Count: 2

注意Domain属性

将上述文件的内容保存到文件夹/opt/hyperledger/fabricconfig中,配置文件命名为:crypto-config.yaml。保存之后执行如下命令:

cd /opt/hyperledger/fabricconfig

cryptogen generate --config=crypto-config.yaml --output ./crypto-config

该命令执行完成之后我们会发现在文件夹/opt/hyperledger/fabricconfig中会新增加一个文件夹crypto-config,里面存放有本例的相关配置文件,可以通过tree命令查看生成证书文件的内容。

执行 : yum install tree

执行命令 tree -L 5 显示如下:

├── crypto-config

│   ├── ordererOrganizations

│   │   └── qklszzn.com

│   │       ├── ca

│   │       ├── msp

│   │       ├── orderers

│   │       ├── tlsca

│   │       └── users

│   └── peerOrganizations

│       ├── org1.qklszzn.com

│       │   ├── ca

│       │   ├── msp

│       │   ├── peers

│       │   ├── tlsca

│       │   └── users

│       ├── org2.qklszzn.com

│       │   ├── ca

│       │   ├── msp

│       │   ├── peers

│       │   ├── tlsca

│       │   └── users

通过上述步骤所有的证书文件都已经生成完毕,现在需要将测试域名映射到本机的IP地址上面,否则后面的操作可能会出现错误。

执行以下命令以便提取相关的域名,

cd /opt/hyperledger/fabricconfig

 

tree -L 5

 

在上述命令显示的内容中提取出后缀为 qklszzn.com域名。本例中提取信息如下:

orderer.qklszzn.com

peer0.org1.qklszzn.com

peer1.org1.qklszzn.com

peer3.org1.qklszzn.com

peer0.org2.qklszzn.com

peer1.org2.qklszzn.com

打开端映射文件

vi /etc/hosts

在打开的文件中设置如下内容

192.168.43.105 orderer.qklszzn.com

192.168.43.105 peer0.org1.qklszzn.com

192.168.43.105 peer1.org1.qklszzn.com

192.168.43.105 peer3.org1.qklszzn.com

192.168.43.105 peer0.org2.qklszzn.com

192.168.43.105 peer1.org2.qklszzn.com

 

输入以上内容之后保存/etc/hosts文件,然后用ping命令测试以下配置是否正确。

注意:192.168.43.105为本机的IP地址

第六步 : 创始块的生成

6.1系统创始块的生成

Fabric是基于区块链的分布式账本,每个账本都拥有自己的区块链,账本的区块链中会存储账本的交易,账本区块链中的第一个区块是个例外,该区块不存在交易数据而是存储配置信息,通常将账本的第一个区块成为创始块。综上所述,Fabric中账本的第一个区块是需要手动生成的。configtxgen模块是专门负责生成系统的创始块和Channel的创始块。configtxgen模块也需要一个配置文件来定义相关的属性。

在Fabric源码中提供的configtxgen模块所需要的配置文件的例子。该文件的路径是$GOPATH/src/github.com/hyperledger/fabric/sampleconfig,在这个目录下面有一个名为configtx.yaml的文件,对这个文件进行修即可使用。由于创始块文件是提供给Orderer节点使用,因此我们创建文件一个文件夹来存在Orderer节点相关的文件。文件夹创建之后把样例配置文件复制到该文件夹中。

创建存放configtxgen模块相关配置文件的文件夹的命令如下所示:

mkdir -p /opt/hyperledger/order/

cp -r $GOPATH/src/github.com/hyperledger/fabric/sampleconfig/configtx.yaml   /opt/hyperledger/order

cd /opt/hyperledger/order

对configtx.yaml进行修改,修改后的内容如下所示:

 # Copyright IBM Corp. All Rights Reserved.

#

# SPDX-License-Identifier: Apache-2.0

#

 

---

################################################################################

#

#   ORGANIZATIONS

#

#   This section defines the organizational identities that can be referenced

#   in the configuration profiles.

#

################################################################################

Organizations:

    - &OrdererOrg

        Name: OrdererOrg

        ID: OrdererMSP

        MSPDir: /opt/hyperledger/fabricconfig/crypto-config/ordererOrganizations/qklszzn.com/msp

    - &Org1

        Name: Org1MSP

        ID: Org1MSP

        MSPDir: /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/msp

        Policies: &SampleOrgPolicies

            Readers:

                Type: Signature

                Rule: "OR('Org1MSP.member')"

            Writers:

                Type: Signature

                Rule: "OR('Org1MSP.member')"

            Admins:

                Type: Signature

                Rule: "OR('Org1MSP.admin')"

        AnchorPeers:

            - Host: peer0.org1.qklszzn.com

              Port: 7051

    - &Org2

        Name: Org2MSP

        ID: Org2MSP

        MSPDir: /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org2.qklszzn.com/msp

        Policies: &SampleOrgPolicies

            Readers:

                Type: Signature

                Rule: "OR('Org2MSP.member')"

            Writers:

                Type: Signature

                Rule: "OR('Org2MSP.member')"

            Admins:

                Type: Signature

                Rule: "OR('Org2MSP.admin')"

        AnchorPeers:

            - Host: peer0.org2.qklszzn.com

              Port: 7051             

Capabilities:

    Channel: &ChannelCapabilities

        V1_3: true

    Orderer: &OrdererCapabilities

        V1_1: true

    Application: &ApplicationCapabilities

        V1_3: true

        V1_2: false

        V1_1: false

 

Application: &ApplicationDefaults

    ACLs: &ACLsDefault

        # ACL policy for lscc's "getid" function

        lscc/ChaincodeExists: /Channel/Application/Readers

 

        # ACL policy for lscc's "getdepspec" function

        lscc/GetDeploymentSpec: /Channel/Application/Readers

 

        # ACL policy for lscc's "getccdata" function

        lscc/GetChaincodeData: /Channel/Application/Readers

 

        # ACL Policy for lscc's "getchaincodes" function

        lscc/GetInstantiatedChaincodes: /Channel/Application/Readers

 

        #---Query System Chaincode (qscc) function to policy mapping for access control---#

 

        # ACL policy for qscc's "GetChainInfo" function

        qscc/GetChainInfo: /Channel/Application/Readers

 

        # ACL policy for qscc's "GetBlockByNumber" function

        qscc/GetBlockByNumber: /Channel/Application/Readers

 

        # ACL policy for qscc's  "GetBlockByHash" function

        qscc/GetBlockByHash: /Channel/Application/Readers

 

        # ACL policy for qscc's "GetTransactionByID" function

        qscc/GetTransactionByID: /Channel/Application/Readers

 

        # ACL policy for qscc's "GetBlockByTxID" function

        qscc/GetBlockByTxID: /Channel/Application/Readers

 

        #---Configuration System Chaincode (cscc) function to policy mapping for access control---#

 

        # ACL policy for cscc's "GetConfigBlock" function

        cscc/GetConfigBlock: /Channel/Application/Readers

 

        # ACL policy for cscc's "GetConfigTree" function

        cscc/GetConfigTree: /Channel/Application/Readers

 

        # ACL policy for cscc's "SimulateConfigTreeUpdate" function

        cscc/SimulateConfigTreeUpdate: /Channel/Application/Readers

 

        #---Miscellanesous peer function to policy mapping for access control---#

 

        # ACL policy for invoking chaincodes on peer

        peer/Propose: /Channel/Application/Writers

 

        # ACL policy for chaincode to chaincode invocation

        peer/ChaincodeToChaincode: /Channel/Application/Readers

 

        #---Events resource to policy mapping for access control###---#

 

        # ACL policy for sending block events

        event/Block: /Channel/Application/Readers

 

        # ACL policy for sending filtered block events

        event/FilteredBlock: /Channel/Application/Readers

 

    # Organizations lists the orgs participating on the application side of the

    # network.

    Organizations:

    Policies: &ApplicationDefaultPolicies

        Readers:

            Type: ImplicitMeta

            Rule: "ANY Readers"

        Writers:

            Type: ImplicitMeta

            Rule: "ANY Writers"

        Admins:

            Type: ImplicitMeta

            Rule: "MAJORITY Admins"

 

    Capabilities:

        <<: *ApplicationCapabilities

 

Orderer: &OrdererDefaults

    OrdererType: solo

    Addresses:

        - orderer.qklszzn.com:7050

 

    # Batch Timeout: The amount of time to wait before creating a batch.

    BatchTimeout: 2s

    BatchSize:

        MaxMessageCount: 10

        AbsoluteMaxBytes: 10 MB

        PreferredMaxBytes: 512 KB

 

    # Max Channels is the maximum number of channels to allow on the ordering

    # network. When set to 0, this implies no maximum number of channels.

    MaxChannels: 0

 

    Kafka:

        # Brokers: A list of Kafka brokers to which the orderer connects. Edit

        # this list to identify the brokers of the ordering service.

        # NOTE: Use IP:port notation.

        Brokers:

            - 127.0.0.1:9092

 

    # EtcdRaft defines configuration which must be set when the "etcdraft"

    # orderertype is chosen.

    EtcdRaft:

        Consenters:

            - Host: raft0.example.com

              Port: 7050

              ClientTLSCert: path/to/ClientTLSCert0

              ServerTLSCert: path/to/ServerTLSCert0

            - Host: raft1.example.com

              Port: 7050

              ClientTLSCert: path/to/ClientTLSCert1

              ServerTLSCert: path/to/ServerTLSCert1

            - Host: raft2.example.com

              Port: 7050

              ClientTLSCert: path/to/ClientTLSCert2

              ServerTLSCert: path/to/ServerTLSCert2

 

    # Organizations lists the orgs participating on the orderer side of the

    # network.

    Organizations:

    Policies:

        Readers:

            Type: ImplicitMeta

            Rule: "ANY Readers"

        Writers:

            Type: ImplicitMeta

            Rule: "ANY Writers"

        Admins:

            Type: ImplicitMeta

            Rule: "MAJORITY Admins"

        # BlockValidation specifies what signatures must be included in the block

        # from the orderer for the peer to validate it.

        BlockValidation:

            Type: ImplicitMeta

            Rule: "ANY Writers"

 

    Capabilities:

        <<: *OrdererCapabilities

Channel: &ChannelDefaults

 

    Policies:

        # Who may invoke the 'Deliver' API

        Readers:

            Type: ImplicitMeta

            Rule: "ANY Readers"

        # Who may invoke the 'Broadcast' API

        Writers:

            Type: ImplicitMeta

            Rule: "ANY Writers"

        # By default, who may modify elements at this config level

        Admins:

            Type: ImplicitMeta

            Rule: "MAJORITY Admins"

 

    Capabilities:

        <<: *ChannelCapabilities

 

Profiles:

 

    TestTwoOrgsOrdererGenesis:

        <<: *ChannelDefaults

        Orderer:

            <<: *OrdererDefaults

            Organizations:

                - *OrdererOrg

        Consortiums:

            SampleConsortium:

                Organizations:

                    - *Org1

                    - *Org2

    TestTwoOrgsChannel:

        Consortium: SampleConsortium

        Application:

            <<: *ApplicationDefaults

            Organizations:

                - *Org1

                - *Org2

 

下面是Fabric 1.1版本的,对configtx.yaml进行修改,修改后的内容如下所示:

 

Profiles:

 

    TestTwoOrgsOrdererGenesis:

        Orderer:

            <<: *OrdererDefaults

            Organizations:

                - *OrdererOrg

        Consortiums:

            SampleConsortium:

                Organizations:

                    - *Org1

                    - *Org2

 

    TestTwoOrgsChannel:

        Consortium: SampleConsortium

        Application:

            <<: *ApplicationDefaults

            Organizations:

                - *Org1

                - *Org2

 

Organizations:

    - &OrdererOrg

        Name: OrdererOrg

        ID: OrdererMSP

        MSPDir: /opt/hyperledger/fabricconfig/crypto-config/ordererOrganizations/qklszzn.com/msp

 

    - &Org1

 

        Name: Org1MSP

        ID: Org1MSP

        MSPDir: /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/msp

        AnchorPeers:

            - Host: peer0.org1.qklszzn.com

              Port: 7051

 

    - &Org2

        Name: Org2MSP

        ID: Org2MSP

        MSPDir: /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org2.qklszzn.com/msp

        AnchorPeers:

            - Host: peer0.org2.qklszzn.com

              Port: 7051

 

Orderer: &OrdererDefaults

 

    OrdererType: solo

    Addresses:

        - orderer.qklszzn.com:7050

    BatchTimeout: 2s

 

    BatchSize:

        MaxMessageCount: 10

        AbsoluteMaxBytes: 98 MB

        PreferredMaxBytes: 512 KB

 

    Kafka:

        Brokers:

            - 127.0.0.1:9092

    Organizations:

 

Application: &ApplicationDefaults

 

    Organizations:

 

配置文件修改完成之后执行如下面命令生成创始块文件。

cd /opt/hyperledger/order

configtxgen -profile  TestTwoOrgsOrdererGenesis  -outputBlock  ./orderer.genesis.block

上述命令执行完成之后会在文件夹/opt/hyperledger/order中生成文件orderer.genesis.block。这是Fabric系统的创始块文件。

6.2账本创始块的生成

创建Channel也是通过configtxgen模块完成的,创建Channel初始块的配置文件和创建系统初始块的配置文件是一样的,具体在本例中,Channel的创始块的配置信息已经定义在本节第一部分系统创始块的生成中生成的配置文件configtx.yaml中。

创建Channel的命令如下:

configtxgen -profile  TestTwoOrgsChannel  -outputCreateChannelTx  ./roberttestchannel.tx -channelID  roberttestchannel

上述命令执行完成之后会在目录生成文件roberttestchannel.tx,该文件用来生成Channel。除此之外还需要生成相关的锚点文件,生成锚点文件需要执行以下命令:

configtxgen -profile  TestTwoOrgsChannel  -outputAnchorPeersUpdate ./Org1MSPanchors.tx -channelID  roberttestchannel -asOrg Org1MSP

 

configtxgen -profile  TestTwoOrgsChannel  -outputAnchorPeersUpdate ./Org2MSPanchors.tx -channelID  roberttestchannel -asOrg Org2MSP

 

上面命令执行完成之后会在相应的文件夹下面生成文件Org1MSPanchors.tx和Org2MSPanchors.tx,这些文件在后面会被使用到。

6.3 Orderer节点的启动

Orderer节点负责交易的打包和区块的生成。Orderer节点的配置信息通常放在环境变量或者配置文件中,本例中的配置信息统一存放在配置文件中。在Fabric源码提供了Orderer启动所用到的配置文件的实例,将示例配置文件复制到Orderer的文件夹下面修改即可使用。

复制配置文件到Orderer文件夹的命令如下所示:

cd /opt/hyperledger/order

cp $GOPATH/src/github.com/hyperledger/fabric/sampleconfig/orderer.yaml /opt/hyperledger/order

在模板配置文件上稍加修改即可满足本例使用,由于篇幅本例中我们只列出需要修改的部分。修改后配置文件中发生变化的内容如下:

 

General:

 

    LedgerType: file

    ListenAddress: 0.0.0.0

    ListenPort: 7050

    TLS:

        Enabled: false

        PrivateKey: /opt/hyperledger/fabricconfig/crypto-config/ordererOrganizations/qklszzn.com/orderers/orderer.qklszzn.com/tls/server.key

        Certificate: /opt/hyperledger/fabricconfig/crypto-config/ordererOrganizations/qklszzn.com/orderers/orderer.qklszzn.com/tls/server.crt

        RootCAs:

          - /opt/hyperledger/fabricconfig/crypto-config/ordererOrganizations/qklszzn.com/orderers/orderer.qklszzn.com/tls/ca.crt

        ClientAuthEnabled: false

        ClientRootCAs:

    LogLevel: debug

    LogFormat: '%{color}%{time:2006-01-02 15:04:05.000 MST} [%{module}] %{shortfunc} -> %{level:.4s} %{id:03x}%{color:reset} %{message}'

    GenesisMethod: file

    GenesisProfile: TestOrgsOrdererGenesis

    GenesisFile: /opt/hyperledger/order/orderer.genesis.block

    LocalMSPDir: /opt/hyperledger/fabricconfig/crypto-config/ordererOrganizations/qklszzn.com/orderers/orderer.qklszzn.com/msp

    LocalMSPID: OrdererMSP

    Profile:

        Enabled: false

        Address: 0.0.0.0:6060

    BCCSP:

 

        Default: SW

        SW:

            Hash: SHA2

            Security: 256

            FileKeyStore:

                KeyStore:

FileLedger:

    Location: /opt/hyperledger/order/production/orderer

    Prefix: hyperledger-fabric-ordererledger

RAMLedger:

    HistorySize: 1000

Debug:

    BroadcastTraceDir:

    DeliverTraceDir:

要注意配置文件中的相关路径

在配置文件orderer.yaml所在的目录执行如下命令启动orderer

orderer start

6.4 Peer节点的启动

Peer模块是Fabric的核心节点,所有的交易数据经过Orderer排序打包之后由Peer模块存储在区块链中。所有的Chaincode也是有Peer模块打包并且激活的。Peer模块的配置信息同样由环境变量和配置文件组成,本例中我们采用配置文的方式来配置peer节点的参数。在设定配置文件之前需要创建一个文件夹存放Peer模块的配置文件和区块数据。在Fabric源码中同样提供了Peer模块配置文件的示例,将示例配置文件复制到Peer模块的文件夹下面修改即可使用。

创建存储Peer模块的配置文件和区块数据的文件夹,并复制示例配置文件的命令如下所示:

mkdir -p /opt/hyperledger/peer

cd /opt/hyperledger/peer

cp  $GOPATH/src/github.com/hyperledger/fabric/sampleconfig/core.yaml /opt/hyperledger/peer

在模板配置文件上稍加修改即可使用,由于篇幅本例中我们只列出需要修改的部分。修改后Peer模块配置文件中变化的内容如下所示:

logging:

    peer:       debug

    cauthdsl:   warning

    gossip:     warning

    ledger:     info

    msp:        warning

    policies:   warning

    grpc:       error

    format: '%{color}%{time:2006-01-02 15:04:05.000 MST} [%{module}] %{shortfunc} -> %{level:.4s} %{id:03x}%{color:reset} %{message}'

peer:

 

    id: peer0.org1.qklszzn.com

    networkId: dev

    listenAddress: 0.0.0.0:7051

    chaincodeListenAddress: 0.0.0.0:7052

    address: peer0.org1.qklszzn.com:7051

    addressAutoDetect: false

    gomaxprocs: -1

    gossip:

 

        bootstrap: 127.0.0.1:7051

        useLeaderElection: true

        orgLeader: false

        endpoint:

        maxBlockCountToStore: 100

        maxPropagationBurstLatency: 10ms

        maxPropagationBurstSize: 10

        propagateIterations: 1

        propagatePeerNum: 3

        pullInterval: 4s

        pullPeerNum: 3

        requestStateInfoInterval: 4s

        publishStateInfoInterval: 4s

        stateInfoRetentionInterval:

        publishCertPeriod: 10s

        skipBlockVerification: false

        dialTimeout: 3s

        connTimeout: 2s

        recvBuffSize: 20

        sendBuffSize: 200

        digestWaitTime: 1s

        requestWaitTime: 1s

        responseWaitTime: 2s

        aliveTimeInterval: 5s

        aliveExpirationTimeout: 25s

        reconnectInterval: 2

        externalEndpoint: peer0.org1.qklszzn.com:7051

        election:

            startupGracePeriod: 15s

            membershipSampleInterval: 1s

            leaderAliveThreshold: 10s

            leaderElectionDuration: 5s

        pvtData:

            maxPeers: 3

            minAck:   3

    events:

        address: 0.0.0.0:7053

        buffersize: 100

        timeout: 10ms

    tls:

        enabled: false

        cert:

            file: /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/peers/peer0.org1.qklszzn.com/tls/server.crt

        key:

            file: /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/peers/peer0.org1.qklszzn.com/tls/server.key

        rootcert:

            file: /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/peers/peer0.org1.qklszzn.com/tls/ca.crt

        serverhostoverride:

    fileSystemPath: /opt/hyperledger/peer/production

    BCCSP:

        Default: SW

        SW:

            Hash: SHA2

            Security: 256

            FileKeyStore:

                KeyStore:

 

    mspConfigPath: /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/peers/peer0.org1.qklszzn.com/msp

 

    localMspId: Org1MSP

    profile:

        enabled:     false

        listenAddress: 0.0.0.0:6060

    handlers:

        authFilter: "DefaultAuth"

        decorator: "DefaultDecorator

    discovery:

        enabled: true

        authCacheEnabled: true

        authCacheMaxSize: 1000

        authCachePurgeRetentionRatio: 0.75

        orgMembersAllowedAccess: false

vm:

    endpoint: unix:///var/run/docker.soc

    docker:

        tls:

            enabled: false

            ca:

                file: docker/ca.crt

            cert:

                file: docker/tls.crt

            key:

                file: docker/tls.key

 

        attachStdout: false

        hostConfig:

            NetworkMode: host

            Dns:

            LogConfig:

                Type: json-file

                Config:

                    max-size: "50m"

                    max-file: "5"

            Memory: 2147483648

chaincode:

    peerAddress:

    id:

        path:

        name:

    builder: $(DOCKER_NS)/fabric-ccenv:$(ARCH)-$(PROJECT_VERSION)

    golang:

        runtime: $(BASE_DOCKER_NS)/fabric-baseos:$(ARCH)-$(BASE_VERSION)

    car:

        runtime: $(BASE_DOCKER_NS)/fabric-baseos:$(ARCH)-$(BASE_VERSION)

    java:

        Dockerfile:  |

            from $(DOCKER_NS)/fabric-javaenv:$(ARCH)-$(PROJECT_VERSION)

    node:

        runtime: $(BASE_DOCKER_NS)/fabric-baseimage:$(ARCH)-$(BASE_VERSION)

    startuptimeout: 300s

    executetimeout: 30s

    mode: dev

    keepalive: 0

    system:

        cscc: enable

        lscc: enable

        escc: enable

        vscc: enable

        qscc: enable

        rscc: disable

    logging:

      level:  info

      shim:   warning

      format: '%{color}%{time:2006-01-02 15:04:05.000 MST} [%{module}] %{shortfunc} -> %{level:.4s} %{id:03x}%{color:reset} %{message}'

ledger:

 

  blockchain:

  state:

    stateDatabase: goleveldb

    couchDBConfig:

       couchDBAddress: 127.0.0.1:5984

       username:

       password:

       maxRetries: 3

       maxRetriesOnStartup: 10

       requestTimeout: 35s

       queryLimit: 10000

  history:

    enableHistoryDatabase: true

 

在配置文件core.yaml所在的文件夹中执行以下命令启动peer节点

export set FABRIC_CFG_PATH=/opt/hyperledger/peer

peer node start >> log_peer.log 2>&1 &

 

6.5 创建通道

现在我们可以创建通道,创建通道的过程一共需要三个步骤。

第一步: 创建通道

export set FABRIC_CFG_PATH=/opt/hyperledger/peer

export set CORE_PEER_LOCALMSPID=Org1MSP

export set CORE_PEER_MSPCONFIGPATH=/opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/users/[email protected]/msp

 

cd /opt/hyperledger/order

//Fabric1.1 版本创建通道

peer channel create -t 50 -o orderer.qklszzn.com:7050 -c roberttestchannel -f /opt/hyperledger/order/roberttestchannel.tx

//Fabric1.3 版本创建通道

peer channel create -o orderer.qklszzn.com:7050 -c roberttestchannel   -f /opt/hyperledger/order/roberttestchannel.tx

 

创建通道完成之后,会在执行命令的当前目录生成名为roberttestchannel.block的通道创始块文件

第二步:让已经运行的Peer模块加入通道

export set CORE_PEER_LOCALMSPID=Org1MSP

export set CORE_PEER_ADDRESS=peer0.org1.qklszzn.com:7051

export set CORE_PEER_MSPCONFIGPATH=/opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/users/[email protected]/msp

 

peer channel join -b /opt/hyperledger/order/roberttestchannel.block

在上述创建通道的命令中-b后面的参数为第一步中生成的文件roberttestchannel.block,需要注意这个文件的路径。

第三步:更新锚节点

export set FABRIC_CFG_PATH=/opt/hyperledger/peer

export set CORE_PEER_LOCALMSPID=Org1MSP

export set CORE_PEER_ADDRESS=peer0.org1.qklszzn.com:7051

export set CORE_PEER_MSPCONFIGPATH=/opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/users/[email protected]/msp

 

 

peer channel update -o orderer.qklszzn.com:7050 -c roberttestchannel -f  /opt/hyperledger/order/Org1MSPanchors.tx

 

6.6 Chaincode的部署和调用

现在可以部署一个Chaincode来测试Peer节点和Orderer节点的部署是否正确。这里采用Fabric源码自带的例子来作为测试Chaincode。

测试用Chaincode的源代码路径如下所示:

$GOPATH/src/github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02

Chaincode相关的测试一共有四个步骤。

查看docker 是否启动,如果没启动,要先启动

问题:Manifest for docker.io/hyperledger/fabric-ccenv:x86_64-1.1.2-snapshot-ff996aa not found

docker tag hyperledger/fabric-ccenv:latest hyperledger/fabric-ccenv:x86_64-1.1.2-snapshot-ff996aa

//Fabric1.1 安装智能合约

peer chaincode install -n r_test_cc6 -v 1.0 -p github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02

//Fabric1.3官网安装智能合约,执行报错;需要下载fabric-samples,然后把目录fabric-samples/chaincode/chaincode_example02拷贝到目录/opt/gopath/src/github.com/chaincode/下

 

 

第一步:安装智能合约

Golang

peer chaincode install -n mycc -v 1.0 -p github.com/chaincode/chaincode_example02/go/

Node.js

# this installs the Node.js chaincode
# make note of the -l flag; we use this to specify the language
peer chaincode install -n mycc -v 1.0 -l node -p /opt/gopath/src/github.com/chaincode/chaincode_example02/node/

Java

peer chaincode install -n mycc -v 1.0 -l java -p /opt/gopath/src/github.com/chaincode/chaincode_example02/java/

 

也可以把fabric1.1的智能合约拿来用

peer chaincode install -n r_test_cc6 -v 1.0 -p github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02/

第二步: 实例化chaincode代码

export set CORE_PEER_LOCALMSPID=Org1MSP

export set CORE_PEER_ADDRESS=peer0.org1.qklszzn.com:7051

export set CORE_PEER_MSPCONFIGPATH=/opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/users/[email protected]/msp

 

peer chaincode instantiate -o  orderer.qklszzn.com:7050 -C roberttestchannel -n r_test_cc6 -v 1.0 -c '{"Args":["init","a","100","b","200"]}' -P "OR      ('Org1MSP.member','Org2MSP.member')"

注意:组织Org1MSP的所有成员或者Org2MSP的所有成员任意一个背书,如果是and就是组织Org1MSP的所有成员或者Org2MSP的所有成员都要进行背书

第三步:通过chaincode写入数据

export set FABRIC_CFG_PATH=/opt/hyperledger/peer

export set CORE_PEER_LOCALMSPID=Org1MSP

export set CORE_PEER_ADDRESS=peer0.org1.qklszzn.com:7051

export set CORE_PEER_MSPCONFIGPATH=/opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/users/[email protected]/msp

 

peer chaincode invoke -o orderer.qklszzn.com:7050 -C roberttestchannel -n r_test_cc6 -c '{"Args":["invoke","a","b","1"]}'

 

第四步:通过chaincode查询数据

export set CORE_PEER_LOCALMSPID=Org1MSP

export set CORE_PEER_ADDRESS=peer0.org1.qklszzn.com:7051

export set CORE_PEER_MSPCONFIGPATH=/opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/users/[email protected]/msp

 

peer chaincode query -C roberttestchannel -n r_test_cc6 -c '{"Args":["query","a"]}'

 

 

如果上述命令都能正确执行,那么一个简单的Fabric系统就已经部署完成了。

猜你喜欢

转载自www.cnblogs.com/haonan-fabric/p/9984669.html