chaincode如何获得Hyperledger Fabric 2.x中的块高度?



我在Hyperledger Fabric 2.4中编码。我需要查询链码中的当前块高度,但我没有找到这样的函数。我怎样才能做到这一点呢?

Chaincode可以通过system chaincode获取通道信息。system chaincode是"内置的";当区块链网络启动

通道信息(带块高度)可通过QSCC系统链码获得。

查询系统链码(QSCC)在所有对等体中运行,提供分类账api,包括块查询,交易查询等

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
}

相关内容

  • 没有找到相关文章

最新更新