Build hyperledger fabric 2.4 development environment and simple case based on Debian

Time:2022-5-28

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 basedFabricWith high scalability and customization, it can be applied in more complex business scenarios, butFabricThe 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 itchaincodeFinally, the whole environment and the sample code can run normally and get the expected results.

Environment construction

Almost all onlineFabricTutorials are based onUbuntuEnvironment rather thanWindows, mainly due toFabricRequired for the operation ofDockerEnvironment inWindowsPoor performance in additionFabricMany official documents are also based onUbuntuCompiled inwindowsMay 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

  1. Install the latest versionGit

    apt install git
  2. Install the latest versioncURL

    apt install curl
  3. installGolang
  4. Install JQ

    apt install jq

    Installing fabric

    Official script installation

    To help developers quickly buildFabricEnvironment, the official created aFabricBatch 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:
    Build hyperledger fabric 2.4 development environment and simple case based on Debian

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.

  1. Installing fabric samples
    fabric-samplesyesFabricThe official demo collection of, which contains multiple samples, each of which hasGolangJavaScripttypescriptJavaAnd these chain codes can be directly deployed to the correspondingFabricIt is very helpful for beginners.fabric-samplesThe installation is very simple and easy to usegit clone [email protected]:hyperledger/fabric-samples.gitYou 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.
  2. Installing fabric
    Fabric is the core development tool of the alliance chain, which contains all commands during our development, compilation and deployment.
  3. 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
  4. 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
  5. Set environment variables in the/etc/profileAdd at the end

    #Fabric
    export FABRIC=/usr/local/fabric
    export PATH=$PATH:$FABRIC/bin
  6. Update environment variablessource /etc/profile

    Install docker

  7. Remove old version if present

    apt remove docker docker-engine docker.io containerd runc
  8. updateaptIndex packages and allow them to useHTTPSinstall

    apt update
    apt install \
     apt-transport-https \
     ca-certificates \
     curl \
     gnupg \
     lsb-release
  9. AddDockerofficialGPGsecret key

    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
  10. AddDockerwarehouse

    echo \
    "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
  11. installDockerengine

    apt update
    apt install docker-ce docker-ce-cli containerd.io
  12. installdocker-compose

    apt install docker-compose

    Install docker image dependency

    FabricRelevant 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

    applydocker imagesCommand 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 arelatest, but ifpullSelect directly whenlatestAn error may be reported, so we manually use the following command to mark the image after the above image is pulledlatestLabel:

    #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:
    Build hyperledger fabric 2.4 development environment and simple case based on Debian

Run test

Start fabric network

  1. Enter the test network directory of fabric sample

    cd fabric-samples/test-network
  2. working./network.sh up Start network

    Creating 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.comandpeer0.org2.example.comIt 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

Build hyperledger fabric 2.4 development environment and simple case based on Debian

Deploy chaincode

It is recommended that all deployment operations be performed inrootAccount, otherwise unknown errors may occur. The following process is the author’s nonrootProblems encountered by the user. All instructions for rebuilding the virtual machine arerootThe 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 deployCCCommand 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 usergoCommand available, checkrootusergoCommand available, onlysudoIt cannot be used after. After checking the data, it was found that this was becauselinuxThe system is restricted to use for safetysudoThe user-defined environment variables will be cleared. The simplest solution is to/etc/sudoersThis restriction is directly annotated in the file1
Build hyperledger fabric 2.4 development environment and simple case based on Debian
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,directCommand 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/protobufAfter downloading and installing manually and running again, the error remains unchanged. At this time, check the localGOPATHAlready exists in the directorygithub.com/golang/protobufPackage, why is it not recognized? At this point, you have an idea to usego envcheckGOPATHEnvironment variable. It is found that it is inconsistent with the local user. The originalsudoCommand will userootofgoEnvironment 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 torootReconfigure under usergoAgent 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 setfabricThe environment variables of the executable file must be guaranteed to successfullytest-networkUse under directorypeerCommand.

  1. Set fabric_ CFG_ Path variable, under which core Yaml file

    export FABRIC_CFG_PATH=$PWD/../config/
    # export FABRIC_CFG_PATH=/usr/local/fabric/config/
  2. Set otherOrg1Organizational 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
  3. 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":[]}'

    Build hyperledger fabric 2.4 development environment and simple case based on Debian

  4. Query ledger asset list

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

    Build hyperledger fabric 2.4 development environment and simple case based on Debian

  5. 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"]}'

    Build hyperledger fabric 2.4 development environment and simple case based on Debian

  6. 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.

becauseasset-transfer (basic)The endorsement strategy of the chain code requires the transaction to be approved at the same timeOrg1andOrg2Signature, so chain code call instructions need to use--peerAddressesLabel to point topeer0.org1.example.comandpeer0.org2.example.com; Because the networkTLSIs turned on, and the command also needs to use--tlsRootCertFilesLabel points to eachpeerNodalTLSCertificates.

reference


  1. QQ_ Jwang_ 03215367. solve the command not found error MOOC [2018-07-31] ↩
  2. Mu Zifeng Failed to normalize chaincode path:’Go list’failed with: go Blog Garden [November 27, 2020] ↩