【翻译】Fabric2.0官方教程文档Using the Fabric test network(施工中)

本文档翻译了Fabric2.0官方测试网络的使用教程,包括开始前的准备、建立测试网络、创建通道、启动链码、与网络交互、关闭网络等内容。在建立网络时,会涉及证书授权的选项,以及使用脚本创建和管理通道、链码。此外,还介绍了如何通过命令行与网络进行交互和故障排除。
摘要由CSDN通过智能技术生成

Fabric2.0官方教程文档未翻译部分即Using the Fabric test network(施工中)

地址

非正文部分

相比起英文文档,官方的中文教程在翻译上有比较大的滞后性,而且2.0的版本还有一些校对上的问题
尤其是Using the Fabric test network这一部分最新版本没有中文翻译
试着翻译了其中的一部分,其他的看着翻译。
非专业,非机翻,但术语不熟,如果看了感到疑惑,请对照上面地址的英文原文进行对照。
需要注意的是,fabric的测试网络或者说测试样例变动频繁,比如1.2的版本用的e2e已经移除了
2.2版本的文档虽说在教程里依旧用的fabcar当做范例,但是可以注意到实际上test_network里头默认安装的链码叫做basic,也能注意到network.sh里头deployCC不再会当你安装链码的同时给你激活初始化程序了。
虽然内容上大同小异,但是严格按照教程走是断断不行的。
当然,fabcar链码已经被独立于chaincode文件夹之外。
在***writing your first application***章节你会再次遇见它。

Before you begin/开始之前

在你开始运行测试网络之前,你需要先克隆fabric-samples仓库并下载Fabric相关镜像。
确认你已经安装了所有的前置条件并安装了Samples、二进制文件、Docker镜像

Bring up the test network/建立测试网络

你可以在fabric-samples仓库下的test-network路径找到这个用于搭建网络的脚本。
通过以下命令可以导航至测试网络的路径。

cd fabric-samples/test-network

在该路径里,你可以看到一个带注释的脚本,即network.sh,它能通过你本地机器上的docker镜像建立一个Fabric网络。你可以通过运行 run ./network.sh -h来输出帮助文档:

Usage:
  network.sh <Mode> [Flags]
    <Mode>
      - 'up' - bring up fabric orderer and peer nodes. No channel is created
      - 'up createChannel' - bring up fabric network with one channel
      - 'createChannel' - create and join a channel after the network is created
      - 'deployCC' - deploy the fabcar chaincode on the channel
      - 'down' - clear the network with docker-compose down
      - 'restart' - restart the network

    Flags:
    -ca <use CAs> -  create Certificate Authorities to generate the crypto material
    -c <channel name> - channel name to use (defaults to "mychannel")
    -s <dbtype> - the database backend to use: goleveldb (default) or couchdb
    -r <max retry> - CLI times out after certain number of attempts (defaults to 5)
    -d <delay> - delay duration in seconds (defaults to 3)
    -l <language> - the programming language of the chaincode to deploy: go (default), javascript, or java
    -v <version>  - chaincode version. Must be a round number, 1, 2, 3, etc
    -i <imagetag> - the tag to be used to launch the network (defaults to "latest")
    -verbose - verbose mode
  network.sh -h (print this message)

 Possible Mode and flags
  network.sh up -ca -c -r -d -s -i -verbose
  network.sh up createChannel -ca -c -r -d -s -i -verbose
  network.sh createChannel -c -r -d -verbose
  network.sh deployCC -l -v -r -d -verbose

 Taking all defaults:
    network.sh up

 Examples:
  network.sh up createChannel -ca -c mychannel -s couchdb -i 2.0.0-beta
  network.sh createChannel -c channelName
  network.sh deployCC -l javascript

在test-network目录内,运行以下指令来清除所有由前次运行遗留的容器和构件:

./network.sh down

之后你便可以通过发布以下命令来建立网络。若你在其他的目录下运行该脚本则会遇到问题。

./network.sh up

该命令创建一个由两个对等节点、一个排序节点构成的Fabric网络。当你运行./network.sh up时,尚未创建任何通道,我们将在下一步实现它。如果这条指令被顺利执行,那么脚本会输出两条像这样的关于节点被顺利创建的记录:

