Fabric hyperledger learning [12] Hyperledger Fabric 2.4+Gin framework+Gateway read/write ledger data (Go version)

Fabric2.4+Gin framework+Gateway read/write ledger data

Advantages of the Gin framework

  1. Lightweight, high performance, strong scalability, strong stability, relatively simple
  2. Gin is an HTTP web framework implemented in Go/golang language , with simple interface and high performance
  3. Gin is a golang micro-framework with elegant packaging, friendly API, clear source code annotations, fast, flexible, and fault-tolerant convenience.
  4. In fact, for golang, the dependence of the web framework is much smaller than that of Python, Java and the like. Its own net/http is simple enough and its performance is very good.
  5. A framework is more like a collection of commonly used functions or tools. With the help of framework development, not only can save a lot of time brought by commonly used packages, but also help the team's coding style and form norms.

Fabric-Gateway

Fabric-Gateway is a service added by Hyperledger Fabric v2.4 on peer. It gradually reduces the frequency of use of Java SDK API, and hopes that everyone's client development will be completed using Gateway.

The gateway SDK is a tool for applications to interact with the blockchain network. It provides some simple APIs to submit transactions or queries to the ledger. Only one peer needs to run an application process to submit transactions.

Application developers can focus on business logic without having to deal with Fabric's infrastructure logic. Therefore, the API provides a logical abstraction of organizations and contracts, not operations or chaincodes and peers

https://hyperledger-fabric.readthedocs.io/en/latest/gateway.html official document address go version

What files do we need to prepare for Gateway to build the client

First of all, in order to submit a transaction, we need to connect to the Fabric network with a legal identity (Identities).

When you create identities, you will generate key certificate materials for nodes and accounts respectively. The account here is the identity we need in the client.

Different from the familiar login method based on account number and password, Fabric uses a private key and a certificate (including a public key signed by a trusted entity) to identify an identity.

Therefore, we need to provide a registration certificate and public key of an account trusted by the current channel.

Secondly, to communicate with the peer node, you need to specify the peer's endpoint (endpoint). The Fabric communication process usually enables the TLS protocol to ensure security, so we also need to provide the TLS certificate of the above account.

Finally, you also need to specify the channel where the chaincode to be called is located , the name of the chaincode, the name of the contract method to be called, and the parameters to be passed to the method * (will be reflected in the code later)

Why did Gateway Client not specify an endorsement node in the whole process? (Principle of requesting endorsement)

When using the peer chaincode invoke command to submit a transaction, we need to use –peerAddresses to specify the endorsement node, and later use –TLSRootCertFile to specify the TLS root certificate used to communicate with the endorsement node. When we need multiple nodes for endorsement, the CLI needs to be in specified one by one in the command.

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 mycc --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":"Init","Args":["A","100","B","200"]}'

But when using the Gateway API to develop the client, did you find that we didn't specify any endorsement-related information except specifying which peer node to communicate with?

This feature benefits from Service Discovery.

If the client wants to complete a series of tasks interacting with the Fabric network, it is necessary to know the topology of the network and various policies of related channels (such as endorsement policies).

In the early days, these were statically configured by programmers locally on the client, but the network topology is volatile, and it is impossible for a mature client application to manually modify the configuration of the client every time it connects. found to complete the endorsement.

Service discovery is part of peer node functionality. The network topology, endorsement policy, and online nodes can be obtained through service discovery.

Our Gateway client calls the service discovery through the Peer node to obtain the endorsement policy of the target chain code, and learns the set of endorsement nodes (including IP addresses and ports) that are currently online that can meet the endorsement policy. Gateway selects the number of nodes that meet the endorsement policy by default. The least set of nodes sending endorsement requests will be randomly selected if the number of nodes in each set is the same.

So if the endorsement fails, please check the node status and whether service discovery is started.

Install Gin

go get -u github.com/gin-gonic/gin

避雷:go版本要在1.45版本及其以上,不然无法使用Gin框架里面的部分组件

insert image description here

Prerequisites Successful deployment of Fabric2.4 (or other versions) network

For details, please refer to my blog:

Fabric Hyperledger Learning [4] Deploy and build Hyperledger Fabric2.4 (2.X) blockchain network in Ububtu environment

./network.sh up createChannel -ca -s couchdb   如果想要同时启动CA服务器和couchdb

!!!!!!!!!假如启动失败,可能之前测试网络时出现重复或者已经存在的镜像,删除即可   

docker ps -qa | xargs docker stop

docker ps -qa | xargs docker rm

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-a4HXK0Yz-1684376642148) (Gin framework access ledger data.assets/image-20230307121534532.png)]

Install and deploy the official asset chain code (you can find it in the official chain code folder)

For how to deploy the go language chain code written by yourself and instantiate the test, refer to my blog to learn:

Fabric Hyperledger Learning [2] Deploy self-written go language chain code and instantiate test in Fabric2.4 network environment (hands-on teaching, super detailed steps)

insert image description here

./network.sh deployCC -ccn basic -ccp ../asset-transfer-basic/chaincode-go -ccl go
// 以org1的组织管理员身份去操作链码:
export PATH=${
    
    PWD}/../bin:$PATH
export FABRIC_CFG_PATH=$PWD/../config/
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/Admin@org1.example.com/msp
export CORE_PEER_ADDRESS=localhost:7051

Initialize the 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 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":[""]}'

add 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":"CreateAsset","Args":["asset66", "yellow", "6", "Tom", "130660"]}'

insert image description here

accessCouchDb

localhost:5984/_utils   

Visit couchdb, you can see that the value has been stored

The default username and password are: admin and adminpw

insert image description here
insert image description here

Start integrating the Gin framework to access ledger data for read and write operations

Create a new go project, and put the certificate file in the virtual machine into the same level directory of the go project

insert image description here

insert image description here

Modify configuration information

Here you need to modify the IP to your own virtual machine IP or your own server IP

const (
   mspID         = "Org1MSP"
   cryptoPath    = "./peerOrganizations/org1.example.com"
   certPath      = cryptoPath + "/users/[email protected]/msp/signcerts/cert.pem"
   keyPath       = cryptoPath + "/users/[email protected]/msp/keystore/"
   tlsCertPath   = cryptoPath + "/peers/peer0.org1.example.com/tls/ca.crt"
   peerEndpoint  = "192.168.239.131:7051" // 修改成服务器IP地址或者自己虚拟机里面的IP地址
   gatewayPeer   = "peer0.org1.example.com"
   channelName   = "mychannel"
   chaincodeName = "basic"
)

Start the go project, the backend has already queried the initialized asset information, and then we will implement the query in the fabric network

insert image description here

ApiPost7 interface test, get all asset information localhost:8082/fabric/GetAllAssets

insert image description here

Create Asset localhost:8082/fabric/CreateAsset

insert image description here

Query again, you can query the asset information created in the previous step localhost:8082/fabric/GetAllAssets

insert image description here

Access CouchDb, the added asset information has been uploaded, and the data has been uploaded successfully

insert image description here

insert image description here

Guess you like

Origin blog.csdn.net/weixin_42694422/article/details/130741285