91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

hyperledger v1.0.5區塊鏈的示例分析

發布時間:2021-12-07 09:26:44 來源:億速云 閱讀:249 作者:小新 欄目:互聯網科技

這篇文章主要介紹hyperledger v1.0.5區塊鏈的示例分析,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

hyperledger v1.0.5 區塊鏈入門

1. what-做什么

區塊鏈技術發展至今,形成了公有鏈、聯盟鏈和邦鏈三種種主流技術平臺。

公有鏈: 面向大眾,用戶可以匿名參與,非常方便,賬本數據也公開,加上強大的智能合約,因此公有鏈極大地促進了區塊鏈概念和技術的普及,比如比特幣、Ethereum平臺等。

聯盟鏈: 考慮到商業應用對安全、隱私、監管、審計、性能的需求,提高準入門檻,增加了安全、隱私、可監管審計等商業特性,是區塊鏈技術在商業領域的應用探索。

邦鏈:暫時資料比較少。

概念

通道( Channel ):通道是構建在 Hyperledger Fabric 區塊鏈網絡上的私有區塊鏈,實現了數據的隔離和保密。通道中的 Chaincode 和交易只有加入該通道的節點( Peer )可見。同一個節點可以加入多個通道,并為每個通道內容維護一個賬本。每一個通道即為一條邏輯上的區塊鏈。可以按照業務來劃分通道,也可以按照行政職能和隱私策略來劃分通道。

節點( Peer ): 維護賬本的網絡節點,通常區塊鏈網絡架構中存在多種角色,如 endorser 和 committer 。

排序服務或共識服務( Order Services ) : 提供排序服務或共識服務的網絡節點,完成交易的排序和區塊打包等工作,支持可插拔的共識組件,當前生產環境下使用 Kafka 進行交易排序。

分布式賬本( Distribute Ledger ) :由網絡中若干去中心化節點共同維護的數據賬本。

組織( Org ) :聯盟鏈中按照 訪問和使用賬本的網絡節點,一個聯盟(或者一個區塊鏈網絡)有多個組織(成員),一個組織內可以有多個節點( Peer ),每個節點參與賬本和世界狀態維護。

智能合約( Smart Contract ) :根據特定條件自動執行的合約程序。智能合約是區塊鏈的重要特征,是用戶與區塊鏈進行交互,利用區塊鏈實現業務邏輯的重要途徑。

鏈碼( Chaincode ):鏈碼是 Hyperledger Fabric 對智能合約的一種實現方式,是運行于 Hyperledger Fabric 網絡之上一段應用程序代碼,也是用戶與 Hyperledger Fabric 交互的唯一途徑。

鏈( Chain ):一個鏈即是一個由若干區塊通過特定指向鏈接、摘要算法或加密算法錨定組成的數據集合。

2. how-怎么做

+---------------------------------+		
|        	     SDK              |
+---------------------------------+	
| golang | nodejs | python | java |
+---------------------------------+			
	|
	V
+---------------------------------+				
| fabric-ca :                     |
+---------------------------------+
     |                       |
+-------------------+     +-------------------+
|	Peer            |     |  Peer             |	        
+-------------------+     +-------------------+		
     |                       |
     V                       V
+-------------------+     +-------------------+
| Orderer           |     | Orderer           |
+-------------------+     +-------------------+
                 |           |
             +-------------------+
             | Couchdb           |
             +-------------------+

2.1. 依賴工具

yum -y install epel-release
yum install -y git
yum install -y golang

2.2. 安裝Docker

curl -s https://raw.githubusercontent.com/oscm/shell/master/virtualization/docker/docker.centos7.ce.sh	 | bash
curl -s https://raw.githubusercontent.com/oscm/shell/master/virtualization/docker/registry-mirror.sh	 | bash
or 
curl -fsSL https://get.docker.com/ | sh	

創建2個docker網絡,如下:
docker network create fabric_noops
docker network create fabric_pbft

安裝 docker-compose

curl -s https://raw.githubusercontent.com/oscm/shell/master/virtualization/docker/docker-compose.sh	 | bash

2.3. 安裝 Node.js 環境

yum install -y nodejs
npm install

2.4. 安裝 hyperledger 1.0.4

運行后 hyperledger 相關鏡像被安裝到 Docker 中

cd /usr/local/src
curl -s https://raw.githubusercontent.com/hyperledger/fabric/release/scripts/bootstrap-1.0.4.sh | bash

由于上面腳本會安裝所有節點,速度較慢,作者建議你參考下一章節,手工安裝所需最低配置節點。

2.5. 手工安裝 hyperledger v 1.0.5 開發環境

對于開發環境,最小化的環境,包括 1 個 peer 節點、1 個 Orderer 節點、1 個 CA 節點。

準備一個服務器或者虛擬機,安裝 CentOS 操作系統。

如果你是在已有的Docker上安裝,建議你刪除所有容器后在安裝。以免出現沖突等情況。

docker stop $(docker ps -q) && docker rm $(docker ps -aq)
2.5.1. 登錄 docker
[root@localhost ~]# docker login
Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.
Username: netkiller
Password: 
Login Succeeded
2.5.2. Docker 安裝
docker pull hyperledger/fabric-baseimage:latest \
  && docker pull hyperledger/fabric-membersrvc:latest \
  && docker pull hyperledger/fabric-peer:latest \
  && docker pull hyperledger/fabric-orderer:latest \
  && docker pull hyperledger/fabric-ca:latest \
  && docker pull hyperledger/blockchain-explorer:latest

安裝會出現下面問題

[root@localhost ~]# docker search fabric-peer | grep hyperledger/fabric-peer
hyperledger/fabric-peer            Fabric Peer docker image for Hyperledger Pro…   69

[root@localhost ~]# docker pull hyperledger/fabric-peer:latest
Error response from daemon: manifest for hyperledger/fabric-peer:latest not found

可以 search 到的鏡像 pull 不了,原因是 fabric-peer:latest,latest 不存在,你需要指定版本號。

docker pull hyperledger/fabric-membersrvc:latest \
&& docker pull hyperledger/fabric-peer:x86_64-1.0.5 \
&& docker pull hyperledger/fabric-orderer:x86_64-1.0.5 \
&& docker pull hyperledger/fabric-couchdb:x86_64-1.0.5 \
&& docker pull hyperledger/fabric-ca:x86_64-1.0.5 \
&& docker pull hyperledger/fabric-tools:x86_64-1.0.5

docker tag hyperledger/fabric-peer:x86_64-1.0.5 hyperledger/fabric-peer \
&& docker tag hyperledger/fabric-orderer:x86_64-1.0.5 hyperledger/fabric-orderer \
&& docker tag hyperledger/fabric-couchdb:x86_64-1.0.5 hyperledger/fabric-couchdb \
&& docker tag hyperledger/fabric-ca:x86_64-1.0.5 hyperledger/fabric-ca \
&& docker tag hyperledger/fabric-tools:x86_64-1.0.5 hyperledger/fabric-tools

查看鏡像

[root@localhost src]# docker images
REPOSITORY                      TAG                 IMAGE ID            CREATED             SIZE
hyperledger/fabric-orderer      latest              368c78b6f03b        2 months ago        151MB
hyperledger/fabric-orderer      x86_64-1.0.5        368c78b6f03b        2 months ago        151MB
hyperledger/fabric-peer         latest              c2ab022f0bdb        2 months ago        154MB
hyperledger/fabric-peer         x86_64-1.0.5        c2ab022f0bdb        2 months ago        154MB
hyperledger/fabric-membersrvc   latest              b3654d32e4f9        15 months ago       1.42GB
2.5.3. 編譯安裝
git config --global core.autocrlf false				
$ git clone https://github.com/hyperledger/fabric.git 
$ make docker 
$ git clone https://github.com/hyperledger/fabric-ca.git		
$ make docker 

cd fabric/devenv
vagrant box add hyperledger/fabric-baseimage centos7.box
vagrant up

yum -y install epel-release
yum -y install git
yum -y install golang
yum -y install python-pip	
pip install --upgrade backports.ssl_match_hostname
pip install docker-compose

docker-compose -version