Creating network "net_test" with the default driver
Creating volume "net_orderer.example.com" with default driver
Creating volume "net_peer0.org1.example.com" with default driver
Creating volume "net_peer0.org2.example.com" with default driver
Creating orderer.example.com    ... done
Creating peer0.org2.example.com ... done
Creating peer0.org1.example.com ... done
CONTAINER ID        IMAGE                               COMMAND             CREATED             STATUS                  PORTS                              NAMES
8d0c74b9d6af        hyperledger/fabric-orderer:latest   "orderer"           4 seconds ago       Up Less than a second   0.0.0.0:7050->7050/tcp             orderer.example.com
ea1cf82b5b99        hyperledger/fabric-peer:latest      "peer node start"   4 seconds ago       Up Less than a second   0.0.0.0:7051->7051/tcp             peer0.org1.example.com
cd8d9b23cb56        hyperledger/fabric-peer:latest      "peer node start"   4 seconds ago       Up 1 second             7051/tcp, 0.0.0.0:9051->9051/tcp   peer0.org2.example.com

如果没得到该结果,请跳转到文章的故障排除环节来查阅可能是哪里出错了。默认状况下,网络将使用cryptogen工具来建立网络。同样的,你也能够使用证书颁发机构(CA)机制 来建立你的网络。

Creating a channel/创建通道

既然我们已经在机器上运行了peer节点和排序节点,我们可以使用脚本来为Org1和Org2之间的交易创建一个通道。通道提供了特定网络成员之间的加密交流层。通道仅仅可以被邀请加入通道的组织使用,并列对于其余网络上的成员并不可见。各个通道有着单独的区块链账本。受邀加入的组织们将他们的对等节点加入通道来存储通道账本并验证通道上的交易。

Now that we have peer and orderer nodes running on our machine, we can
use the script to create a Fabric channel for transactions between
Org1 and Org2. Channels are a private layer of communication between
specific network members. Channels can be used only by organizations
that are invited to the channel, and are invisible to other members of
the network. Each channel has a separate blockchain ledger.
Organizations that have been invited “join” their peers to the channel
to store the channel ledger and validate the transactions on the
channel.

You can use the network.sh script to create a channel between Org1 and Org2 and join their peers to the channel. Run the following command to create a channel with the default name of mychannel:

./network.sh createChannel

If the command was successful, you can see the following message printed in your logs:

========= Channel successfully joined ===========

You can also use the channel flag to create a channel with custom name. As an example, the following command would create a channel named channel1:

./network.sh createChannel -c channel1

The channel flag also allows you to create multiple channels by specifying different channel names. After you create mychannel or channel1, you can use the command below to create a second channel named channel2:

./network.sh createChannel -c channel2

如果你想一步到位地在建立网络的同时创建通道,你可以在命令里将up和creatChannel模式一并使用:

./network.sh up createChannel

Starting a chaincode on the channel/在通道上开始你的链码

当你创建完通道之后,你可以开始用智能合约和你的通道账本进行交互。智能合约包含管理链上账本中资产的业务逻辑(business logic)。由成员运行的应用可以激活智能合约来在账本上创建资产,或者改变和转移那些资产。应用程序也能够通过智能合约查询账本上的数据。
为保证交易是有效的,智能合约创建的交易通常需要被多个组织签名以提交给通道账本。对于Fabric的模型而言,多重签名是不可或缺的。对于一笔交易要求多重背书,可以防止通道上的单一组织篡改对等伙伴间的账本或者是启用未经过同意的业务逻辑。为签名一份交易,每个组织需要激活并执行与对等伙伴之间、为交易的输出签名的智能合约。假如交易输出是一致的,并且已经有足够多的的组织签名了交易,交易就能被提交给账本。指定了通道上需要执行智能合约的特定组织的策略,称为背书策略,该策略是为每个链码设置的,作为链码定义的一部分。
(The policy that specifies the set organizations on the channel that need to execute the smart contract is referred to as the endorsement policy, which is set for each chaincode as part of the chaincode definition.)

