Relevant experiment source code has been uploaded: https://github.com/wefantasy/…
preface
In the implementation of Ethereum public auction smart contract based on the truss framework, we have implemented the writing and deployment of Ethereum smart contract, but its working method is doomed to be applied only in limited business scenarios. In contrast, super ledger basedFabric
With high scalability and customization, it can be applied in more complex business scenarios, butFabric
The technology involves many new concepts. The source code is fast to update and the compatibility between versions is poor. It is very unfriendly to beginners. In order to enable you to quickly masterFabric
, this paper builds a blockchain operating environment based on its latest version 2.4, and deploys official examples on itchaincode
Finally, the whole environment and the sample code can run normally and get the expected results.
Environment construction
Almost all onlineFabric
Tutorials are based onUbuntu
Environment rather thanWindows
, mainly due toFabric
Required for the operation ofDocker
Environment inWindows
Poor performance in additionFabric
Many official documents are also based onUbuntu
Compiled inwindows
May encounter unpredictablebug
. Originally, in order to facilitate the later deployment to the public network server, I wanted to build an environment on CentOS. However, because centos8 stopped maintenance and CentOS stream had a poor experience, I finally chose the Debian system.
The versions of systems and software in this environment are as follows:
System and software | version |
---|---|
VMware Pro | 16.0.0 |
Debian | debian-11.2.0-amd64-DVD-1.iso |
git | 2.30.2 |
curl | 7.74.0 |
docker | 20.10 |
golang | go1.17.8 |
jq | jq-1.6 |
fabric | 2.4.0 |
fabric-ca | 1.5.2 |
fabric-samples | [v2.3.0]() |
The image versions of dockers in this environment are as follows:
image | version |
---|---|
hyperledger/fabric-tools | 2.4 |
hyperledger/fabric-peer | 2.4 |
hyperledger/fabric-orderer | 2.4 |
hyperledger/fabric-ccenv | 2.4 |
hyperledger/fabric-baseos | 2.4 |
hyperledger/fabric-ca | 1.5 |
Warning: it is recommended that all fabric experiments be performed with root permission, otherwise many environment variables will occur during sudo permission switching.
Miscellaneous installation
-
Install the latest version
Git
apt install git
-
Install the latest version
cURL
apt install curl
- install
Golang
-
Install JQ
apt install jq
Installing fabric
Official script installation
To help developers quickly build
Fabric
Environment, the official created aFabric
Batch processing tool for environment setupbootstrap.sh
, you can directly install the environment through this tool:wget https://raw.githubusercontent.com/hyperledger/fabric/master/scripts/bootstrap.sh chmod +x bootstrap.sh ./bootstrap.sh
If you are not surprised, you will see the smooth environment installation process of the script:
Manual installation
Of course, if there is no accident when using the official script directly, there will be accidents (network reasons). Here we can manually install the required environments.
- Installing fabric samples
fabric-samples
yesFabric
The official demo collection of, which contains multiple samples, each of which hasGolang
、JavaScript
、typescript
、Java
And these chain codes can be directly deployed to the correspondingFabric
It is very helpful for beginners.fabric-samples
The installation is very simple and easy to usegit clone [email protected]:hyperledger/fabric-samples.git
You can clone the project source code locally. If it fails all the time, you can directly download the corresponding version of the compressed package in the release. - Installing fabric
Fabric is the core development tool of the alliance chain, which contains all commands during our development, compilation and deployment. -
Download fabric 2.4.0 and unzip it
wget https://github.com/hyperledger/fabric/releases/download/v2.4.0/hyperledger-fabric-linux-amd64-2.4.0.tar.gz mkdir /usr/local/fabric tar -xzvf hyperledger-fabric-linux-amd64-2.3.2.tar.gz -C /usr/local/fabric
-
Download fabric Ca 1.5.2 and unzip it
wget https://github.com/hyperledger/fabric-ca/releases/download/v1.5.2/hyperledger-fabric-ca-linux-amd64-1.5.2.tar.gz tar -xzvf hyperledger-fabric-ca-linux-amd64-1.5.2.tar.gz mv bin/* /usr/local/fabric/bin
-
Set environment variables in the
/etc/profile
Add at the end#Fabric export FABRIC=/usr/local/fabric export PATH=$PATH:$FABRIC/bin
-
Update environment variables
source /etc/profile
Install docker
-
Remove old version if present
apt remove docker docker-engine docker.io containerd runc
-
update
apt
Index packages and allow them to useHTTPS
installapt update apt install \ apt-transport-https \ ca-certificates \ curl \ gnupg \ lsb-release
-
Add
Docker
officialGPG
secret keycurl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
-
Add
Docker
warehouseecho \ "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
-
install
Docker
engineapt update apt install docker-ce docker-ce-cli containerd.io
-
install
docker-compose
apt install docker-compose
Install docker image dependency
Fabric
Relevant images can be downloaded from the official image website of dockerhub, and the installation method can be obtained by searching the required images. All images used in this experiment are:docker pull hyperledger/fabric-tools:2.4 docker pull hyperledger/fabric-peer:2.4 docker pull hyperledger/fabric-orderer:2.4 docker pull hyperledger/fabric-ccenv:2.4 docker pull hyperledger/fabric-baseos:2.4 docker pull hyperledger/fabric-ca:1.5
apply
docker images
Command to view the image after installation:hyperledger/fabric-tools 2.4 625237d887db 4 weeks ago 473MB hyperledger/fabric-peer 2.4 ee643d889779 4 weeks ago 62.3MB hyperledger/fabric-orderer 2.4 df64446ac2df 4 weeks ago 37.3MB hyperledger/fabric-ccenv 2.4 da4f00cb576a 4 weeks ago 517MB hyperledger/fabric-baseos 2.4 0287ebf8aaf3 4 weeks ago 6.94MB hyperledger/fabric-ca 1.5 4ea287b75c63 6 months ago 69.8MB
The image labels used in the sample code are
latest
, but ifpull
Select directly whenlatest
An error may be reported, so we manually use the following command to mark the image after the above image is pulledlatest
Label:#Docker tag ImageID repository:tag docker tag 625237d887db hyperledger/fabric-tools:latest docker tag ee643d889779 hyperledger/fabric-peer:latest docker tag df64446ac2df hyperledger/fabric-orderer:latest docker tag da4f00cb576a hyperledger/fabric-ccenv:latest docker tag 0287ebf8aaf3 hyperledger/fabric-baseos:latest docker tag 4ea287b75c63 hyperledger/fabric-ca:latest
The final image is:
Run test
Start fabric network
-
Enter the test network directory of fabric sample
cd fabric-samples/test-network
-
working
./network.sh up
Start networkCreating network "fabric_test" with the default driver Creating volume "docker_orderer.example.com" with default driver Creating volume "docker_peer0.org1.example.com" with default driver Creating volume "docker_peer0.org2.example.com" with default driver Creating peer0.org1.example.com ... done Creating orderer.example.com ... done Creating peer0.org2.example.com ... done Creating cli ... done CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 7738c1e84751 hyperledger/fabric-tools:latest "/bin/bash" Less than a second ago Up Less than a second cli 1f24de2c6cd5 hyperledger/fabric-peer:latest "peer node start" 2 seconds ago Up Less than a second 0.0.0.0:9051->9051/tcp, :::9051->9051/tcp, 0.0.0.0:19051->19051/tcp, :::19051->19051/tcp peer0.org2.example.com bfc48b20360c hyperledger/fabric-orderer:latest "orderer" 2 seconds ago Up Less than a second 0.0.0.0:7050->7050/tcp, :::7050->7050/tcp, 0.0.0.0:7053->7053/tcp, :::7053->7053/tcp, 0.0.0.0:17050->17050/tcp, :::17050->17050/tcp orderer.example.com b9a61fdaf47a hyperledger/fabric-peer:latest "peer node start" 2 seconds ago Up Less than a second 0.0.0.0:7051->7051/tcp, :::7051->7051/tcp, 0.0.0.0:17051->17051/tcp, :::17051->17051/tcp peer0.org1.example.com
Finally, the above output log indicates that the network is started successfully. Each node and user joining the fabric network must belong to an organization. The above network contains two parallel organizations————peer0.org1.example.com
andpeer0.org2.example.com
It also includes aorderer.example.com
。
Create channel
In the previous section, the peer node and the order node have been run on the machine. Now you can use network SH creates a channel between org1 and org2. Channel is a private channel between specific network members. It can only be used by organizations belonging to this channel, and is invisible to other network members. Each channel has a separate blockchain ledger. Organizations belonging to the channel can let their peers join the channel, so that peers can store the ledger on the channel and verify the transactions on the ledger.
Create a custom channel testchanel using the following command:
./network.sh createChannel -c testchannel
Deploy chaincode
It is recommended that all deployment operations be performed in
root
Account, otherwise unknown errors may occur. The following process is the author’s nonroot
Problems encountered by the user. All instructions for rebuilding the virtual machine areroot
The deployment is completed under the account.
After creating a channel, you can start to use smart contracts to interact with the channel ledger. Smart contracts contain business logic for managing assets on the blockchain ledger. Application networks run by members can call smart contracts on the ledger to create, change and transfer these assets. Can pass./network.sh deployCC
Command to deploy smart contracts, but many problems may occur in this process.
Deploy chaincode using the following command:
./network.sh deployCC -c testchannel -ccn basic -ccp ../asset-transfer-basic/chaincode-go -ccl go
Errors may occur after this command is executed:scripts/deployCC.sh: line 114: log.txt: Permission denied
, which is obviously caused by insufficient permissions. Add sudo to try:
./network.sh deployCC -c testchannel -ccn basic -ccp ../asset-transfer-basic/chaincode-go -ccl go
New error after adding sudo:deployCC.sh: line 59: go: command not found
. Check this usergo
Command available, checkroot
usergo
Command available, onlysudo
It cannot be used after. After checking the data, it was found that this was becauselinux
The system is restricted to use for safetysudo
The user-defined environment variables will be cleared. The simplest solution is to/etc/sudoers
This restriction is directly annotated in the file1:
A new error occurs when you re execute the previous command after adding a comment:
go: github.com/golang/[email protected]: Get "https://proxy.golang.org/github.com/golang/protobuf/@v/v1.3.2.mod": dial tcp 172.217.160.81:443: i/o timeout
Obviously, this is because the local network cannot access the proxy Golang Org, enter on the command linego env -w GO111MODULE=on && go env -w GOPROXY=https://goproxy.cn,direct
Command to configure domestic agent2Then execute again. Surprisingly, the error does not change, and the set proxy does not take effect? Manual usego get github.com/golang/protobuf
After downloading and installing manually and running again, the error remains unchanged. At this time, check the localGOPATH
Already exists in the directorygithub.com/golang/protobuf
Package, why is it not recognized? At this point, you have an idea to usego env
checkGOPATH
Environment variable. It is found that it is inconsistent with the local user. The originalsudo
Command will useroot
ofgo
Environment variables, and the previously set agents and downloaded packages can only take effect under local users. Therefore, the final solution to this problem is to switch directly toroot
Reconfigure under usergo
Agent and running. The following results can be seen after successful operation:
2021-08-15 00:45:54.064 PDT [chaincodeCmd] ClientWait -> INFO 001 txid [ebeb8df6904f45b81fb30714f7eecb30b4bbfd32f4acc809f34f7c660e396eb8] committed with status (VALID) at localhost:7051
2021-08-15 00:45:54.144 PDT [chaincodeCmd] ClientWait -> INFO 002 txid [ebeb8df6904f45b81fb30714f7eecb30b4bbfd32f4acc809f34f7c660e396eb8] committed with status (VALID) at localhost:9051
Chaincode definition committed on channel 'testchannel'
Using organization 1
Querying chaincode definition on peer0.org1 on channel 'testchannel'...
Attempting to Query committed status on peer0.org1, Retry after 3 seconds.
+ peer lifecycle chaincode querycommitted --channelID testchannel --name basic
+ res=0
Committed chaincode definition for chaincode 'basic' on channel 'testchannel':
Version: 1.0, Sequence: 1, Endorsement Plugin: escc, Validation Plugin: vscc, Approvals: [Org1MSP: true, Org2MSP: true]
Query chaincode definition successful on peer0.org1 on channel 'testchannel'
Using organization 2
Querying chaincode definition on peer0.org2 on channel 'testchannel'...
Attempting to Query committed status on peer0.org2, Retry after 3 seconds.
+ peer lifecycle chaincode querycommitted --channelID testchannel --name basic
+ res=0
Committed chaincode definition for chaincode 'basic' on channel 'testchannel':
Version: 1.0, Sequence: 1, Endorsement Plugin: escc, Validation Plugin: vscc, Approvals: [Org1MSP: true, Org2MSP: true]
Query chaincode definition successful on peer0.org2 on channel 'testchannel'
Chaincode initialization is not required
Contractual interaction
In the fabric installation, we have setfabric
The environment variables of the executable file must be guaranteed to successfullytest-network
Use under directorypeer
Command.
-
Set fabric_ CFG_ Path variable, under which core Yaml file
export FABRIC_CFG_PATH=$PWD/../config/ # export FABRIC_CFG_PATH=/usr/local/fabric/config/
-
Set other
Org1
Organizational variable dependencies# Environment variables for Org1 #Core_ Peer_ TLS_ Rootcert_ File and core_ Peer_ The mspconfigpath environment variable points to the identity certificate in the organizations folder of org1. export CORE_PEER_TLS_ENABLED=true export CORE_PEER_LOCALMSPID="Org1MSP" 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/[email protected]/msp export CORE_PEER_ADDRESS=localhost:7051
-
Initialize chaincode
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 testchannel -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":[]}'
-
Query ledger asset list
peer chaincode query -C testchannel -n basic -c '{"Args":["GetAllAssets"]}'
-
Modify ledger 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 testchannel -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"]}'
-
Turn off the network
./network.sh down
This command will stop and delete nodes and chain code containers, organize encryption materials, delete previously running channel items and docker volumes, and remove chain code images from the docker registry.
because
asset-transfer (basic)
The endorsement strategy of the chain code requires the transaction to be approved at the same timeOrg1
andOrg2
Signature, so chain code call instructions need to use--peerAddresses
Label to point topeer0.org1.example.com
andpeer0.org2.example.com
; Because the networkTLS
Is turned on, and the command also needs to use--tlsRootCertFiles
Label points to eachpeer
NodalTLS
Certificates.
reference
- QQ_ Jwang_ 03215367. solve the command not found error MOOC [2018-07-31] ↩
- Mu Zifeng Failed to normalize chaincode path:’Go list’failed with: go Blog Garden [November 27, 2020] ↩