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
}
相关推荐
梦昼初DawnDream4 小时前
linux安全基线
linux·运维·安全
Broken Arrows4 小时前
在Linux系统中,top命令的显示参数详解
linux·运维·服务器
code-vibe6 小时前
物理机 kali 改造笔记 (一)
linux·运维·服务器
小坏讲微服务6 小时前
五分钟使用 Docker-compose搭建 Redis 8.0 中间件
运维·redis·docker·中间件·容器·kubernetes·k8s
老黄编程6 小时前
03-gpg(证书管理 )详细范例
linux·运维·ubuntu·数字证书
Aimyon_367 小时前
MinerU Docker自定义版本部署
运维·docker·容器
莱茶荼菜7 小时前
Ubuntu 20.04 系统库管理详细教程
linux·运维·ubuntu
迅为电子8 小时前
嵌入式Linux新手入门:北京迅为3568开发板驱动开发第二章helloworld 驱动实验
linux·运维·驱动开发
kyle~11 小时前
机器视觉---Intel RealSense SDK 2.0 开发流程
运维·c++·windows·深度相机·intel realsense
数智大号12 小时前
超云发布R2425存储服务器:以全栈自研引领国产存储新方向
运维·服务器