In Fabric, smart contracts are deployed on the network in packages referred to as chaincode. A Chaincode is installed on the peers of an organization and then deployed to a channel, where it can then be used to endorse transactions and interact with the blockchain ledger. Before a chaincode can be deployed to a channel, the members of the channel need to agree on a chaincode definition that establishes chaincode governance. When the required number of organizations agree, the chaincode definition can be committed to the channel, and the chaincode is ready to be used.

当你使用network.sh命令创建完通道后,你可以在通道上用如下指令启用你的链码:

./network.sh deployCC

The deployCC subcommand will install the fabcar chaincode on peer0.org1.example.com and peer0.org2.example.com and then deploy the chaincode on the channel specified using the channel flag (or mychannel if no channel is specified). If are deploying a chaincode for the first time, the script will install the chaincode dependencies. By default, The script installs the Golang version of the fabcar chaincode. However, you can use the language flag, -l, to install the Java or javascript versions of the chaincode.

After the fabcar chaincode definition has been committed to the channel, the script initializes the chaincode by invoking the init function and then invokes the chaincode to put an initial list of cars on the ledger. The script then queries the chaincode to verify the that the data was added. If the chaincode was installed, deployed, and invoked correctly, you should see the following list of cars printed in your logs:

[{"Key":"CAR0", "Record":{"make":"Toyota","model":"Prius","colour":"blue","owner":"Tomoko"}},{"Key":"CAR1", "Record":{"make":"Ford","model":"Mustang","colour":"red","owner":"Brad"}},{"Key":"CAR2", "Record":{"make":"Hyundai","model":"Tucson","colour":"green","owner":"Jin Soo"}},{"Key":"CAR3", "Record":{"make":"Volkswagen","model":"Passat","colour":"yellow","owner":"Max"}},{"Key":"CAR4", "Record":{"make":"Tesla","model":"S","colour":"black","owner":"Adriana"}},{"Key":"CAR5", "Record":{"make":"Peugeot","model":"205","colour":"purple","owner":"Michel"}},{"Key":"CAR6", "Record":{"make":"Chery","model":"S22L","colour":"white","owner":"Aarav"}},{"Key":"CAR7", "Record":{"make":"Fiat","model":"Punto","colour":"violet","owner":"Pari"}},{"Key":"CAR8", "Record":{"make":"Tata","model":"Nano","colour":"indigo","owner":"Valeria"}},{"Key":"CAR9", "Record":{"make":"Holden","model":"Barina","colour":"brown","owner":"Shotaro"}}]
===================== Query successful on peer0.org1 on channel 'mychannel' =====================

Interacting with the network/与网络交互

当你建立起测试网络之后,你可以使用peer命令行界面和你的网络进行交互
peer命令行界面允许你激活已经部署的智能合约,更新通道,
或者从命令行界面安装并部署一个新的智能合约。
请确认你正在测试网络目录里进行下述操作。如果按照“安装样例、二进制文件和容器镜像”的指引
你可以在fabric-samples里的bin文件夹内找到peer的二进制文件。用以下指令可以将这些二进制文件添加到你的命令行界面路径里

export PATH=${PWD}/../bin:${PWD}:$PATH

你同时需要设置好FABRIC_CFG_PATH路径到fabric-samples仓库里头core.yaml所在的位置。
这之后,你便可以如下设置环境变量,以便于使你能够以Orag1的身份操作peer命令行界面
CORE_PEER_TLS_ROOTCERT_FILECORE_PEER_MSPCONFIGPATH 环境变量指向Org1的加密材料所在的organizations文件夹
如果你使用过./network.sh deployCC安装和启动了fabcar链码,你便可以从命令行界面向账本进行查询。
使用如下指令可以获得已经被添加在你的通道账本内的所有车辆列表。

peer chaincode query -C mychannel -n fabcar -c '{"Args":["queryAllCars"]}'

如果这条命令被操作成功。你可以看到程序运行时会有和下面一样的车辆列表被打印在日志内。

