Fabric中的溯源方法

背景

在Fabric链码中,我们可以使用PutState方法对一个key的值进行覆盖,当我们再使用GetState查询时是最新的值。如果我们希望找到这个key的修改记录,我们可以使用溯源方法GetHistoryForKey。完整源码链接:https://github.com/hyperledger/fabric-samples/blob/main/asset-transfer-ledger-queries/chaincode-go/asset_transfer_ledger_chaincode.go

代码
go 复制代码
// HistoryQueryResult structure used for returning result of history query
type HistoryQueryResult struct {
	Record    *Asset    `json:"record"`
	TxId      string    `json:"txId"`
	Timestamp time.Time `json:"timestamp"`
	IsDelete  bool      `json:"isDelete"`
}


// GetAssetHistory returns the chain of custody for an asset since issuance.
func (t *SimpleChaincode) GetAssetHistory(ctx contractapi.TransactionContextInterface, assetID string) ([]HistoryQueryResult, error) {
	log.Printf("GetAssetHistory: ID %v", assetID)

	resultsIterator, err := ctx.GetStub().GetHistoryForKey(assetID)
	if err != nil {
		return nil, err
	}
	defer resultsIterator.Close()

	var records []HistoryQueryResult
	for resultsIterator.HasNext() {
		response, err := resultsIterator.Next()
		if err != nil {
			return nil, err
		}

		var asset Asset
		if len(response.Value) > 0 {
			err = json.Unmarshal(response.Value, &asset)
			if err != nil {
				return nil, err
			}
		} else {
			asset = Asset{
				ID: assetID,
			}
		}

		timestamp, err := ptypes.Timestamp(response.Timestamp)
		if err != nil {
			return nil, err
		}

		record := HistoryQueryResult{
			TxId:      response.TxId,
			Timestamp: timestamp,
			Record:    &asset,
			IsDelete:  response.IsDelete,
		}
		records = append(records, record)
	}

	return records, nil
}
相关推荐
小白鸽i1 分钟前
【Linux】已安装的软件如何重新构建deb安装包?
linux·运维·服务器
考虑考虑18 分钟前
JFROG手动上传包
运维·后端·自动化运维
Initialize-le29 分钟前
备份显示成功、恢复却失败?四步验证法
运维
GeofferyLibrom34 分钟前
PS5 自动化挂机指南:基于 Mac + Chiaki-ng 视觉识别——龙信2自动挂机实战
运维·macos·自动化
海宇数据41 分钟前
零信任架构实战:基于海宇企业综合风险报告构建自动化供应商资质审查网关
运维·人工智能·架构·自动化
2603_969579281 小时前
接口文档经常过时?试试自动化文档方案
运维·自动化
程序员-Benothing1 小时前
Linux CPU性能分析:top、mpstat、pidstat、perf实战
linux·运维·服务器
William.csj1 小时前
Bitvise SSH Client——配置跳板机:通过中转服务器连接内网服务器
运维·服务器·ssh
小诗懂技术2 小时前
Linux设备驱动并发控制总结_CSDN
linux·运维·服务器
colinu2 小时前
Docker 容器端口未发布问题快速排查文档
运维·docker·容器