Four-word analysis - blockchain hyperledger fabric2.2 deployment practical tutorial

I. Introduction

This tutorial runs under the ubuntu20 version. Please deploy the ubuntu20 environment before performing the operation. All deployments are carried out in accordance with the official document hyperledger fabric . I will also explain the problems encountered during the operation. If you don’t know much, please refer to the concept of blockchain first. If there is something wrong in the understanding, please criticize and correct it.

2. Introduction to hyperledger fabric

Hyperledger Fabric is one of the blockchain projects in Hyperledger (Super Book) and one of the classic consortium chains. It has a ledger, using smart contracts, a system where participants manage transactions, but it is not fully decentralized, i.e. members who want to join the consortium need to register from a trusted Membership Service Provider (MSP), the following are An introduction to some related concepts.

noun explain
assets Recorded data, usually in json format representing a collection of key-value pairs
chaincode Business logic, i.e. smart contracts, define and modify transaction instructions
assets Recorded data, usually in json format representing a collection of key-value pairs
Ledger Features Features such as key-based, range-based, and composite queries
privacy Channels are created that are isolated from each other and, while allowing sharing of network infrastructure between organizations, can also be privatized
Security and Member Services All members are open and can operate and manage data on a wider range of networks and channels
consensus From proposal and endorsement to sorting, verification and submission, there is consensus verification in it to ensure that transactions reach consensus and prevent double spending
blockchain network Technical infrastructure for application ledger and smart contracts (chaincode)

The following figure shows the structure of Fabric:
insert image description here
The following figure shows the structure of Hyperledger Fabric. For details, see Blockchain Network :
insert image description here

3. Test network example

3.1 Build a development environment

1. Install git

sudo apt-get install git

2. Install curl

sudo apt-get install curl

3. Install docker

# 安装并检查版本
sudo apt-get -y install docker-compose
docker --version
docker-compose --version
# 提示,以后只要碰到docker有关的错误,先执行2.3.1步骤
#1.重启docker
sudo systemctl start docker
#设置系统启动时docker启动,可选
sudo systemctl enable docker
#2.将用户添加到docker组,确保在用户命令下可以执行
sudo gpasswd -a $USER docker
#3.更新用户组
newgrp docker   
# docker信息
docker info
# 测试docker,若报错详见文末附加问题1
docker run hello-world 

4. Install go

Install and extract:

mkdir ~/download
cd ~/download
# 下载
wget https://studygolang.com/dl/golang/go1.13.linux-amd64.tar.gz
# 解压
sudo tar -C /usr/local -xzf go1.13.linux-amd64.tar.gz

Create the go directory and configure the environment:

mkdir $HOME/go
#用vi打开~./bashrc,配置环境变量
vi ~/.bashrc
# 在最下方插入
export GOROOT=/usr/local/go
export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
#使配置的环境变量生效
source ~/.bashrc
#检查是否配置正确
go version
# 配置goproxy环境变量加速国内下载
go env -w  GOPROXY=https://goproxy.io

3.2 Install examples, binaries and Docker images

1. Clone hyperledger/fabric-samplesthe repository

mkdir -p $GOPATH/src/github.com/hyperledger
cd $GOPATH/src/github.com/hyperledger
# 获取fabric-samples源码
git clone https://github.com/hyperledger/fabric-samples.git

2. Select the appropriate version tag, enter the directory, and switch branches

cd fabric-samples
# 可自行选择版本
git checkout release-2.2
#查看版本
git branch

insert image description here
3. Install the Hyperledger Fabric platform-specific binaries and configuration files of the specified version into the /binand /configdirectories under fabric-samples, and download the Hyperledger Fabric docker image of the specified version.
Configure the image source first:

sudo vi /etc/docker/daemon.json
#把以下代码加进去
{
    
    
"registry-mirrors":["https://registry.docker-cn.com"]
}
#如果你想要最新的生产发布版本,忽略所有的版本标识符。
# curl -sSL https://bit.ly/2ysbOFE | bash -s
# curl -sSL https://bit.ly/2ysbOFE | bash -s -- <fabric_version> <fabric-ca_version> <thirdparty_version>
# 若报错详见文末附加问题2
curl -sSL https://bit.ly/2ysbOFE | bash -s -- 2.2.0 1.4.7 0.4.18
# 若不行试试下面这个
curl -sSL https://raw.githubusercontent.com/hyperledger/fabric/master/scripts/bootstrap.sh | bash -s  2.2.0 1.4.7 0.4.18