[{"Key":"CAR0", "Record":{"make":"Toyota","model":"Prius","colour":"blue","owner":"Tomoko"}},{"Key":"CAR1", "Record":{"make":"Ford","model":"Mustang","colour":"red","owner":"Brad"}},{"Key":"CAR2", "Record":{"make":"Hyundai","model":"Tucson","colour":"green","owner":"Jin Soo"}},{"Key":"CAR3", "Record":{"make":"Volkswagen","model":"Passat","colour":"yellow","owner":"Max"}},{"Key":"CAR4", "Record":{"make":"Tesla","model":"S","colour":"black","owner":"Adriana"}},{"Key":"CAR5", "Record":{"make":"Peugeot","model":"205","colour":"purple","owner":"Michel"}},{"Key":"CAR6", "Record":{"make":"Chery","model":"S22L","colour":"white","owner":"Aarav"}},{"Key":"CAR7", "Record":{"make":"Fiat","model":"Punto","colour":"violet","owner":"Pari"}},{"Key":"CAR8", "Record":{"make":"Tata","model":"Nano","colour":"indigo","owner":"Valeria"}},{"Key":"CAR9", "Record":{"make":"Holden","model":"Barina","colour":"brown","owner":"Shotaro"}}]

当一个网络成员打算转移或者变更一项账本上的资产时,链码会被激活。用下述的命令可以通过激活链码的方式,改变账本上一辆车的归属权。

