Centos7 Fabric2.4 network construction (3)

Tip: The previous article talked about creating a channel. The orderer uses the osnadmin command to activate the channel, the peer joins the channel, and then updates the anchor node. Now install the chain code.

Table of contents

Preface

1. Install the chaincode in the main script

2. deployCC.sh 

2.1 Chaincode

 2.2 Packaging chain code

2.3 Install the chain code on the peer node

2.4 Approval of chaincode definitions

2.5 Submit the chaincode definition to the channel

2.6 Call chain code


Preface

Part One: Centos7 Fabric2.4 Network Construction (1)_Big. boss’s blog-CSDN blog

Part 2: Centos7 Fabric2.4 network construction (2)_Big. boss’s blog-CSDN blog


提示:用的是官方的例子学习搭建自己的网络,本次是用cryptogen生成证书,单机多节点部署

End users interact with the blockchain ledger by calling smart contracts. In Hyperledger Fabric, smart contracts are deployed in packages called chaincodes. Organizations that want to verify transactions or query ledgers must have chain code installed on peer nodes. All peer nodes that join the channel can install the chain code. After the chain code is installed, channel members can deploy the chain code to the channel and use the chain code. The smart contracts in the code create or update assets on the channel ledger.

Organizations that want to verify transactions or query the ledger need to install chaincode on their peers. After the chaincode is installed on nodes joining the channel, channel members can deploy the chaincode to the channel and use smart contracts in the chaincode to create or update assets on the channel ledger.

1. Install the chaincode in the main script

Users ultimately interact with the blockchain ledger by calling smart contracts. In Hyperledger Fabric, smart contracts are deployed in packages called chain codes.

We can confirm that the channel was successfully created by deploying the chaincode to the channel. We can use the network.sh script to deploy the chain code of asset transfer to the created channel. Use the following command to deploy the chain code to the channel.

./network.sh deployCC -ccn basic -ccp ../asset-transfer-basic/chaincode-go -ccl go

## 调用脚本将链码部署到通道
function deployCC() {
  scripts/deployCC.sh $CHANNEL_NAME $CC_NAME $CC_SRC_PATH $CC_SRC_LANGUAGE $CC_VERSION $CC_SEQUENCE $CC_INIT_FCN $CC_END_POLICY $CC_COLL_CONFIG $CLI_DELAY $MAX_RETRY $VERBOSE

  if [ $? -ne 0 ]; then
    fatalln "Deploying chaincode failed"
  fi
}

2. deployCC.sh 

2.1 Chaincode

We need to package the chaincode first before installing it on our peer node. We use go’s smart contract here.

Before packaging the chaincode, we need to install the dependencies of the chaincode and open the folder where the chaincode is located.

 Dependencies are listed in the go.mod file in the directory

 The go.mod file imports the Fabric contract API into the smart contract package. You can open chaincode/smartcontract.go to understand how the contract API is used to define the SmartContract type at the beginning of the smart contract.

// SmartContract provides functions for managing an Asset
type SmartContract struct {
	contractapi.Contract
}

The SmartContract type is then used to create a transaction context for functions defined in the smart contract that read and write to the BlockChain ledger,

// CreateAsset issues a new asset to the world state with given details.
func (s *SmartContract) CreateAsset(ctx contractapi.TransactionContextInterface, id string, color string, size int, owner string, appraisedValue int) error {
	exists, err := s.AssetExists(ctx, id)
	if err != nil {
		return err
	}
	if exists {
		return fmt.Errorf("the asset %s already exists", id)
	}

	asset := Asset{
		ID:             id,
		Color:          color,
		Size:           size,
		Owner:          owner,
		AppraisedValue: appraisedValue,
	}
	assetJSON, err := json.Marshal(asset)
	if err != nil {
		return err
	}

	return ctx.GetStub().PutState(id, assetJSON)
}

 2.2 Packaging chain code

To install smart contract dependencies, run the following command from the asset-transfer-basic/chaincode-go directory

GO111MODULE=on go mod vendor

If the command is successful, the go package will be installed in a vendor folder

Now that we have the dependencies, we can package the chaincode package back into our working directory so that we can package the chaincode package with our other network artifacts.

You can use the peer CLI to create a chaincode package in the required format. The peer binary file is located in the bin folder of the working directory. You also need to set FABRIC_CFG_PATH to point to the core.yaml file in the working directory.

export PATH=${ROOTDIR}/bin:${PWD}/bin:$PATH
export FABRIC_CFG_PATH=${PWD}/config/