2.6. 啟動 docker 虛擬機

這里我們最小化啟動,需要四個節點,分別是 ca, peer, order, couchdb。

創建文件 docker-compose.yml

[root@localhost ~]# mkdir -p docker
[root@localhost ~]# cd docker
[root@localhost docker]# vim docker-compose.yml
#
# Copyright IBM Corp All Rights Reserved
#
# SPDX-License-Identifier: Apache-2.0
#
version: '2'

networks:
  basic:

services:
  ca.example.com:
    image: hyperledger/fabric-ca
    environment:
      - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server
      - FABRIC_CA_SERVER_CA_NAME=ca.example.com
      - FABRIC_CA_SERVER_CA_CERTFILE=/etc/hyperledger/fabric-ca-server-config/ca.org1.example.com-cert.pem
      - FABRIC_CA_SERVER_CA_KEYFILE=/etc/hyperledger/fabric-ca-server-config/4239aa0dcd76daeeb8ba0cda701851d14504d31aad1b2ddddbac6a57365e497c_sk
    ports:
      - "7054:7054"
    command: sh -c 'fabric-ca-server start -b admin:adminpw -d'
    volumes:
      - ./crypto-config/peerOrganizations/org1.example.com/ca/:/etc/hyperledger/fabric-ca-server-config
    container_name: ca.example.com
    networks:
      - basic

  orderer.example.com:
    container_name: orderer.example.com
    image: hyperledger/fabric-orderer
    environment:
      - ORDERER_GENERAL_LOGLEVEL=debug
      - ORDERER_GENERAL_LISTENADDRESS=0.0.0.0
      - ORDERER_GENERAL_GENESISMETHOD=file
      - ORDERER_GENERAL_GENESISFILE=/etc/hyperledger/configtx/genesis.block
      - ORDERER_GENERAL_LOCALMSPID=OrdererMSP
      - ORDERER_GENERAL_LOCALMSPDIR=/etc/hyperledger/msp/orderer/msp
    working_dir: /opt/gopath/src/github.com/hyperledger/fabric/orderer
    command: orderer
    ports:
      - 7050:7050
    volumes:
        - ./config/:/etc/hyperledger/configtx
        - ./crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/:/etc/hyperledger/msp/orderer
        - ./crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/:/etc/hyperledger/msp/peerOrg1
    networks:
      - basic

  peer0.org1.example.com:
    container_name: peer0.org1.example.com
    image: hyperledger/fabric-peer
    environment:
      - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
      - CORE_PEER_ID=peer0.org1.example.com
      - CORE_LOGGING_PEER=debug
      - CORE_CHAINCODE_LOGGING_LEVEL=DEBUG
      - CORE_PEER_LOCALMSPID=Org1MSP
      - CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/peer/
      - CORE_PEER_ADDRESS=peer0.org1.example.com:7051
      # # the following setting starts chaincode containers on the same
      # # bridge network as the peers
      # # https://docs.docker.com/compose/networking/
      - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${COMPOSE_PROJECT_NAME}_basic
      - CORE_LEDGER_STATE_STATEDATABASE=CouchDB
      - CORE_LEDGER_STATE_COUCHDBCONFIG_COUCHDBADDRESS=couchdb:5984
      # The CORE_LEDGER_STATE_COUCHDBCONFIG_USERNAME and CORE_LEDGER_STATE_COUCHDBCONFIG_PASSWORD
      # provide the credentials for ledger to connect to CouchDB.  The username and password must
      # match the username and password set for the associated CouchDB.
      - CORE_LEDGER_STATE_COUCHDBCONFIG_USERNAME=
      - CORE_LEDGER_STATE_COUCHDBCONFIG_PASSWORD=
    working_dir: /opt/gopath/src/github.com/hyperledger/fabric
    command: peer node start
    # command: peer node start --peer-chaincodedev=true
    ports:
      - 7051:7051
      - 7053:7053
    volumes:
        - /var/run/:/host/var/run/
        - ./crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/msp:/etc/hyperledger/msp/peer
        - ./crypto-config/peerOrganizations/org1.example.com/users:/etc/hyperledger/msp/users
        - ./config:/etc/hyperledger/configtx
    depends_on:
      - orderer.example.com
      - couchdb
    networks:
      - basic

  couchdb:
    container_name: couchdb
    image: hyperledger/fabric-couchdb
    # Populate the COUCHDB_USER and COUCHDB_PASSWORD to set an admin user and password
    # for CouchDB.  This will prevent CouchDB from operating in an "Admin Party" mode.
    environment:
      - COUCHDB_USER=
      - COUCHDB_PASSWORD=
    ports:
      - 5984:5984
    networks:
      - basic

  cli:
    container_name: cli
    image: hyperledger/fabric-tools
    tty: true
    environment:
      - GOPATH=/opt/gopath
      - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
      - CORE_LOGGING_LEVEL=DEBUG
      - CORE_PEER_ID=cli
      - CORE_PEER_ADDRESS=peer0.org1.example.com:7051
      - CORE_PEER_LOCALMSPID=Org1MSP
      - CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
      - CORE_CHAINCODE_KEEPALIVE=10
    working_dir: /opt/gopath/src/github.com/hyperledger/fabric/peer
    command: /bin/bash
    volumes:
        - /var/run/:/host/var/run/
        - ./../chaincode/:/opt/gopath/src/github.com/
        - ./crypto-config:/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/
    networks:
        - basic
    #depends_on:
    #  - orderer.example.com
    #  - peer0.org1.example.com
    #  - couchdb

啟動 Docker

[root@localhost docker]# docker-compose -f docker-compose.yml up -d ca.example.com orderer.example.com peer0.org1.example.com couchdb

查看進程

[root@localhost docker]# docker-compose ps 
         Name                       Command               State                       Ports                      
----------------------------------------------------------------------------------------------------------------
ca.example.com           sh -c fabric-ca-server sta ...   Up      0.0.0.0:7054->7054/tcp                         
cli                      /bin/bash                        Up                                                     
couchdb                  tini -- /docker-entrypoint ...   Up      4369/tcp, 0.0.0.0:5984->5984/tcp, 9100/tcp     
orderer.example.com      orderer                          Up      0.0.0.0:7050->7050/tcp                         
peer0.org1.example.com   peer node start                  Up      0.0.0.0:7051->7051/tcp, 0.0.0.0:7053->7053/tcp
 

2.7. 管理 hyperledger

2.7.1. CouchDB 管理界面
[root@localhost fabcar]# curl http://localhost:5984
{"couchdb":"Welcome","version":"2.0.0","vendor":{"name":"The Apache Software Foundation"}}

http://localhost:5984/_utils/

2.8. 部署 chaincode

2.8.1. channel 管理

Hyperledger Fabric Channel 可以理解為 vlan (交換機術語) 用來實現區塊隔離。

2.8.1.1. 列出 channel

root@595ec455c0ff:/opt/gopath/src/github.com/hyperledger/fabric# peer channel list 
2018-02-07 03:24:41.151 UTC [msp] GetLocalMSP -> DEBU 001 Returning existing local MSP
2018-02-07 03:24:41.152 UTC [msp] GetDefaultSigningIdentity -> DEBU 002 Obtaining default signing identity
2018-02-07 03:24:41.154 UTC [channelCmd] InitCmdFactory -> INFO 003 Endorser and orderer connections initialized
2018-02-07 03:24:41.155 UTC [msp/identity] Sign -> DEBU 004 Sign: plaintext: 0A85070A5B08031A0B08F9E2E9D30510...631A0D0A0B4765744368616E6E656C73 
2018-02-07 03:24:41.156 UTC [msp/identity] Sign -> DEBU 005 Sign: digest: 238CBAB61A0524954DC3C511588EB8FC1F886E636A8800131EBE16FB95FB0C9A 
2018-02-07 03:24:41.167 UTC [channelCmd] list -> INFO 006 Channels peers has joined to: 
2018-02-07 03:24:41.167 UTC [channelCmd] list -> INFO 007 mychannel 
2018-02-07 03:24:41.167 UTC [main] main -> INFO 008 Exiting.....

2.8.1.2. 創建 Channel