peer chaincode invoke -o localhost:7050 --ordererTLSHostnameOverride orderer.example.com --tls true --cafile ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C mychannel -n fabcar --peerAddresses localhost:7051 --tlsRootCertFiles ${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt --peerAddresses localhost:9051 --tlsRootCertFiles ${PWD}/organizations/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt -c '{"function":"changeCarOwner","Args":["CAR9","Dave"]}'

如果指令被成功运行,你将看到如下的反馈:

2019-12-04 17:38:21.048 EST [chaincodeCmd] chaincodeInvokeOrQuery -> INFO 001 Chaincode invoke successful. result: status:200

由于fabcar链码的背书策略需要交易被Org1和Org2两个组织签署,链码激活指令同时需要使用"--peerAddresses"标识指向peer0.org1.example.compeer0.org2.example.com
由于TLS已经在网络上被激活了,该命令还需要通过–tlsRootCertFiles标识为每个peer节点引用TLS证书。
在激活了链码之后,我们可以用另一条指令去查询上条指令如何变更了区块链账本上的资产。由于我们已经查询过Org1 peer节点,我们不妨运用这个机会去查询Org2 peer节点上运行的链码

# Environment variables for Org2
export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org2MSP"
export CORE_PEER_TLS_ROOTCERT_FILE=${PWD}/organizations/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt
export CORE_PEER_MSPCONFIGPATH=${PWD}/organizations/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp
export CORE_PEER_ADDRESS=localhost:9051

现在,你可以查询在peer0.org2.example.com组织上运行的fabcar链码了:

peer chaincode query -C mychannel -n fabcar -c '{"Args":["queryAllCars"]}'

Bring down the network/关闭网络

当你完成测试网络的使用时,你可以通过下列指令来关闭测试网络

./network.sh down

该指令将停止和移除节点和链码容器,删除组织的加密材料,并在你的docker注册表内移除链码镜像。该指令也能移除上一次运行产生的通道工件(channel artifacts)和docker的卷(docker volumes),以便于你在遇到任何问题时使用./network.sh up重新启动网络。

Bring up the network with Certificate Authorities/通过证书授权的方式建立网络

超级账本 fabric使用公钥设施(PKI)来认证所有网络成员的行为。对任意节点、网络管理员和提交交易的用户需要拥有一个公共证书和私钥来认证他的身份。
这些身份需要有一个有效的信任源(root of trust),以确信证书和私钥由网络上的成员发布。
network.sh脚本需要在他创建和编排节点前,生成部署和操作网络所需的加密材料(crypto material)。
默认情况下,脚本运用名为cryptogen的(二进制文件)工具来产生所需的证书和私钥。该工具供开发和测试使用,且可以快速地通过可信源创建fabric组织所需的加密材料
当你运行 ./network.sh up ,你可以看见cryptogen工具为Org1,Org2和排序Org生成证书和节点。

creating Org1, Org2, and ordering service organization with crypto from 'cryptogen'

/Usr/fabric-samples/test-network/../bin/cryptogen

##########################################################
##### Generate certificates using cryptogen tool #########
##########################################################

##########################################################
############ Create Org1 Identities ######################
##########################################################
+ cryptogen generate --config=./organizations/cryptogen/crypto-config-org1.yaml --output=organizations
org1.example.com
+ res=0
+ set +x
##########################################################
############ Create Org2 Identities ######################
##########################################################
+ cryptogen generate --config=./organizations/cryptogen/crypto-config-org2.yaml --output=organizations
org2.example.com
+ res=0
+ set +x
##########################################################
############ Create Orderer Org Identities ###############
##########################################################
+ cryptogen generate --config=./organizations/cryptogen/crypto-config-orderer.yaml --output=organizations
+ res=0
+ set +x

当然,network.sh同样提供了通过证书授权机构来建立网络的选项。在生产环境网络,每个组织会运行一个证书颁发机构(或者多个中间证书颁发机构/or multiple intermediate CAs)来创建一个属于该组织的认证身份。
所有由同一个组织的证书颁发机构创建的身份共用相同的信任源。尽管用CA运行网络比起通过cryptogen要花费更多的时间,但用CA启动网络可以为将部署的生产环境网络提供一个简介/入门(introduction)。此外,建立Fabric证书颁发机构让你可以用FabricSDKS注册用户身份并创建可由你的应用使用的证书和私钥。(?这段不确定,建议自行对照原文)

Standing up the Fabric CAs also provides you with the ability to
enroll a client identity using the Fabric SDKs and create a
certificate and private key that can be used by your application.

无论是经由证书授权机构还是cryptogen建立网络,生成的加密材料都存放于organizations文件夹内。
如果你希望通过FabricCAs来建立网络,首先使用下列命令关闭已经运行的网络

./network.sh down

随后你可以运用CA标识来启动网络

./network.sh up -ca

当你执行了命令后,你可以看到脚本建立起三个证书颁发机构,网络里的每个组织各有一个。

##########################################################
##### Generate certificates using Fabric CA's ############
##########################################################
Creating network "net_default" with the default driver
Creating ca_org2    ... done
Creating ca_org1    ... done
Creating ca_orderer ... done

该脚本用FabricCA客户端来登录属于各个组织的用户并为每个身份生成证书和密钥。你能在organizations/fabric-ca目录下的registerEnroll.sh脚本当中找到设置网络的相关指令。
想要了解更多的有关如何使用Fabric CA来部署Fabric网络的内容,请访问Fabric CA操作指南。你可以通过访问身份(indentity)和成员资格(membership)的概念话题来了解fabric如何运作PKI(公钥基础设施)。

What’s happening behind the scenes?/ 上述场景的背后即运行这些指令背后发生了什么?

如果你想更多地了解样例网络,你可以查看test-network目录下的文件和脚本。下面提供的步骤将为你解密当你发布./network.sh up指令时将发生什么。
./network.sh 为两个对等组织和排序组织创建证书和密钥。脚本在默认情况下根据organizations/cryptogen文件夹下的配置文件运行cryptogen。
如果你用-ca标识符来创建证书颁发机构,

./network.sh creates the certificates and keys for two peer organizations and the orderer organization. By default, the script uses the cryptogen tool using the configuration files located in the organizations/cryptogen folder. If you use the -ca flag to create Certificate Authorities, the script uses Fabric CA server configuration files and registerEnroll.sh script located in the organizations/fabric-ca folder. Both cryptogen and the Fabric CAs create the crypto material and MSP folders for all three organizations in the organizations folder.
The script uses configtxgen tool to create the system channel genesis block. Configtxgen consumes the TwoOrgsOrdererGenesis channel profile in the configtx/configtx.yaml file to create the genesis block. The block is stored in the system-genesis-block folder.
Once the organization crypto material and the system channel genesis block have been generated, the network.sh can bring up the nodes of the netwowrk. The script uses the docker-compose-test-net.yaml file in the docker folder to create the peer and orderer nodes. The docker folder also contains the docker-compose-e2e.yaml file that brings up the nodes of the network alongside three Fabric CAs. This file is meant to be used to run end-to-end tests by the Fabric SDK. Refer to the Node SDK repo for details on running these tests.
If you use the createChannel subcommand, ./network.sh runs the createChannel.sh script in the scripts folder to create a channel using the supplied channel name. The script uses the configtx.yaml file to create the channel creation transaction, as well as two anchor peer update transactions. The script uses the peer cli to create the channel, join peer0.org1.example.com and peer0.org2.example.com to the channel, and make both of the peers anchor peers.
If you issue the deployCC command, ./network.sh runs the deployCC.sh script to install the fabcar chaincode on both peers and then define then chaincode on the channel. Once the chaincode definition is committed to the channel, the peer cli initializes the chainocde using the Init and invokes the chaincode to put initial data on the ledger.

Troubleshooting/故障排除

If you have any problems with the tutorial, review the following:

You should always start your network fresh. You can use the following command to remove the artifacts, crypto material, containers, volumes, and chaincode images from previous runs:

./network.sh down
You will see errors if you do not remove old containers, images, and volumes.

If you see Docker errors, first check your Docker version (Prerequisites), and then try restarting your Docker process. Problems with Docker are oftentimes not immediately recognizable. For example, you may see errors that are the result of your node not being able to access the crypto material mounted within a container.

If problems persist, you can remove your images and start from scratch:

docker rm -f $(docker ps -aq)
docker rmi -f $(docker images -q)
If you see errors on your create, approve, commit, invoke or query commands, make sure you have properly updated the channel name and chaincode name. There are placeholder values in the supplied sample commands.

If you see the error below:

Error: Error endorsing chaincode: rpc error: code = 2 desc = Error installing chaincode code mycc:1.0(chaincode /var/hyperledger/production/chaincodes/mycc.1.0 exits)
You likely have chaincode images (e.g. dev-peer1.org2.example.com-fabcar-1.0 or dev-peer0.org1.example.com-fabcar-1.0) from prior runs. Remove them and try again.

docker rmi -f $(docker images | grep peer[0-9]-peer[0-9] | awk ‘{print $3}’)
If you see the below error:

[configtx/tool/localconfig] Load -> CRIT 002 Error reading configuration: Unsupported Config Type “”
panic: Error reading configuration: Unsupported Config Type “”
Then you did not set the FABRIC_CFG_PATH environment variable properly. The configtxgen tool needs this variable in order to locate the configtx.yaml. Go back and execute an export FABRIC_CFG_PATH=$PWD/configtx/configtx.yaml, then recreate your channel artifacts.

If you see an error stating that you still have “active endpoints”, then prune your Docker networks. This will wipe your previous networks and start you with a fresh environment:

docker network prune
You will see the following message:

WARNING! This will remove all networks not used by at least one container.
Are you sure you want to continue? [y/N]
Select y.

If you see an error similar to the following:

/bin/bash: ./scripts/createChannel.sh: /bin/bash^M: bad interpreter: No such file or directory
Ensure that the file in question (createChannel.sh in this example) is encoded in the Unix format. This was most likely caused by not setting core.autocrlf to false in your Git configuration (see Windows extras). There are several ways of fixing this. If you have access to the vim editor for instance, open the file:

vim ./fabric-samples/test-network/scripts/createChannel.sh
Then change its format by executing the following vim command:

:set ff=unix
If your orderer exits upon creation or if you see that the create channel command fails due to an inability to connect to your ordering service, use the docker logs command to read the logs from the ordering node. You may see the following message:

PANI 007 [channel system-channel] config requires unsupported orderer capabilities: Orderer capability V2_0 is required but not supported: Orderer capability V2_0 is required but not supported
This occurs when you are trying to run the network using Fabric version 1.4.x docker images. The test network needs to run using Fabric version 2.x.

If you continue to see errors, share your logs on the fabric-questions channel on Hyperledger Rocket Chat or on StackOverflow.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值