You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Hyperledger Fabric 2.x(含2.4)链码中获取区块高度?

在Hyperledger Fabric 2.4链码中查询当前区块高度的实现方法

Hyperledger Fabric 2.4的链码上下文(ChaincodeStubInterface)没有直接提供查询区块高度的函数,但可以通过调用QSCC系统链码的GetChainInfo接口实现,该接口会返回当前通道的链状态信息,其中包含区块高度。

实现步骤与代码示例

  1. 在自定义链码中添加查询区块高度的方法,调用QSCC系统链码:
import (
    "fmt"

    "github.com/hyperledger/fabric-contract-api-go/contractapi"
    "github.com/hyperledger/fabric-protos-go/common"
    "google.golang.org/protobuf/proto"
)

// 自定义链码结构体
type YourChaincode struct {
    contractapi.Contract
}

// GetBlockHeight 查询当前通道的区块高度
func (cc *YourChaincode) GetBlockHeight(ctx contractapi.TransactionContextInterface) (int64, error) {
    // 构造QSCC调用参数:方法名+通道ID
    qsccArgs := [][]byte{
        []byte("GetChainInfo"),
        []byte(ctx.GetStub().GetChannelID()),
    }

    // 调用QSCC系统链码,第三个参数为空表示当前通道
    resp, err := ctx.GetStub().InvokeChaincode("qscc", qsccArgs, "")
    if err != nil {
        return 0, fmt.Errorf("调用QSCC失败: %w", err)
    }

    // 反序列化返回的ChainInfo protobuf数据
    var chainInfo common.ChainInfo
    if err = proto.Unmarshal(resp.Payload, &chainInfo); err != nil {
        return 0, fmt.Errorf("解析链信息失败: %w", err)
    }

    // chainInfo.Height即为当前区块高度(创世块对应高度1,后续区块依次递增)
    return chainInfo.Height, nil
}
  1. 依赖安装:确保导入所需的proto包和序列化包,执行以下命令安装依赖:
go get github.com/hyperledger/fabric-protos-go/common
go get google.golang.org/protobuf/proto

注意事项

  • 权限配置:默认通道ACL允许链码调用QSCC的GetChainInfo方法,若通道有自定义ACL配置,需确保对应链码的MSP账号拥有/channel/Application/qscc/GetChainInfo的调用权限。
  • 区块高度定义:Fabric中区块高度指已成功提交的区块总数,创世块编号为0,对应高度1;最新区块的编号为高度-1。

内容的提问来源于stack exchange,提问作者mageover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 15:15:01