CORE_PEER_LOCALMSPID=Org1MSP
CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/users/Admin@org1.example.com/msp
peer channel create -o orderer.example.com:7050 -c mychannel -f /etc/hyperledger/configtx/channel.tx

2.8.1.3. 加入 Channel

CORE_PEER_LOCALMSPID=Org1MSP
CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/users/Admin@org1.example.com/msp
peer0.org1.example.com peer channel join -b mychannel.block
2.8.2. 部署連
[root@localhost docker]# docker-compose exec peer0.org1.example.com bash
root@dcb09db1cbc8:/go/src/github.com/hyperledger/fabric#

安裝合約

CORE_PEER_LOCALMSPID=Org1MSP
CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
peer chaincode install -n fabcar -v 1.0 -p github.com/fabcar

實例化合約

CORE_PEER_LOCALMSPID=Org1MSP
CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
peer chaincode instantiate -o orderer.example.com:7050 -C mychannel -n fabcar -v 1.0 -c '{"Args":[""]}' -P "OR ('Org1MSP.member','Org2MSP.member')"

初始化合約

CORE_PEER_LOCALMSPID=Org1MSP
CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
peer chaincode invoke -o orderer.example.com:7050 -C mychannel -n fabcar -c '{"function":"initLedger","Args":[""]}'
2.8.3. 測試
root@595ec455c0ff:/opt/gopath/src/github.com/hyperledger/fabric# peer chaincode invoke -o orderer.example.com:7050 -C mychannel -n fabcar -c '{"function":"queryCar","Args":["CAR9"]}'
2018-02-07 04:44:03.451 UTC [msp] GetLocalMSP -> DEBU 001 Returning existing local MSP
2018-02-07 04:44:03.451 UTC [msp] GetDefaultSigningIdentity -> DEBU 002 Obtaining default signing identity
2018-02-07 04:44:03.454 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 003 Using default escc
2018-02-07 04:44:03.455 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 004 Using default vscc
2018-02-07 04:44:03.456 UTC [msp/identity] Sign -> DEBU 005 Sign: plaintext: 0A97070A6908031A0C089388EAD30510...0A0871756572794361720A0443415239 
2018-02-07 04:44:03.456 UTC [msp/identity] Sign -> DEBU 006 Sign: digest: 28C28E7387383CC89E298B29932853964A5D26E4AA358C1242D62ACCAF121BFB 
2018-02-07 04:44:03.495 UTC [msp/identity] Sign -> DEBU 007 Sign: plaintext: 0A97070A6908031A0C089388EAD30510...F7BBABB41F274432D5C6985A78D8E949 
2018-02-07 04:44:03.495 UTC [msp/identity] Sign -> DEBU 008 Sign: digest: BC6559CACFFC49B5B053B050B7634D1D4D920CAC3F228ED6F38EBFF6A760D7C1 
2018-02-07 04:44:03.504 UTC [chaincodeCmd] chaincodeInvokeOrQuery -> DEBU 009 ESCC invoke result: version:1 response:<status:200 message:"OK" payload:"{\"colour\":\"brown\",\"make\":\"Holden\",\"model\":\"Barina\",\"owner\":\"Shotaro\"}" > payload:"\n \245\036\265\326\362rL\341\234\326\267\3452\360\277]\220\017C\212\206\311\034\344P\022\034(\364\026-_\022\215\001\n0\022\026\n\006fabcar\022\014\n\n\n\004CAR9\022\002\010\005\022\026\n\004lscc\022\016\n\014\n\006fabcar\022\002\010\001\032J\010\310\001\032E{\"colour\":\"brown\",\"make\":\"Holden\",\"model\":\"Barina\",\"owner\":\"Shotaro\"}\"\r\022\006fabcar\032\0031.0" endorsement:<endorser:"\n\007Org1MSP\022\200\006-----BEGIN -----\nMIICGjCCAcCgAwIBAgIRAPlwF/rUZUP9mqN4wSml4iswCgYIKoZIzj0EAwIwczEL\nMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBG\ncmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMTcwODMxMDkxNDMyWhcNMjcwODI5MDkxNDMy\nWjBbMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMN\nU2FuIEZyYW5jaXNjbzEfMB0GA1UEAxMWcGVlcjAub3JnMS5leGFtcGxlLmNvbTBZ\nMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHihxW6ks3B2+5XdbAVq3CBgxRRRZ22x\nzzpqnD86nKkz7fBElBuhlXl2K6rTxyY2OBOB0ts8keqZ93xueRGymrajTTBLMA4G\nA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8EAjAAMCsGA1UdIwQkMCKAIEI5qg3Ndtru\nuLoM2nAYUdFFBNMarRst3dusalc2Xkl8MAoGCCqGSM49BAMCA0gAMEUCIQD4j0Rn\ne1rrd0FSCzsR6u+IuuPK5dI/kR/bh7+VLf0TNgIgCfUtkJvfvzVEwZLFoFyjoHtr\ntvwzNUS1U0hEqIaDeo4=\n-----END -----\n" signature:"0E\002!\000\2657\267\025<v\010\014sC\261U\207H\251\021KJw#\2322C\031<\346=\207\222\343\263\025\002 So\272|v\027xM\026\225\003bx\312\277n\367\273\253\264\037'D2\325\306\230Zx\330\351I" > 
2018-02-07 04:44:03.509 UTC [chaincodeCmd] chaincodeInvokeOrQuery -> INFO 00a Chaincode invoke successful. result: status:200 payload:"{\"colour\":\"brown\",\"make\":\"Holden\",\"model\":\"Barina\",\"owner\":\"Shotaro\"}" 
2018-02-07 04:44:03.510 UTC [main] main -> INFO 00b Exiting.....

3. fabric-samples

安裝 fabric-samples

git clone https://github.com/hyperledger/fabric-samples.git
cd fabric-samples

fabric-samples 包含了很多例子,我們只運行幾個常用的例子。

3.1. fabcar

cd fabric-samples/fabcar

啟動

[root@localhost fabcar]# ./startFabric.sh 

# don't rewrite paths for Windows Git Bash users
export MSYS_NO_PATHCONV=1

docker-compose -f docker-compose.yml down
Stopping peer0.org1.example.com ... done
Stopping couchdb ... done
Stopping orderer.example.com ... done
Stopping ca.example.com ... done
Removing peer0.org1.example.com ... done
Removing couchdb ... done
Removing orderer.example.com ... done
Removing ca.example.com ... done
Removing network net_basic

docker-compose -f docker-compose.yml up -d ca.example.com orderer.example.com peer0.org1.example.com couchdb
Creating network "net_basic" with the default driver
Creating couchdb
Creating orderer.example.com
Creating ca.example.com
Creating peer0.org1.example.com

# wait for Hyperledger Fabric to start
# incase of errors when running later commands, issue export FABRIC_START_TIMEOUT=<larger number>
export FABRIC_START_TIMEOUT=10
#echo ${FABRIC_START_TIMEOUT}
sleep ${FABRIC_START_TIMEOUT}