If you want to confirm whether you can use the peer CLI, you can check the peer version. It will prompt that the required version is 2.0.0 or higher.

Next, use the peer lifecycle package command to create the chaincode:

peer lifecycle chaincode package basic.tar.gz --path ./asset-transfer-basic/chaincode-go/ --lang golang --label basic_1.0

This command will create a package named basic.tar.gz in the current directory. The --lang flag is used to specify the chaincode language, and the --path flag provides the location of the smart contract code. The path must be a fully qualified path or a path relative to your current working directory. The --label flag is used to specify the chaincode label, which will identify the chaincode after installation. It is recommended that the label include the chaincode name and version.

2.3 Install the chain code on the peer node

After we package the asset transfer (basic) smart contract, we can install the chaincode on our peer nodes. The chaincode needs to be installed on every peer that will support transactions. Because we are going to set the endorsement policy to require endorsements from Org1 and Org2, we need to install the chaincode on the peers operated by both organizations:

  • peer0.org1.hmw.com
  • peer1.org1.hmw.com
  • peer0.org2.hmw.com
  • peer1.org2.hmw.com

Let us first install the chaincode on Org1 peer0, set the following environment variables, and operate the peer CLI as the Org1 administrator user. Set CORE_PEER_ADDRESS to point to peer0.org1.hmw.com

export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org1MSP"
export CORE_PEER_TLS_ROOTCERT_FILE=${PWD}/organizations/peerOrganizations/org1.hmw.com/tlsca/tlsca.org1.hmw.com-cert.pem
export CORE_PEER_MSPCONFIGPATH=${PWD}/organizations/peerOrganizations/org1.hmw.com/users/[email protected]/msp
export CORE_PEER_ADDRESS=localhost:8051

Send the peer life cycle chaincode install command to install the chaincode on peer0.org1

peer lifecycle chaincode install basic.tar.gz

If the command is successful, the peer will generate and return a bundle identifier. This bundle ID will be used to approve the chaincode in the next step. You should see output similar to the following: 

 In the same way, install the chain code on the remaining peer nodes.

When the chaincode is installed, the chaincode is built by the peer. If there are issues with the smart contract code, the install command will return any build errors from the chaincode.

2.4 Approval of chaincode definitions

After installing the chaincode package, you need to approve the chaincode definition for our organization, which includes important parameters for the chaincode package, such as name, version, and chaincode endorsement policy.

The set of channel members that need to approve a chaincode before it can be deployed is governed by the /Channel/Application/LifecycleEndorsement policy, which by default requires a majority of channel members to approve a chaincode before it can be used on the channel. Therefore, we only have two organizations on the channel, and the majority of the two organizations is 2, so Org1 and Org2 need to approve our basic chain code at the same time.

If an organization has installed chaincode on their peers, they are required to include the packageID in their organization-approved chaincode definition. packageID is used to associate the chaincode installed on the peer node with the approved chaincode definition and allows the organization to use the chaincode to endorse transactions. We can use the peer lifecycle chaincode queryinstalled command to query the packageID installed on the peer.

peer lifecycle chaincode queryinstalled

 The packageID is a hash combination of the chaincode label and the chaincode binary. Each peer will generate the same packageID.

 Next, we will use the packageID when we approve the chaincode, so go ahead and set the environment variable and paste the returned packageID into the command below. Note: Not all users have the same packageID. This step must be completed based on the packageID returned by the query.

export CC_PACKAGE_ID=basic_1.0:dee2d612e15f5059478b9048fa4b3c9f792096554841d642b9b59099fa0e04a4
export ORDERER_CA=${PWD}/organizations/ordererOrganizations/hmw.com/tlsca/tlsca.hmw.com-cert.pem
peer lifecycle chaincode approveformyorg -o localhost:7050 --ordererTLSHostnameOverride orderer0.hmw.com --tls --cafile "$ORDERER_CA" --channelID mychannel --name basic --version 1.0 --package-id $CC_PACKAGE_ID --sequence 1

The above command uses the --package-id flag to include the package identifier in the chaincode definition. The --sequence parameter is an integer that tracks the number of times the chaincode has been defined or updated since the chaincode was first deployed to channel, so the sequence number is 1. When upgrading the basic chaincode, the serial number will be incremented to 2. If you are using the provided low-level Fabric Chaincode Shim API, you can pass the --init-required flag to the above command to request execution of the Init function to initialize the chaincode. The first call to the chaincode needs to target the Init function and include the --isInit flag before you can use other functions in the chaincode to interact with the ledger.

