I'm coding in Hyperledger Fabric 2.4. I need to query the current block height in the chaincode but I didn't find such a function. How can I achieve this?
Asked
Active
Viewed 68 times
1 Answers
1
Chaincode can obtain information about the channel, using the system chaincode
. The system chaincode
is "built-in" when a blockchain network is up
channel information(with block height) can be obtained through the QSCC
system chaincode.
Query system chaincode (QSCC) runs in all peers to provide ledger APIs which include block query, transaction query etc
import (
"fmt"
"github.com/hyperledger/fabric-chaincode-go/shim"
pb "github.com/hyperledger/fabric-protos-go/peer"
"github.com/golang/protobuf/proto"
commonProto "github.com/hyperledger/fabric-protos-go/common"
)
func (t *MyChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
// ... your chaincode logic ...
// Define the system chaincode you want to call and the arguments.
// In this example, we'll query the block height using the "qscc" system chaincode.
sysCC := "qscc"
fcn := "GetChainInfo"
channelID := "mychannel"
// Call the system chaincode
response := stub.InvokeChaincode(sysCC, [][]byte{[]byte(fcn), []byte(channelID)}, channelID)
// Check the response for errors
if response.Status != shim.OK {
errMsg := fmt.Sprintf("Error invoking '%s' chaincode: %s", sysCC, response.Message)
return shim.Error(errMsg)
}
// Process the response payload
result := response.Payload
// Unmarshal the response payload
chainInfo := &commonProto.BlockchainInfo{}
err := proto.Unmarshal(result, chainInfo)
if err != nil {
errMsg := fmt.Sprintf("Error unmarshaling BlockchainInfo: %s", err)
return shim.Error(errMsg)
}
// Get the block height
blockHeight := chainInfo.GetHeight()
// ... do something with the block height
// ... continue with your chaincode logic and return the appropriate response
}

myeongkil kim
- 2,465
- 4
- 16
- 22