# Create the channel
docker exec -e "CORE_PEER_LOCALMSPID=Org1MSP" -e "CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/users/Admin@org1.example.com/msp" peer0.org1.example.com peer channel create -o orderer.example.com:7050 -c mychannel -f /etc/hyperledger/configtx/channel.tx
2018-02-06 04:27:38.822 UTC [msp] GetLocalMSP -> DEBU 001 Returning existing local MSP
2018-02-06 04:27:38.822 UTC [msp] GetDefaultSigningIdentity -> DEBU 002 Obtaining default signing identity
2018-02-06 04:27:38.825 UTC [channelCmd] InitCmdFactory -> INFO 003 Endorser and orderer connections initialized
2018-02-06 04:27:38.825 UTC [msp] GetLocalMSP -> DEBU 004 Returning existing local MSP
2018-02-06 04:27:38.825 UTC [msp] GetDefaultSigningIdentity -> DEBU 005 Obtaining default signing identity
2018-02-06 04:27:38.826 UTC [msp] GetLocalMSP -> DEBU 006 Returning existing local MSP
2018-02-06 04:27:38.826 UTC [msp] GetDefaultSigningIdentity -> DEBU 007 Obtaining default signing identity
2018-02-06 04:27:38.826 UTC [msp/identity] Sign -> DEBU 008 Sign: plaintext: 0A88060A074F7267314D535012FC052D...53616D706C65436F6E736F727469756D 
2018-02-06 04:27:38.826 UTC [msp/identity] Sign -> DEBU 009 Sign: digest: D2F2DB3135CE892465FB7B6C2C89A6C566EC6E0081034AF00AF62014ED098E10 
2018-02-06 04:27:38.827 UTC [msp] GetLocalMSP -> DEBU 00a Returning existing local MSP
2018-02-06 04:27:38.827 UTC [msp] GetDefaultSigningIdentity -> DEBU 00b Obtaining default signing identity
2018-02-06 04:27:38.827 UTC [msp] GetLocalMSP -> DEBU 00c Returning existing local MSP
2018-02-06 04:27:38.827 UTC [msp] GetDefaultSigningIdentity -> DEBU 00d Obtaining default signing identity
2018-02-06 04:27:38.827 UTC [msp/identity] Sign -> DEBU 00e Sign: plaintext: 0ABF060A1508021A0608BADDE4D30522...4447D0A2A449E39255165BEE40760F3E 
2018-02-06 04:27:38.827 UTC [msp/identity] Sign -> DEBU 00f Sign: digest: BE32EAB1C6CE6A2C7F79FED4D1C646702EE07A3D64014B5EE2B77F8B35E9CF5F 
2018-02-06 04:27:38.935 UTC [msp] GetLocalMSP -> DEBU 010 Returning existing local MSP
2018-02-06 04:27:38.935 UTC [msp] GetDefaultSigningIdentity -> DEBU 011 Obtaining default signing identity
2018-02-06 04:27:38.935 UTC [msp] GetLocalMSP -> DEBU 012 Returning existing local MSP
2018-02-06 04:27:38.935 UTC [msp] GetDefaultSigningIdentity -> DEBU 013 Obtaining default signing identity
2018-02-06 04:27:38.935 UTC [msp/identity] Sign -> DEBU 014 Sign: plaintext: 0ABF060A1508021A0608BADDE4D30522...96444BF5E3AA12080A021A0012021A00 
2018-02-06 04:27:38.936 UTC [msp/identity] Sign -> DEBU 015 Sign: digest: 11D42E8978C507DC0C33304B81E089DB5DAB72967A153BD52932C5A4054C3D4B 
2018-02-06 04:27:38.937 UTC [channelCmd] readBlock -> DEBU 016 Got status: &{NOT_FOUND}
2018-02-06 04:27:38.937 UTC [msp] GetLocalMSP -> DEBU 017 Returning existing local MSP
2018-02-06 04:27:38.937 UTC [msp] GetDefaultSigningIdentity -> DEBU 018 Obtaining default signing identity
2018-02-06 04:27:38.939 UTC [channelCmd] InitCmdFactory -> INFO 019 Endorser and orderer connections initialized
2018-02-06 04:27:39.139 UTC [msp] GetLocalMSP -> DEBU 01a Returning existing local MSP
2018-02-06 04:27:39.139 UTC [msp] GetDefaultSigningIdentity -> DEBU 01b Obtaining default signing identity
2018-02-06 04:27:39.140 UTC [msp] GetLocalMSP -> DEBU 01c Returning existing local MSP
2018-02-06 04:27:39.140 UTC [msp] GetDefaultSigningIdentity -> DEBU 01d Obtaining default signing identity
2018-02-06 04:27:39.140 UTC [msp/identity] Sign -> DEBU 01e Sign: plaintext: 0ABF060A1508021A0608BBDDE4D30522...75CF3E958E8612080A021A0012021A00 
2018-02-06 04:27:39.140 UTC [msp/identity] Sign -> DEBU 01f Sign: digest: 26B8D88C16CF0DC0573F9BB9A69EC1BF1FEA8C12D052F832B3DB7B2A10D2CA6D 
2018-02-06 04:27:39.145 UTC [channelCmd] readBlock -> DEBU 020 Received block: 0
2018-02-06 04:27:39.146 UTC [main] main -> INFO 021 Exiting.....
# Join peer0.org1.example.com to the channel.
docker exec -e "CORE_PEER_LOCALMSPID=Org1MSP" -e "CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/users/Admin@org1.example.com/msp" peer0.org1.example.com peer channel join -b mychannel.block
2018-02-06 04:27:39.465 UTC [msp] GetLocalMSP -> DEBU 001 Returning existing local MSP
2018-02-06 04:27:39.465 UTC [msp] GetDefaultSigningIdentity -> DEBU 002 Obtaining default signing identity
2018-02-06 04:27:39.467 UTC [channelCmd] InitCmdFactory -> INFO 003 Endorser and orderer connections initialized
2018-02-06 04:27:39.468 UTC [msp/identity] Sign -> DEBU 004 Sign: plaintext: 0A86070A5C08011A0C08BBDDE4D30510...2A0C0B6B1D4B1A080A000A000A000A00 
2018-02-06 04:27:39.468 UTC [msp/identity] Sign -> DEBU 005 Sign: digest: 455E4221B3AE6DD1238BF5C8893970131846C096F1465D4CA89385AF3C7C0B2F 
2018-02-06 04:27:39.991 UTC [channelCmd] executeJoin -> INFO 006 Peer joined the channel!
2018-02-06 04:27:39.991 UTC [main] main -> INFO 007 Exiting.....
Creating cli
2018-02-06 04:27:46.123 UTC [msp] GetLocalMSP -> DEBU 001 Returning existing local MSP
2018-02-06 04:27:46.123 UTC [msp] GetDefaultSigningIdentity -> DEBU 002 Obtaining default signing identity
2018-02-06 04:27:46.123 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 003 Using default escc
2018-02-06 04:27:46.123 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 004 Using default vscc
2018-02-06 04:27:47.513 UTC [golang-platform] getCodeFromFS -> DEBU 005 getCodeFromFS github.com/fabcar
2018-02-06 04:27:48.448 UTC [golang-platform] func1 -> DEBU 006 Discarding GOROOT package bytes
2018-02-06 04:27:48.449 UTC [golang-platform] func1 -> DEBU 007 Discarding GOROOT package encoding/json
2018-02-06 04:27:48.449 UTC [golang-platform] func1 -> DEBU 008 Discarding GOROOT package fmt
2018-02-06 04:27:48.449 UTC [golang-platform] func1 -> DEBU 009 Discarding provided package github.com/hyperledger/fabric/core/chaincode/shim
2018-02-06 04:27:48.449 UTC [golang-platform] func1 -> DEBU 00a Discarding provided package github.com/hyperledger/fabric/protos/peer
2018-02-06 04:27:48.449 UTC [golang-platform] func1 -> DEBU 00b Discarding GOROOT package strconv
2018-02-06 04:27:48.449 UTC [golang-platform] GetDeploymentPayload -> DEBU 00c done
2018-02-06 04:27:48.458 UTC [msp/identity] Sign -> DEBU 00d Sign: plaintext: 0A86070A5C08031A0C08C4DDE4D30510...939FFF060000FFFF9C08DC0700200000 
2018-02-06 04:27:48.459 UTC [msp/identity] Sign -> DEBU 00e Sign: digest: 881EE9535C8EC4371B72CE38BC52BD950864D1CA50F1F64B707EC7492B38AC75 
2018-02-06 04:27:48.512 UTC [chaincodeCmd] install -> DEBU 00f Installed remotely response:<status:200 payload:"OK" > 
2018-02-06 04:27:48.512 UTC [main] main -> INFO 010 Exiting.....
2018-02-06 04:27:48.845 UTC [msp] GetLocalMSP -> DEBU 001 Returning existing local MSP
2018-02-06 04:27:48.845 UTC [msp] GetDefaultSigningIdentity -> DEBU 002 Obtaining default signing identity
2018-02-06 04:27:48.847 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 003 Using default escc
2018-02-06 04:27:48.848 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 004 Using default vscc
2018-02-06 04:27:48.849 UTC [msp/identity] Sign -> DEBU 005 Sign: plaintext: 0A91070A6708031A0C08C4DDE4D30510...324D53500A04657363630A0476736363 
2018-02-06 04:27:48.849 UTC [msp/identity] Sign -> DEBU 006 Sign: digest: 7279142B6DCADB92F178A42EB4812C9103108F2AEE8F40F8AD0125D3E13AEC25 
2018-02-06 04:28:51.790 UTC [msp/identity] Sign -> DEBU 007 Sign: plaintext: 0A91070A6708031A0C08C4DDE4D30510...33975E7D10605FC261528FBDEEC0A9A8 
2018-02-06 04:28:51.790 UTC [msp/identity] Sign -> DEBU 008 Sign: digest: 6A3D493ACD5E447FAD3D91C518CD60C45D0DB8E20D5DCFB70B45DA7572C666C0 
2018-02-06 04:28:51.885 UTC [main] main -> INFO 009 Exiting.....
2018-02-06 04:29:02.974 UTC [msp] GetLocalMSP -> DEBU 001 Returning existing local MSP
2018-02-06 04:29:02.974 UTC [msp] GetDefaultSigningIdentity -> DEBU 002 Obtaining default signing identity
2018-02-06 04:29:02.976 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 003 Using default escc
2018-02-06 04:29:02.976 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 004 Using default vscc
2018-02-06 04:29:02.977 UTC [msp/identity] Sign -> DEBU 005 Sign: plaintext: 0A93070A6908031A0C088EDEE4D30510...1A0E0A0A696E69744C65646765720A00 
2018-02-06 04:29:02.977 UTC [msp/identity] Sign -> DEBU 006 Sign: digest: F5979DA908E3058B28762469FEECB498F506FB2A7D62F01ED56C5CCE3354D5CE 
2018-02-06 04:29:03.103 UTC [msp/identity] Sign -> DEBU 007 Sign: plaintext: 0A93070A6908031A0C088EDEE4D30510...EEB1365266BC4EF15DDAB42DD4202559 
2018-02-06 04:29:03.103 UTC [msp/identity] Sign -> DEBU 008 Sign: digest: 027F185369407246B34B7247E6B83E08078761FFA13C43F508CD7257BBF5BC7B 
2018-02-06 04:29:03.113 UTC [chaincodeCmd] chaincodeInvokeOrQuery -> DEBU 009 ESCC invoke result: version:1 response:<status:200 message:"OK" > payload:"\n e\350\256\026\2161o\374\224\311\210g\322\001\234\332Vt\026+\204\034\013\310;\371\234\353\030`:\360\022\267\006\n\240\006\022\205\006\n\006fabcar\022\372\005\032J\n\004CAR0\032B{\"make\":\"Toyota\",\"model\":\"Prius\",\"colour\":\"blue\",\"owner\":\"Tomoko\"}\032G\n\004CAR1\032?{\"make\":\"Ford\",\"model\":\"Mustang\",\"colour\":\"red\",\"owner\":\"Brad\"}\032N\n\004CAR2\032F{\"make\":\"Hyundai\",\"model\":\"Tucson\",\"colour\":\"green\",\"owner\":\"Jin Soo\"}\032N\n\004CAR3\032F{\"make\":\"Volkswagen\",\"model\":\"Passat\",\"colour\":\"yellow\",\"owner\":\"Max\"}\032G\n\004CAR4\032?{\"make\":\"Tesla\",\"model\":\"S\",\"colour\":\"black\",\"owner\":\"Adriana\"}\032K\n\004CAR5\032C{\"make\":\"Peugeot\",\"model\":\"205\",\"colour\":\"purple\",\"owner\":\"Michel\"}\032H\n\004CAR6\032@{\"make\":\"Chery\",\"model\":\"S22L\",\"colour\":\"white\",\"owner\":\"Aarav\"}\032H\n\004CAR7\032@{\"make\":\"Fiat\",\"model\":\"Punto\",\"colour\":\"violet\",\"owner\":\"Pari\"}\032J\n\004CAR8\032B{\"make\":\"Tata\",\"model\":\"Nano\",\"colour\":\"indigo\",\"owner\":\"Valeria\"}\032M\n\004CAR9\032E{\"make\":\"Holden\",\"model\":\"Barina\",\"colour\":\"brown\",\"owner\":\"Shotaro\"}\022\026\n\004lscc\022\016\n\014\n\006fabcar\022\002\010\001\032\003\010\310\001\"\r\022\006fabcar\032\0031.0" endorsement:<endorser:"\n\007Org1MSP\022\200\006-----BEGIN -----\nMIICGjCCAcCgAwIBAgIRAPlwF/rUZUP9mqN4wSml4iswCgYIKoZIzj0EAwIwczEL\nMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBG\ncmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMTcwODMxMDkxNDMyWhcNMjcwODI5MDkxNDMy\nWjBbMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMN\nU2FuIEZyYW5jaXNjbzEfMB0GA1UEAxMWcGVlcjAub3JnMS5leGFtcGxlLmNvbTBZ\nMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHihxW6ks3B2+5XdbAVq3CBgxRRRZ22x\nzzpqnD86nKkz7fBElBuhlXl2K6rTxyY2OBOB0ts8keqZ93xueRGymrajTTBLMA4G\nA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8EAjAAMCsGA1UdIwQkMCKAIEI5qg3Ndtru\nuLoM2nAYUdFFBNMarRst3dusalc2Xkl8MAoGCCqGSM49BAMCA0gAMEUCIQD4j0Rn\ne1rrd0FSCzsR6u+IuuPK5dI/kR/bh7+VLf0TNgIgCfUtkJvfvzVEwZLFoFyjoHtr\ntvwzNUS1U0hEqIaDeo4=\n-----END -----\n" signature:"0E\002!\000\271u\265\3621\223\255|\353h\003\364g\363\3474\310>\032\351\225\326\306z\356\324\013\366\235\334J\237\002 ^>\200AhmDWh\261\301\204Ye\346\345\356\2616Rf\274N\361]\332\264-\324 %Y" > 
2018-02-06 04:29:03.113 UTC [chaincodeCmd] chaincodeInvokeOrQuery -> INFO 00a Chaincode invoke successful. result: status:200 
2018-02-06 04:29:03.113 UTC [main] main -> INFO 00b Exiting.....

