Fabric 1.3新功能介紹及環境搭建

第一部分:新功能介紹html

功能1. 使用Identity Mixer實現MSP(Membership Service Prodiver)

       這是一種經過使用零知識證實來保持身份匿名和不可連接的方法。工具idexmigen能夠在測試環境中生成Identity Mixer憑證。java

1.1零知識證實

     零知識證實,英文名爲Zero-Knowledge Proof,是由S.Goldwasser、S.Micali以及C.Rackoff在20世紀80年代初提出的。它指的是證實者(被驗證者)可以在不向驗證者提供任何有用的信息的狀況下,使驗證者相信某個論斷是正確的。node

零知識證實實質上是一種涉及兩方或更多方的協議,即兩方或更多方完成一項任務所需採起的一系列步驟。python

1.2 什麼是Idemix?

       Idemix是一個加密協議套件,它提供強大的身份驗證以及隱私保護功能,如匿名,無需揭示交易者身份便可進行交易,以及不可連接性,即單個身份發送多個交易的能力,而不會泄露交易是經過相同的身份發送的。linux

Idemix流中涉及三個參與者:用戶,發行者和 驗證者。nginx

 

發行者證實將一組用戶的屬性以數字證書的形式發佈,如下稱爲「憑證」。git

用戶稍後生成擁有憑證的「 零知識證實 」,而且可以選擇性地公開用戶選擇顯示的屬性。它不會向驗證者,發行者或任何其餘人顯示其餘信息。github

1.3 如何將Idemix與Hyperledger Fabric一塊兒使用

要在Hyperledger Fabric中使用Idemix,須要如下三個基本步驟:golang

 

發行者:Fabric CA 或者 idemixgendocker

驗證者: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/Admin@org1.qklszzn.com/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/Admin@org1.qklszzn.com/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/Admin@org1.qklszzn.com/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/Admin@org1.qklszzn.com/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/Admin@org1.qklszzn.com/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/Admin@org1.qklszzn.com/msp

 

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

 

 

若是上述命令都能正確執行,那麼一個簡單的Fabric系統就已經部署完成了。

相關文章
相關標籤/搜索