温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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