Total setup execution time : 136 secs ...


Start by installing required packages run 'npm install'
Then run 'node enrollAdmin.js', then 'node registerUser'

The 'node invoke.js' will fail until it has been updated with valid arguments
The 'node query.js' may be run at anytime once the user has been registered

至此 hyperledger 開發環境已經啟動完畢

node enrollAdmin.js
node registerUser.js 
node invoke.js
node query.js
[root@localhost fabcar]# node enrollAdmin.js
 Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded admin from persistence
Assigned the admin user to the fabric client ::{"name":"admin","mspid":"Org1MSP","roles":null,"affiliation":"","enrollmentSecret":"","enrollment":{"signingIdentity":"9995fba0ac327e43983b07d09a50423de8cb510176484566abfce0cb86e5f594","identity":{"certificate":"-----BEGIN CERTIFICATE-----\nMIIB8TCCAZegAwIBAgIUNH9h0PUYxF1vpUqzEXKRfVc2a7YwCgYIKoZIzj0EAwIw\nczELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh\nbiBGcmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMT\nE2NhLm9yZzEuZXhhbXBsZS5jb20wHhcNMTgwMjA2MDQ0NTAwWhcNMTkwMjA2MDQ0\nNTAwWjAQMQ4wDAYDVQQDEwVhZG1pbjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA\nBEhyVSI9Dl7S2fIYQdiJAB2zeXR9aHIQSVSG7auK3y3yVvABOQPA/Kyn2iMAl4rr\nky/0FYY5B+lxYLLSype/2zKjbDBqMA4GA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8E\nAjAAMB0GA1UdDgQWBBRotEXOHR/h2ZLwHV/eAUT80bIQFTArBgNVHSMEJDAigCBC\nOaoNzXba7ri6DNpwGFHRRQTTGq0bLd3brGpXNl5JfDAKBggqhkjOPQQDAgNIADBF\nAiEAnBH8WJvb24o2eC5VmMvtQMoB8NDBTpdq5RNyVJx97HcCIBhWMM6R7crkL8M7\n3wmZ1lNNkAJmpRoes7cNxO/ak5Xy\n-----END CERTIFICATE-----\n"}}}