Try a few times and you will be successful!
insert image description here
We can see that all downloads are complete
insert image description here

cd chaincode-go
sudo vi go.mod
# 进入文件发现是1.14 自己把改成1.13 ,要与你下载的go版本匹配

insert image description here

Environment variable settings

vi ~/.bashrc
# 添加下面的变量
export PATH=$PATH:$GOPATH/src/github.com/hyperledger/fabric-samples/bin
# 使之生效
source ~/.bashrc
# 检验成功否
fabric-ca-client version

insert image description here

3.3 Use Fabric to test the network

Reminder: When you see this, it means that your environment has been deployed. Next, you need to use the test network. It should be noted that the operation must be performed in a complete period of time. Do not perform the following operations intermittently, otherwise it may be There will be a lot of problems that are difficult for newbies to solve!

More importantly,
turn on debug mode when encountering problems!
Turn on debug mode!
Turn on debug mode!

export FABRIC_LOGGING_SPEC=debug

1. Start the test network
and enter fabric-samplesthe next test-network
to analyze the network.sh script

# 脚本有500多行,在这讲解脚本里的一些方法
function clearContainers()# 清除容器
function removeUnwantedImages() # 清除不想要的镜像
# 大家仔细看看都能读懂,下面挑几个关键且常用的讲
#创建组织
function createOrgs() {
    
    
# 这里包含一些业务逻辑比如
# Create crypto material using cryptogen or Fabric CA
if [ "$CRYPTO" == "cryptogen" ];then...
if [ "$CRYPTO" == "Certificate Authorities" ]; then..
}
# 创建联盟
function createConsortium()
# 开启网络
function networkUp()
# 创建channel
function createChannel()
# 开启链码
function deployCC()
# 最后给出了一些确定操作模式并打印出我们所要求的内容
if [ "$MODE" == "up" ]; then
  infoln "Starting nodes with CLI timeout of '${MAX_RETRY}' tries and CLI delay of '${CLI_DELAY}' seconds and using database '${DATABASE}' ${CRYPTO_MODE}"
elif [ "$MODE" == "createChannel" ]; then
  infoln "Creating channel '${CHANNEL_NAME}'."
  infoln "If network is not up, starting nodes with CLI timeout of '${MAX_RETRY}' tries and CLI delay of '${CLI_DELAY}' seconds and using database '${DATABASE} ${CRYPTO_MODE}"
elif [ "$MODE" == "down" ]; then
  infoln "Stopping network"
elif [ "$MODE" == "restart" ]; then
  infoln "Restarting network"
elif [ "$MODE" == "deployCC" ]; then
  infoln "deploying chaincode on channel '${CHANNEL_NAME}'"
else
  printHelp
  exit 1
fi

if [ "${MODE}" == "up" ]; then
  networkUp
elif [ "${MODE}" == "createChannel" ]; then
  createChannel
elif [ "${MODE}" == "deployCC" ]; then
  deployCC
elif [ "${MODE}" == "down" ]; then
  networkDown
else
  printHelp
  exit 1
fi 

Execute the following command to execute the scriptnetwork.sh

./network.sh up

After execution, we can see that we have created the ordering organization orderer, the peer0 node of the alliance member org1, the peer0 node of the alliance member org2, and the corresponding mirror image.
insert image description here
2. The components of the test network are
executed. docker ps -a
You can see the three nodes created and all the organizations that are members of the previously tested hello-world
insert image description here
Fabric network are called alliances. This test network has two alliance members org1 and 2, and one maintains the network ordering service. The organization orderer, each organization operates a peer node, peer0.org1.example.com and peer0.org2.example.com.
The peer node is the basic component of the fabric network. The most common peer node is the endorsement node. The peer node stores the blockchain ledger for verification before transactions.
The example network uses a single-node Raft ordering service, previous versions had solo mode and kafka mode, this test only uses a single-node ordering service, but a real network will have multiple ordering nodes, organized by one or more orderers.

3. Create a channel

There are several ways to create a ./network.sh createChannelchannel between org1 and org2 and join their peers using:

# 1.不输入自定义名称通道,默认为mychannel
./network.sh createChannel
# 2.输入自定义名称,可以创建多个不同名称通道
./network.sh createChannel -c channel1
./network.sh createChannel -c channel2
# 3.也可以建立网络创建通道一起
./network.sh up createChannel

insert image description here

4. Start a chain code in the channel
In fabric, chain code refers to the smart contract.
After the channel is created, start deploying the chaincode to interact with the channel ledger. The chaincode contains the business logic of the assets on the blockchain ledger and is written in the go language, which will be described in detail later. A network of applications run by members can call only contracts on the ledger to create, change and transfer assets.
In order to ensure the transaction is valid, transactions created using smart contracts require signatures from multiple organizations before they can be submitted to the ledger, that is, endorsement, and smart contracts also define endorsement policies, such as requiring 2/3 of the members to agree to pass, half of the members to agree to pass, etc. .
After creating the channel, now start the chaincode:

./network.sh deployCC -ccn basic -ccp ../asset-transfer-basic/chaincode-go -ccl go
# 出错详见附加问题3

The following figure shows that the chain code is successfully started
insert image description here
5. Interact with
the network Add fabric-samplesthe binbinary file under the file to the CLI path:

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

Also need to set fabric-samplesin the codebase FABRIC_CFG_PATHto point to the core.yamlfiles in it:

export FABRIC_CFG_PATH=$PWD/../config/

Set an environment variable that allows the user to operate the peer's CLI as org1:

# Environment variables for Org1