Just now, the identity approval chain code definition of Org2 was used. Org1 configures the environment variables in the same way to complete the Org1 approval chain code definition.

We have now deployed the basic chaincode to most nodes on the channel. Although only most organizations need to approve the chaincode definition (default policy), all organizations need to approve the chaincode definition before they can start the chaincode on peer nodes. If you submit definitions before channel members approve the chaincode, the organization will not be able to endorse the transaction, so it is recommended that all channel members approve the chaincode before submitting it.

2.5 Submit the chaincode definition to the channel

After a sufficient number of organizations approve the chaincode definition, an organization can submit the chaincode definition to the channel. If a majority of channel members approve the chaincode definition, the transaction is successfully submitted and the parameters agreed in the chaincode definition will be in the channel. realized on.

You can check whether channel members have approved the same chaincode definition using the peer lifecycle chaincode checkcommitreadiness command. The flags used for this checkcommitreadiness command are the same as those used to approve your organization's chaincode. However, --package is not required. -id flag.

peer lifecycle chaincode checkcommitreadiness --channelID mychannel --name basic --version 1.0 --sequence 1  --output json

This command generates a json map showing whether the channel member approves the parameters specified in the checkcommitreadiness command

Since both organizations that are members of the channel have approved the same parameters, the chaincode definition is ready to be submitted to the channel. The chaincode can be submitted to the channel using the peer lifecycle chaincode commit command. The commit command requires an organization administrator to submit it. .

export PEER0_ORG1_CA=${PWD}/organizations/peerOrganizations/org1.hmw.com/tlsca/tlsca.org1.hmw.com-cert.pem
export PEER0_ORG2_CA=${PWD}/organizations/peerOrganizations/org2.hmw.com/tlsca/tlsca.org2.hmw.com-cert.pem
peer lifecycle chaincode commit -o localhost:7050 --ordererTLSHostnameOverride orderer0.hmw.com --channelID mychannel --name basic --version 1.0 --sequence 1 --tls --cafile "$ORDERER_CA" --peerAddresses localhost:8051 --tlsRootCertFiles "$PEER0_ORG1_CA" --peerAddresses localhost:8055 --tlsRootCertFiles "$PEER0_ORG2_CA"

The transaction above uses the --peerAddresses flag to locate peer0.org1.hmw.com for Org1 and peer0.org2.hmw.com for Org2. A commit transaction is submitted to the peer joining the channel to query the chaincode definition approved by the organization operating the peer. This command needs to target peers from a sufficient number of organizations to satisfy the policy for deploying the chaincode. Since approvals are distributed within each organization, you can target any peer who is a member of the channel

Endorsements of chaincode definitions by channel members are submitted to the ordering service to be added to blocks and distributed to the channel. The peers on the channel then verify that a sufficient number of organizations have approved the chaincode definition, and the peer lifecycle chaincode commit command will wait for the peer's verification before returning a response.

You can use the peer lifecycle chaincode querycommitted command to confirm whether the chaincode is submitted to the channel.

peer lifecycle chaincode querycommitted --channelID mychannel --name basic --cafile "$ORDERER_CA"

If the chaincode is successfully submitted to the channel, the querycommitted command will return the sequence and version defined by the chaincode

 

2.6 Call chain code

After the chaincode definition is submitted to the channel, the chaincode will be started on peers that join the channel where the chaincode is installed. The asset transfer (basic) chaincode is now ready to be called by client applications. Use the following command to create an initial set of assets on the ledger, please note that the invoke command needs to target a sufficient number of peers to satisfy the chaincode endorsement policy. (Note that the CLI does not access Fabric Gateway peers, so each endorsing node must be specified.)

peer chaincode invoke -o localhost:7050 --ordererTLSHostnameOverride orderer0.hmw.com --tls --cafile "$ORDERER_CA" -C mychannel -n basic --peerAddresses localhost:8051 --tlsRootCertFiles "$PEER0_ORG1_CA" --peerAddresses localhost:8055 --tlsRootCertFiles "$PEER0_ORG2_CA" -c '{"function":"InitLedger","Args":[]}'

If the command is successful, you should see a response similar to the following:

 We can use the query function to read the collection of cars created by the chaincode:

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

 If the command is successful, you should see a response similar to the following:

At this point, the chaincode installation is completed

For related codes, please refer to: Scripts used for Centos7 Fabric2.4 deployment_Big. boss’s blog-CSDN blog


Guess you like

Origin blog.csdn.net/humingwei11/article/details/124128749