[root@localhost fabcar]# node registerUser.js 
 Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded admin from persistence
Successfully registered user1 - secret:ZjzLwIaVjEAV
Successfully enrolled member user "user1" 
User1 was successfully registered and enrolled and is ready to intreact with the fabric network

[root@localhost fabcar]# node query.js 
Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Query has completed, checking results
Response is  [{"Key":"CAR0", "Record":{"colour":"blue","make":"Toyota","model":"Prius","owner":"Tomoko"}},{"Key":"CAR1", "Record":{"colour":"red","make":"Ford","model":"Mustang","owner":"Brad"}},{"Key":"CAR2", "Record":{"colour":"green","make":"Hyundai","model":"Tucson","owner":"Jin Soo"}},{"Key":"CAR3", "Record":{"colour":"yellow","make":"Volkswagen","model":"Passat","owner":"Max"}},{"Key":"CAR4", "Record":{"colour":"black","make":"Tesla","model":"S","owner":"Adriana"}},{"Key":"CAR5", "Record":{"colour":"purple","make":"Peugeot","model":"205","owner":"Michel"}},{"Key":"CAR6", "Record":{"colour":"white","make":"Chery","model":"S22L","owner":"Aarav"}},{"Key":"CAR7", "Record":{"colour":"violet","make":"Fiat","model":"Punto","owner":"Pari"}},{"Key":"CAR8", "Record":{"colour":"indigo","make":"Tata","model":"Nano","owner":"Valeria"}},{"Key":"CAR9", "Record":{"colour":"brown","make":"Holden","model":"Barina","owner":"Shotaro"}}]

invoke.js 腳本會出現下面錯誤

[root@localhost fabcar]# node invoke.js
Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Assigning transaction_id:  424c946e96d43005e4b815f56fa43bd58d1370404f6713b3ce267928d4499b78
error: [client-utils.js]: sendPeersProposal - Promise is rejected: Error: 2 UNKNOWN: chaincode error (status: 500, message: Invalid Smart Contract function name.)
    at new createStatusError (/root/fabric-samples/fabcar/node_modules/grpc/src/client.js:65:15)
    at /root/fabric-samples/fabcar/node_modules/grpc/src/client.js:568:15
Transaction proposal was bad
Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...
Failed to invoke successfully :: Error: Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...

這里出錯,是因為沒有提供相關的調用方法和參數,暫時不去糾結,繼續做實驗。

3.1.1. 智能合約
[root@localhost fabric-samples]# cat chaincode/fabcar/fabcar.go 
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

/*
 * The sample smart contract for documentation topic:
 * Writing Your First Blockchain Application
 */

package main

/* Imports
 * 4 utility libraries for formatting, handling bytes, reading and writing JSON, and string manipulation
 * 2 specific Hyperledger Fabric specific libraries for Smart Contracts
 */
import (
	"bytes"
	"encoding/json"
	"fmt"
	"strconv"

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

// Define the Smart Contract structure
type SmartContract struct {
}

// Define the car structure, with 4 properties.  Structure tags are used by encoding/json library
type Car struct {
	Make   string `json:"make"`
	Model  string `json:"model"`
	Colour string `json:"colour"`
	Owner  string `json:"owner"`
}

/*
 * The Init method is called when the Smart Contract "fabcar" is instantiated by the blockchain network
 * Best practice is to have any Ledger initialization in separate function -- see initLedger()
 */
func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {
	return shim.Success(nil)
}

/*
 * The Invoke method is called as a result of an application request to run the Smart Contract "fabcar"
 * The calling application program has also specified the particular smart contract function to be called, with arguments
 */
func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface) sc.Response {

	// Retrieve the requested Smart Contract function and arguments
	function, args := APIstub.GetFunctionAndParameters()
	// Route to the appropriate handler function to interact with the ledger appropriately
	if function == "queryCar" {
		return s.queryCar(APIstub, args)
	} else if function == "initLedger" {
		return s.initLedger(APIstub)
	} else if function == "createCar" {
		return s.createCar(APIstub, args)
	} else if function == "queryAllCars" {
		return s.queryAllCars(APIstub)
	} else if function == "changeCarOwner" {
		return s.changeCarOwner(APIstub, args)
	}

	return shim.Error("Invalid Smart Contract function name.")
}