export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org1MSP"
#CORE_PEER_TLS_ROOTCERT_FILE和CORE_PEER_MSPCONFIGPATH环境变量指向Org1的organizations文件夹中的的加密材料。
export CORE_PEER_TLS_ROOTCERT_FILE=${
    
    PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
export CORE_PEER_MSPCONFIGPATH=${
    
    PWD}/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
export CORE_PEER_ADDRESS=localhost:7051

Next, you can call the InitLedger method of the chaincode (Go) to assign some initial assets on the ledger. Run the following command to initialize the ledger with some assets:

peer chaincode invoke -o localhost:7050 --ordererTLSHostnameOverride orderer.example.com --tls --cafile ${
    
    PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C mychannel -n basic --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":"InitLedger","Args":[]}'

As shown in the figure, the initialization is successful!
insert image description here
Next, you can use the CLI tool to query the ledger:

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

insert image description here
It is also possible to transfer or change the owner of the asset (that is, the change operation in the database):

peer chaincode invoke -o localhost:7050 --ordererTLSHostnameOverride orderer.example.com --tls --cafile ${
    
    PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C mychannel -n basic --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":"TransferAsset","Args":["asset6","Christopher"]}'

After the execution, let's check again and find that the owner whose ID is asset6 has become Christopher, as shown in the figure:
insert image description here
Next, we can query through the peer of org2. Before that, let's set the environment variable of org2:

# 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

check again

peer chaincode query -C mychannel -n basic -c '{"Args":["ReadAsset","asset6"]}'

The result is the same as org1, asset6 is transferred to a person named Christopher.
insert image description here
At this point, the test is completed, we close the network./network.sh down

3.4 Networking with Certification Bodies

Hyperledger Fabric uses Public Key Infrastructure (PKI) to verify the actions of all network participants. Transactions submitted by each node, network administrator and user need to have a public certificate and private key to verify their identity. These identities must have a valid root of trust issued by an organization that is a member of the network.
In the test network, network.shthe cryptogen tool was used to create these cryptographic materials before creating the nodes, now let's try:

./network.sh up -ca

insert image description here
You can see that the script starts three CAs, orderer, org1, and org2. Interested friends check what the script has done after startup, so I won't go into details here.
Below we can also take a look at the MSP folder of org1, which contains the certificate and private key for each identity:

tree organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/
# 如果没有tree请按照提示安装

insert image description here

#关闭网络
./network.sh down

4. Application in automobile production

4.1 Build a development environment

Install python2.7, make, gcc, npm, enable remote services to view documentation

sudo apt-get install python2.7
sudo apt-get install make
sudo apt-get install gcc
sudo apt install npm
# 安装
sudo apt-get install openssh-server
# 查看,存在sshd说明已启动
sudo ps -e |grep ssh
# 启动
sudo service ssh start

Enter the fabric-sampleswarehouse and fabcarstart the smart contract through the script of the javasript version:

cd fabric-samples/fabcar
./startFabric.sh javascript
# 启动若报错,查看附加问题4

The startup is successful as shown in the figure
insert image description here

4.2 Operation and use of registration

This tutorial uses javascript for the example written for nodejs, first enter the javascriptfolder:

cd javascript

This directory contains sample programs developed using the Fabric SDK for Node.js. Run the following command to install application dependencies:

npm install

After completion, take a lslook at the application file of the example javaScript through the command:
insert image description here
When we create the network, the certificate authority server (CA) will create an administrator user (admin), the first step uses the enroll.jsgenerated private key, public key and x.509 certificate:

node enrollAdmin.js

After the creation, the certificate of the CA administrator is saved in the walletdirectory, and the certificate and private key can be found in admin.id. Next create a new application user, which will be used to interact with the blockchain. Run the following commands to register and log appUsera :

node registerUser.js

insert image description here
Next, let's query the ledger. The most common query is to query the current value of the ledger (world state). Let's use it first query.js:

node query.js

insert image description here
As shown in the output result, we can see that the query data is in key-value pairs, that is, in json format. Of course, we can also use rich queries by configuring a database (such as CouchDB).
Interested friends can query.jsanalyze it, there are some definitions that are easy to understand.

4.3 Smart Contract

Navigate to the JavaScript version of the FabCar smart contract in the fabric-samples repository:

cd fabric-samples/chaincode/fabcar/javascript/lib

Open fabcar.js, which describes how the smart contract is defined using the Contract class
insert image description here
Now let's change query.jsthe query scope code:

const result = await contract.evaluateTransaction('queryAllCars');
#改为
const result = await contract.evaluateTransaction('queryCar', 'CAR4');

After saving like this, return to fabcar/javascripexecuting:

node query.js

We can see that the query structure has only changed to query the data of this car

Wallet path: ...fabric-samples/fabcar/javascript/wallet
Transaction has been evaluated, result is:
{
    
    "color":"black","docType":"car","make":"Tesla","model":"S","owner":"Adriana"}

4.4 Update the ledger

Just now we have completed some ledger queries and added and modified queries. Now let's update the ledger (that is, "increase" in the database).
We open invoke.js
insert image description here
it. Now we know the principle and start executing.

node invoke.js

After execution, modify query.js to the previous code for querying the world state, and then check

node query.js

As shown in the figure, we can see that CAR12 has been added to the
insert image description here
modification function:

# 这就是invoke.js中的submitTransaction功能,
# 把方法由createCar修改为changeCarOwner
await contract.submitTransaction('changeCarOwner', 'CAR12', 'Dave');

Check again node query.js, you can see that the owner has become "Dave".
At this point, end, return to the fabcar directory, clear the data, and close the test network:

./networkDown.sh

5. Application of commercial paper

This application contains two organizations, MagnetoCorp and DigiBank, which use the blockchain network PaperNet to trade commercial paper with each other, as shown in the figure:
insert image description here
The process is as follows:
I am Isabella, an employee of MagnetoCorp, she will issue commercial paper on behalf of the company, and then switch roles to serve as Balaji, an employee of DigiBank, who will buy this commercial paper, hold it for a period of time, and redeem it with MagnetoCorp for a small profit.

5.1 Running the network

Change into fabric-samplesthe commercial-paperdirectory in and start the network:

cd fabric-samples/commercial-paper
./network-starter.sh

Note that the test network name here is fabric_test, the official tutorial is net_test, pay attention to check the operation of the Fabric node on the local machine through the command:
insert image description here
You can also check it through the command:docker ps
insert image description here
docker network inspect fabric_test
insert image description here

peer0.org1.example.com will belong to the DigiBank organization
peer0.org2.example.com will belong to the MagnetoCorp organization
. The network launched is called PaperNet . After
it is launched, eight containers will be generated, corresponding to eight different IP addresses, which can be viewed through the docker network inspect net_testcommand:
1. The peer
of Org1——peer0.org1.example.com
2. The peer of Org2——peer0.org2.example.com 3. The CouchDB database corresponding to the peer of Org1——couchdb0 4. The CouchDB database corresponding
to the peer of Org2—— --couchdb1
5. Ordering Service Node
-- orderer.example.com 6. Org1's CA -- ca_org1 7.
Org2's CA -- ca_org2
8. Ordering Service Org's CA -- ca_orderer

5.2 As MagnetoCorp

Administrator status

First switch to the MagnetoCorp directory:

cd commercial-paper/organization/magnetocorp

In the MagnetoCorp directory, run the following command to run the monitordocker.shscript and start the logspout tool for the container associated with PaperNet running on fabric_test:

# 如果是非最高权限用户,请在下列命令前加上sudo
./configuration/cli/monitordocker.sh fabric_test
#如果 monitordocker.sh 中的默认端口已经在使用,可以传入一个端口号
#./monitordocker.sh net_test <port_number>
./monitordocker.sh net_test 8079

insert image description here

developer status

Check commercial paper smart contracts:
issue (issue), buy (purchase), redeem (redeem) are the three core functions of PaperNet smart contracts.
Open a new terminal on behalf of the MagnetoCorp developers:

cd commercial-paper/organization/magnetocorp

View smart contracts under contract/lib papercontract.js, which includes commercial paper smart contracts, which define transaction methods such as issuance, purchase, redemption, and query.
insert image description here
Deploy the smart contract to the channel:
Before the application calls papercontract, the contract must be installed on the appropriate peer node in the test network, and then it is defined on the channel using the Fabric chaincode lifecycle, so it needs to be an administrator of MagnetoCorp and DigiBank The identity to install and approve the consent chaincode.
insert image description here
One or more smart contracts can be defined in a chaincode. Installing the chaincode enables different organizations in PaperNet to use the smart contracts. It also means that only administrators need to pay attention to the chaincode, and others only need to pay attention to the smart contracts.
Install and approve smart contracts as MagnetoCorp:
open another command- side down, admin can interact with PaperNet cd commercial-paper/organization/magnetocorpby using the container, also need to set some environment variables in the command window to use the correct binary to peer to MagneoCorp The node's address sends the command and signs the request with the correct encryption:peerpeer

# 打印完整环境变量并使用生效
source magnetocorp.sh

Now start interacting with the network as an administrator:

1. Install the papercontract smart contract and
use peer lifecycle chaincode packageto package the smart contract into a chain code

# 创建链码包
peer lifecycle chaincode package cp.tar.gz --lang node --path ./contract --label cp_0

peer lifecycle chaincode installInstall chaincode on MagnetoCorp's peer node using command

peer lifecycle chaincode install cp.tar.gz
# 若报错,见附加问题6

insert image description here
2. Agree (verify) the chain code definition
First query the packageID of the chain code on the peer:

peer lifecycle chaincode queryinstalled

insert image description here
Next, you need to save the packageID as an environment variable

export PACKAGE_ID=cp_0:ddca913c004eb34f36dfb0b4c0bcc6d4afc1fa823520bb5966a3bfcf1808f40a

Then use the following command to agree to the chaincode definition:

peer lifecycle chaincode approveformyorg --orderer localhost:7050 --ordererTLSHostnameOverride orderer.example.com --channelID mychannel --name papercontract -v 0 --package-id $PACKAGE_ID --sequence 1 --tls --cafile $ORDERER_CA

In order to use a chaincode definition, channel members need to agree on one of the most important chaincode parameters is the endorsement policy, which describes the set of organizations that must endorse a transaction before it can be determined to be valid. By agreeing to the papercontract chaincode without specifying the --policy flag, we here agree to use the channel's default Endorsement policy - requiring the majority of organizations on the channel to endorse transactions, and all transactions, valid or not, will be recorded in the blockchain ledger , but only valid transactions will update the world state.

5.3 As DigiBank

1. Install and approve smart contracts as
DigiBank Based on mychanner's LifecycleEndorsement policy, the Fabric chaincode lifecycle will require most organizations on the channel to agree to the definition of the chaincode before submitting the chaincode to the channel, i.e. both agree (MagnetoCorp and DigiBank). Switch to the digibank environment deployment:

cd commercial-paper/organization/digibank/
source digibank.sh

Now install and agree to papercontract as DigiBank, using the same method as MagnetoCorp:

# 打包链码
peer lifecycle chaincode package cp.tar.gz --lang node --path ./contract --label cp_0
# 安装链码
peer lifecycle chaincode install cp.tar.gz
# 查询安装链码的packageID
peer lifecycle chaincode queryinstalled
# 将id保存为环境变量
# export PACKAGE_ID=cp_0: <packageID>
export PACKAGE_ID=cp_0:ddca913c004eb34f36dfb0b4c0bcc6d4afc1fa823520bb5966a3bfcf1808f40a
# Digibank管理员同意papercontract的链码定义:
peer lifecycle chaincode approveformyorg --orderer localhost:7050 --ordererTLSHostnameOverride orderer.example.com --channelID mychannel --name papercontract -v 0 --package-id $PACKAGE_ID --sequence 1 --tls --cafile $ORDERER_CA

insert image description here
At this point, both organizations have agreed to the papernet chaincode, which also means that the client application on the channel can call the CommercialPaper smart contract in the papercontract chaincode. Here we continue to use the identity of the DigiBank administrator to peer lifecycle chaincode commitsubmit the chaincode definition of papercontract to mychannel using the command:

peer lifecycle chaincode commit -o localhost:7050 --ordererTLSHostnameOverride orderer.example.com --peerAddresses localhost:7051 --tlsRootCertFiles ${
    
    PEER0_ORG1_CA} --peerAddresses localhost:9051 --tlsRootCertFiles ${
    
    PEER0_ORG2_CA} --channelID mychannel --name papercontract -v 0 --sequence 1 --tls --cafile $ORDERER_CA --waitForEvent

insert image description here
It can be seen that the papercontract container has been started on the two peer nodes, and the papercontract code has been deployed to the channel. Next, the MagnetoCorp application is used to issue commercial paper.

5.4 Application Structure

The smart contract included in the papercontract is called by the application issue.js of MagnetoCorp. Let's take a look cd commercial-paper/organization/magnetocorp/application. In this directory, there are issue.js
insert image description here
some imports defined in front of the code as seen in the figure above. Now let's install these imported packages first. down:

# 切换目录
cd commercial-paper/organization/magnetocorp/application/
# 安装依,这个命令会把当前包下所有js文件中引入的依赖下载
npm install
# 查看目录
ls

insert image description here
When we look at node_modules, we see that many packages are already installed, because js-yamland fabric-networkare themselves built into other npm packages! package-lock.jsonThe file accurately identifies the installed version.

5.5 Wallets

Because it issue.jsstands for Isabella, it also stands for MagnetoCorp, and issue.jswill use the identity in the Isabella wallet that reflects the above facts. Now we need to perform this one-time activity to add the X.509 certificate to Isabella's wallet.
Run node enrollUser.jsadds identity information to her wallet:
insert image description here
Let's ls ../identity/user/isabella/wallet/look at what's in the wallet again:
insert image description here
Isabella can store multiple identities in her wallet, but in our example, she only uses one. Inside the wallet folder is an isabella.id file that provides the information Isabella needs to connect to the network.
insert image description here

5.6 Publishing applications

Isabella can now use issue.js to submit a transaction that will issue MagnetoCorp commercial paper 00001:

node issue.js

insert image description here
Process issue transaction response.
{“class”:“org.papernet.commercialpaper”,
“currentState”:1,
“issuer”:“MagnetoCorp”,
“paperNumber”:“00001”,
“issueDateTime”:“2020-05-31”,
“maturityDateTime”:“2020-11-30”,
“faceValue”:5000000,
“mspid”:“Org2MSP”,
“owner”:“MagnetoCorp”}

5.7 DigiBank Application

Now we use the identity of DigiBank to use the buy and redeem operations:

cd commercial-paper/organization/digibank/application/

Take a closer look at the two files in this directory. The
insert image description here
operation process is the same as that of MagnetoCorp:

# 安装依赖
npm install
# 注册用户
node enrollUser.js

insert image description here

Like Isabella, a balaji's identity information is added to DigiBank's wallet for purchase and redemption transactions. Next, let's try to buy and redeem!

# 购买
node buy.js
# 赎回
node redeem.js

insert image description here

Finally, don't forget to clean up this data:

cd fabric-samples/commercial-paper
sudo ./network-clean.sh

If you need to execute the second time, you need to manually delete some folders, such as the identity folder under digibank and magnetocorp, and the package node_moudle of npm install.
Only after deleting, the second execution of these codes can be successful, or the installation will not be executed again. Dependent code works too.

Additional questions

  1. Got permission denied while trying to connect to the Docker daemon socket at...
    Solution:
    The account that executes the command does not have permission. The account I use to execute the command is a normal account without root permission. Either switch to the root user or change the current Users are added in, be sure to remember to update the user group!

    	#将用户添加到docker组,确保在用户命令下可以执行
    	sudo gpasswd -a $USER docker
    	#更新用户组
    	newgrp docker
    
  2. curl: (7) Failed to connect to raw.githubusercontent.com port 443: Connection refused
    Solution:
    Open the website: https://www.ipaddress.com/
    to check the IP address corresponding to raw.githubusercontent.com
    insert image description here
    insert image description here
    and enter it on the command line sudo vi /etc/hosts

    #添加一行:
    #【查询到的任一 ip 】raw.githubusercontent.com,我这里是:
    185.199.108.133 raw.githubusercontent.com
    

    It may fail, try a few more times, I probably have to repeat the download command 6-8 times before it succeeds!

  3. Chaincode installation on peer0.org1 has failed insert image description here
    . The context deadline exceeded is exceeded. Other operations may also cause this. Note that these operations must be done in one go, do not suspend the virtual machine or interrupt the operation, otherwise there will be a lot of Problem, another, remember to take backups, snapshots, so you can go back to the previous node and avoid re-deleting and changing.

  4. Error: chaincode install failed with status: 500 - failed to invoke backing implementation of 'InstallChaincode': could not build chaincode: docker build failed: docker image build failed: docker build failed: Error returned from build: 1 "+ INPUT_DIR=/chaincode /input
    error: Chaincode install failed, status: 500 - Failed to invoke support implementation for 'InstallChaincode': Failed to build chaincode: docker build failed: docker image build failed: docker build failed: returned error from build: 1" + INPUT_DIR= The problem with /chaincode/input
    is that there is a problem with the docker build, because I suspended the virtual machine before and the docker container did not restart. Try restarting it:

    systemctl restart docker
    
  5. Could not resolve host: github.com
    pulled the mirror and found this problem. Maybe the network is gone. See if the network icon in the upper right corner of you is still there? If it is gone, execute the following command:

    sudo service network-manager stop
    sudo rm /var/lib/NetworkManager/NetworkManager.state
    sudo gedit /etc/NetworkManager/NetworkManager.conf
    

    insert image description here

    #把false改成true,再重启网络
    sudo service network-manager restart
    
  6. peer lifecycle chaincode install cp.tar.gzError: chaincode install failed with status: 500 - failed to invoke backing implementation of ‘InstallChaincode’: could not build chaincode: docker build failed: docker image build failed: docker build failed: Error returned from build: 1 "+ INPUT_DIR=/chaincode/input+ OUTPUT_DIR=/chaincode/output+ cp -R /chaincode/input/src/. /chaincode/output+ cd /chaincode/output+ ‘[’ -f package-lock.json -o -f npm-shrinkwrap.json ]+ npm install --production
    npm ERR! code EAI_AGAIN
    npm ERR! errno EAI_AGAIN
    npm ERR! request to https://registry.npmjs.org/fabric-shim failed, reason: getaddrinfo EAI_AGAIN registry.npmjs.org
    npm ERR! A complete log of this run can be found in:
    npm ERR! /root/.npm/_logs/2022-05-24T06_09_07_419Z-debug.log
    insert image description here
    I checked a lot of information on the Internet, and they all said that it was a problem with the version of go. You can change to go1.13. I used go1.18 before.

Epilogue

The above is the analysis and operation of all the official examples. I have basically stepped on the pit of the official tutorial for the reference of friends who are new to hyperledger fabric. The follow-up study and the blockchain project that I will deploy will also be updated in the blockchain. in the topic. If there is anything wrong, please correct me; if you have other questions, please leave a message, if it is helpful to you, please give me a like!

Guess you like

Origin blog.csdn.net/weixin_44165950/article/details/124857431