func (s *SmartContract) queryCar(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {

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

	carAsBytes, _ := APIstub.GetState(args[0])
	return shim.Success(carAsBytes)
}

func (s *SmartContract) initLedger(APIstub shim.ChaincodeStubInterface) sc.Response {
	cars := []Car{
		Car{Make: "Toyota", Model: "Prius", Colour: "blue", Owner: "Tomoko"},
		Car{Make: "Ford", Model: "Mustang", Colour: "red", Owner: "Brad"},
		Car{Make: "Hyundai", Model: "Tucson", Colour: "green", Owner: "Jin Soo"},
		Car{Make: "Volkswagen", Model: "Passat", Colour: "yellow", Owner: "Max"},
		Car{Make: "Tesla", Model: "S", Colour: "black", Owner: "Adriana"},
		Car{Make: "Peugeot", Model: "205", Colour: "purple", Owner: "Michel"},
		Car{Make: "Chery", Model: "S22L", Colour: "white", Owner: "Aarav"},
		Car{Make: "Fiat", Model: "Punto", Colour: "violet", Owner: "Pari"},
		Car{Make: "Tata", Model: "Nano", Colour: "indigo", Owner: "Valeria"},
		Car{Make: "Holden", Model: "Barina", Colour: "brown", Owner: "Shotaro"},
	}

	i := 0
	for i < len(cars) {
		fmt.Println("i is ", i)
		carAsBytes, _ := json.Marshal(cars[i])
		APIstub.PutState("CAR"+strconv.Itoa(i), carAsBytes)
		fmt.Println("Added", cars[i])
		i = i + 1
	}

	return shim.Success(nil)
}

func (s *SmartContract) createCar(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {

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

	var car = Car{Make: args[1], Model: args[2], Colour: args[3], Owner: args[4]}

	carAsBytes, _ := json.Marshal(car)
	APIstub.PutState(args[0], carAsBytes)

	return shim.Success(nil)
}

func (s *SmartContract) queryAllCars(APIstub shim.ChaincodeStubInterface) sc.Response {

	startKey := "CAR0"
	endKey := "CAR999"

	resultsIterator, err := APIstub.GetStateByRange(startKey, endKey)
	if err != nil {
		return shim.Error(err.Error())
	}
	defer resultsIterator.Close()

	// buffer is a JSON array containing QueryResults
	var buffer bytes.Buffer
	buffer.WriteString("[")

	bArrayMemberAlreadyWritten := false
	for resultsIterator.HasNext() {
		queryResponse, err := resultsIterator.Next()
		if err != nil {
			return shim.Error(err.Error())
		}
		// Add a comma before array members, suppress it for the first array member
		if bArrayMemberAlreadyWritten == true {
			buffer.WriteString(",")
		}
		buffer.WriteString("{\"Key\":")
		buffer.WriteString("\"")
		buffer.WriteString(queryResponse.Key)
		buffer.WriteString("\"")

		buffer.WriteString(", \"Record\":")
		// Record is a JSON object, so we write as-is
		buffer.WriteString(string(queryResponse.Value))
		buffer.WriteString("}")
		bArrayMemberAlreadyWritten = true
	}
	buffer.WriteString("]")

	fmt.Printf("- queryAllCars:\n%s\n", buffer.String())

	return shim.Success(buffer.Bytes())
}

func (s *SmartContract) changeCarOwner(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {

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

	carAsBytes, _ := APIstub.GetState(args[0])
	car := Car{}

	json.Unmarshal(carAsBytes, &car)
	car.Owner = args[1]

	carAsBytes, _ = json.Marshal(car)
	APIstub.PutState(args[0], carAsBytes)

	return shim.Success(nil)
}

// The main function is only relevant in unit test mode. Only included here for completeness.
func main() {

	// Create a new Smart Contract
	err := shim.Start(new(SmartContract))
	if err != nil {
		fmt.Printf("Error creating new Smart Contract: %s", err)
	}
}
3.1.2. 創建記錄
[root@localhost fabcar]# cp invoke.js createCar.js
[root@localhost fabcar]# vim createCar.js
var request = {
                //targets: let default to the peer assigned to the client
                chaincodeId: 'fabcar',
                fcn: '',
                args: [''],
                chainId: 'mychannel',
                txId: tx_id
        };

改為

var request = {
		//targets: let default to the peer assigned to the client
		chaincodeId: 'fabcar',
		fcn: 'createCar',
		args: ['CAR10', 'Chevy', 'Volt', 'Red', 'Nick'],
		chainId: 'mychannel',
		txId: tx_id
	};

運行結果

[root@localhost fabcar]# node createCar.js 
Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Assigning transaction_id:  907d35d7c5debf952f28135b2c341797acdb7ef1f1389607fb04891a27e8ba19
Transaction proposal was good
Successfully sent Proposal and received ProposalResponse: Status - 200, message - "OK"
info: [EventHub.js]: _connect - options {}
The transaction has been committed on peer localhost:7053
Send transaction promise and event listener promise have completed
Successfully sent transaction to the orderer.
Successfully committed the change to the ledger by the peer
3.1.3. 查詢單條記錄

查找 CAR5 這條記錄的數據。

[root@localhost fabcar]# node queryOne.js 
Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Query has completed, checking results
Response is  {"colour":"purple","make":"Peugeot","model":"205","owner":"Michel"}
[root@localhost fabcar]# cat queryOne.js 
'use strict';
/*
* Copyright IBM Corp All Rights Reserved
*
* SPDX-License-Identifier: Apache-2.0
*/
/*
 * Chaincode query
 */

var Fabric_Client = require('fabric-client');
var path = require('path');
var util = require('util');
var os = require('os');

//
var fabric_client = new Fabric_Client();

// setup the fabric network
var channel = fabric_client.newChannel('mychannel');
var peer = fabric_client.newPeer('grpc://localhost:7051');
channel.addPeer(peer);

//
var member_user = null;
var store_path = path.join(__dirname, 'hfc-key-store');
console.log('Store path:'+store_path);
var tx_id = null;

// create the key value store as defined in the fabric-client/config/default.json 'key-value-store' setting
Fabric_Client.newDefaultKeyValueStore({ path: store_path
}).then((state_store) => {
	// assign the store to the fabric client
	fabric_client.setStateStore(state_store);
	var crypto_suite = Fabric_Client.newCryptoSuite();
	// use the same location for the state store (where the users' certificate are kept)
	// and the crypto store (where the users' keys are kept)
	var crypto_store = Fabric_Client.newCryptoKeyStore({path: store_path});
	crypto_suite.setCryptoKeyStore(crypto_store);
	fabric_client.setCryptoSuite(crypto_suite);

	// get the enrolled user from persistence, this user will sign all requests
	return fabric_client.getUserContext('user1', true);
}).then((user_from_store) => {
	if (user_from_store && user_from_store.isEnrolled()) {
		console.log('Successfully loaded user1 from persistence');
		member_user = user_from_store;
	} else {
		throw new Error('Failed to get user1.... run registerUser.js');
	}

	// queryCar chaincode function - requires 1 argument, ex: args: ['CAR4'],
	// queryAllCars chaincode function - requires no arguments , ex: args: [''],
	const request = {
		//targets : --- letting this default to the peers assigned to the channel
		chaincodeId: 'fabcar',
		fcn: 'queryCar',
		args: ['CAR10']
	};

	// send the query proposal to the peer
	return channel.queryByChaincode(request);
}).then((query_responses) => {
	console.log("Query has completed, checking results");
	// query_responses could have more than one  results if there multiple peers were used as targets
	if (query_responses && query_responses.length == 1) {
		if (query_responses[0] instanceof Error) {
			console.error("error from query = ", query_responses[0]);
		} else {
			console.log("Response is ", query_responses[0].toString());
		}
	} else {
		console.log("No payloads were returned from query");
	}
}).catch((err) => {
	console.error('Failed to query successfully :: ' + err);
});

運行結果

[root@localhost fabcar]# node queryOne.js 
Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Query has completed, checking results
Response is  {"colour":"Red","make":"Chevy","model":"Volt","owner":"Nick"}
3.1.4. 修改汽車所有者
[root@localhost fabcar]# cp invoke.js changeCarOwner.js
[root@localhost fabcar]# vim changeCarOwner.js
var request = {
                //targets: let default to the peer assigned to the client
                chaincodeId: 'fabcar',
                fcn: '',
                args: [''],
                chainId: 'mychannel',
                txId: tx_id
        };

修改為

var request = {
                //targets: let default to the peer assigned to the client
                chaincodeId: 'fabcar',
                fcn: 'changeCarOwner',
                args: ['CAR10', 'Neo'],
                chainId: 'mychannel',
                txId: tx_id
        };

運行結果

[root@localhost fabcar]# node changeCarOwner.js 
Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Assigning transaction_id:  b183a7bac6161ff7c7e9974e20bb1a72b2ac5f11ab698a2ae4f63cfdbc33a735
Transaction proposal was good
Successfully sent Proposal and received ProposalResponse: Status - 200, message - "OK"
info: [EventHub.js]: _connect - options {}
The transaction has been committed on peer localhost:7053
Send transaction promise and event listener promise have completed
Successfully sent transaction to the orderer.
Successfully committed the change to the ledger by the peer


[root@localhost fabcar]# node queryOne.js 
Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Query has completed, checking results
Response is  {"colour":"Red","make":"Chevy","model":"Volt","owner":"Neo"}

現在我們可以看到 所有者已經改為 Neo

3.2. balance-transfer

[root@localhost fabric-samples]# cd balance-transfer/
[root@localhost balance-transfer]# ./runApp.sh 

Stopping peer0.org1.example.com ... done
Stopping peer0.org2.example.com ... done
Stopping peer1.org2.example.com ... done
Stopping peer1.org1.example.com ... done
Stopping ca_peerOrg1 ... done
Stopping orderer.example.com ... done
Stopping ca_peerOrg2 ... done
Removing peer0.org1.example.com ... done
Removing peer0.org2.example.com ... done
Removing peer1.org2.example.com ... done
Removing peer1.org1.example.com ... done
Removing ca_peerOrg1 ... done
Removing orderer.example.com ... done
Removing ca_peerOrg2 ... done
Removing network artifacts_default

========== No containers available for deletion ==========


========== No images available for deletion ===========

Creating network "artifacts_default" with the default driver
Creating ca_peerOrg2
Creating orderer.example.com
Creating ca_peerOrg1
Creating peer1.org2.example.com
Creating peer0.org2.example.com
Creating peer0.org1.example.com
Creating peer1.org1.example.com
/root/fabric-samples/balance-transfer


============== node modules installed already =============

[2018-02-06 09:14:54.916] [DEBUG] Helper - [crypto_ecdsa_aes]: constructor, keySize: 256
[2018-02-06 09:14:54.921] [DEBUG] Helper - [crypto_ecdsa_aes]: Hash algorithm: SHA2, hash output size: 256
[2018-02-06 09:14:55.046] [DEBUG] Helper - [utils.CryptoKeyStore]: CryptoKeyStore, constructor - start
[2018-02-06 09:14:55.048] [DEBUG] Helper - [utils.CryptoKeyStore]: constructor, no super class specified, using config: fabric-client/lib/impl/FileKeyValueStore.js
[2018-02-06 09:14:55.056] [DEBUG] Helper - [crypto_ecdsa_aes]: constructor, keySize: 256
[2018-02-06 09:14:55.056] [DEBUG] Helper - [crypto_ecdsa_aes]: Hash algorithm: SHA2, hash output size: 256
[2018-02-06 09:14:55.057] [DEBUG] Helper - [utils.CryptoKeyStore]: CryptoKeyStore, constructor - start
[2018-02-06 09:14:55.057] [DEBUG] Helper - [utils.CryptoKeyStore]: constructor, no super class specified, using config: fabric-client/lib/impl/FileKeyValueStore.js
[2018-02-06 09:14:55.082] [INFO] SampleWebApp - ****************** SERVER STARTED ************************
[2018-02-06 09:14:55.082] [INFO] SampleWebApp - **************  http://localhost:4000  ******************

安裝 jq 工具

yum install -y jq

API 測試結果

[root@localhost balance-transfer]# ./testAPIs.sh 
POST request Enroll on Org1  ...

{"success":true,"secret":"uXlJIPvBgLbh","message":"Jim enrolled Successfully","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTc5NjMwMDUsInVzZXJuYW1lIjoiSmltIiwib3JnTmFtZSI6Im9yZzEiLCJpYXQiOjE1MTc5MjcwMDV9.pBqwAVac32NIA_x5S163h9_lRfIHMx4shX05D0geO5k"}

ORG1 token is eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTc5NjMwMDUsInVzZXJuYW1lIjoiSmltIiwib3JnTmFtZSI6Im9yZzEiLCJpYXQiOjE1MTc5MjcwMDV9.pBqwAVac32NIA_x5S163h9_lRfIHMx4shX05D0geO5k

POST request Enroll on Org2 ...

{"success":true,"secret":"kXcltqsAoiDf","message":"Barry enrolled Successfully","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTc5NjMwMDcsInVzZXJuYW1lIjoiQmFycnkiLCJvcmdOYW1lIjoib3JnMiIsImlhdCI6MTUxNzkyNzAwN30.ePexFJ2r9WoYNma5iKomJu3anEvg3PTgBEqI6K-s6F0"}

ORG2 token is eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTc5NjMwMDcsInVzZXJuYW1lIjoiQmFycnkiLCJvcmdOYW1lIjoib3JnMiIsImlhdCI6MTUxNzkyNzAwN30.ePexFJ2r9WoYNma5iKomJu3anEvg3PTgBEqI6K-s6F0


POST request Create channel  ...

{"success":true,"message":"Channel 'mychannel' created Successfully"}

POST request Join channel on Org1

{"success":true,"message":"Successfully joined peers in organization org1 to the channel 'mychannel'"}

POST request Join channel on Org2

{"success":true,"message":"Successfully joined peers in organization org2 to the channel 'mychannel'"}

POST Install chaincode on Org1

Successfully Installed chaincode on organization org1

POST Install chaincode on Org2

Successfully Installed chaincode on organization org2

POST instantiate chaincode on peer1 of Org1

Failed to order the transaction. Error code: undefined

POST invoke chaincode on peers of Org1 and Org2

Transacton ID is Failed to order the transaction. Error code: undefined


GET query chaincode on peer1 of Org1

a now has Error: 2 UNKNOWN: could not find chaincode with name 'mycc' - make sure the chaincode mycc has been successfully instantiated and try again after the move

GET query Block by blockNumber

Error: 2 UNKNOWN: chaincode error (status: 500, message: Failed to get block number 1, error Entry not found in index)
    at new createStatusError (/root/fabric-samples/balance-transfer/node_modules/grpc/src/client.js:65:15)
    at /root/fabric-samples/balance-transfer/node_modules/grpc/src/client.js:568:15

GET query Transaction by TransactionID

Error: 2 UNKNOWN: chaincode error (status: 500, message: Failed to get transaction with id Failed, error Entry not found in index)
    at new createStatusError (/root/fabric-samples/balance-transfer/node_modules/grpc/src/client.js:65:15)
    at /root/fabric-samples/balance-transfer/node_modules/grpc/src/client.js:568:15


GET query ChainInfo

{"height":{"low":1,"high":0,"unsigned":true},"currentBlockHash":{"buffer":{"type":"Buffer","data":[8,1,18,32,180,19,234,224,76,239,188,107,147,219,120,185,108,73,201,120,81,0,242,221,32,3,94,175,16,200,181,113,100,97,129,57]},"offset":4,"markedOffset":-1,"limit":36,"littleEndian":true,"noAssert":false},"previousBlockHash":{"buffer":{"type":"Buffer","data":[]},"offset":0,"markedOffset":-1,"limit":0,"littleEndian":false,"noAssert":false}}

GET query Installed chaincodes

["name: mycc, version: v0, path: github.com/example_cc"]

GET query Instantiated chaincodes

[]

GET query Channels

{"channels":[{"channel_id":"mychannel"}]}

Total execution time : 364 secs ...

上面 ERROR 可能是因為 hyperledger v1.0.5 版本的緣故。此時的 fabric-samples 僅僅支持 v1.0.0。

4. Hyperledger Composer

Build Blockchain applications and business networks your way

https://hyperledger.github.io/composer/

5. Restful 接口

5.1. 注冊

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST -d '
{

    "enrollId": "jim",
    "enrollSecret": "6avZQLwcUe9b"

}' http://localhost:7050/registrar

5.2. 

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST -d '
{

   "jsonrpc": "2.0",
   "method": "deploy",
   "params": {
    "type": 1,
    "chaincodeID":{
        "name": "mycc"
    },
    "ctorMsg": {
         "function":"init",
         "args":[]
     },
    "secureContext": "jim"
  },
   "id": 1

}' http://localhost:7050/chaincode

6. Hyperledger Fabric Client SDK for Node.js

6.1. package.json

[root@localhost fabcar]# cat package.json 
{
    "name": "fabcar",
    "version": "1.0.0",
    "description": "Hyperledger Fabric Car Sample Application",
    "main": "fabcar.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "dependencies": {
        "fabric-ca-client": "^1.0.2",
        "fabric-client": "^1.0.2",
        "grpc": "^1.6.0"
    },
    "author": "Anthony O'Dowd",
    "license": "Apache-2.0",
    "keywords": [
        "Hyperledger",
        "Fabric",
        "Car",
        "Sample",
        "Application"
    ]
}

7. fabric-sdk-java

7.1. Maven

<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.0.1</version>
		</dependency>

	</dependencies>
</project>

8. FAQ

8.1. 

ERROR: manifest for hyperledger/fabric-orderer:latest not found
ERROR: manifest for hyperledger/fabric-couchdb:latest not found
ERROR: manifest for hyperledger/fabric-ca:latest not found	
ERROR: manifest for hyperledger/fabric-tools:latest not found

解決方案

docker pull hyperledger/fabric-membersrvc:latest \
&& docker pull hyperledger/fabric-peer:x86_64-1.0.5 \
&& docker pull hyperledger/fabric-orderer:x86_64-1.0.5 \
&& docker pull hyperledger/fabric-couchdb:x86_64-1.0.5 \
&& docker pull hyperledger/fabric-ca:x86_64-1.0.5 \
&& docker pull hyperledger/fabric-tools:x86_64-1.0.5

docker tag hyperledger/fabric-peer:x86_64-1.0.5 hyperledger/fabric-peer \
&& docker tag hyperledger/fabric-orderer:x86_64-1.0.5 hyperledger/fabric-orderer \
&& docker tag hyperledger/fabric-couchdb:x86_64-1.0.5 hyperledger/fabric-couchdb \
&& docker tag hyperledger/fabric-ca:x86_64-1.0.5 hyperledger/fabric-ca \
&& docker tag hyperledger/fabric-tools:x86_64-1.0.5 hyperledger/fabric-tools

8.2. 卸載 hyperledger 環境

docker rmi -f $(docker images -q)

以上是“hyperledger v1.0.5區塊鏈的示例分析”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

平乐县| 葵青区| 定边县| 车险| 房产| 凤凰县| 舒城县| 旬阳县| 临湘市| 高雄市| 阿拉善盟| 阿克苏市| 深泽县| 常宁市| 安岳县| 凉山| 枝江市| 绿春县| 高尔夫| 大余县| 信宜市| 玉树县| 平凉市| 墨竹工卡县| 青龙| 广河县| 咸宁市| 永修县| 兴国县| 宁晋县| 郯城县| 阿瓦提县| 治县。| 体育| 襄城县| 河西区| 雷州市| 灵武市| 铜陵市| 雅安市| 左贡县|