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
}
相关推荐
Sylvan Ding1 小时前
远程主机状态监控-GPU服务器状态监控-深度学习服务器状态监控
运维·服务器·深度学习·监控·远程·gpu状态
北漂老男孩2 小时前
在 Linux 上安装 MATLAB:完整指南与疑难解决方案
linux·运维·matlab
Why not try?!2 小时前
Centos7 中 Docker运行配置Apache
运维·docker·容器
杰克逊的日记2 小时前
Flink运维要点
大数据·运维·flink
hnlucky2 小时前
如何彻底清空docker里面不使用的容器?
运维·docker·容器
像风一样的男人@3 小时前
Linux --systemctl损坏
linux·运维·服务器
南方以南_3 小时前
【云实验】搭建个人网盘实验
linux·运维·服务器
humors2213 小时前
Windows运维工具批处理版
运维·windows·计算机·电脑·笔记本·维护·台式机
xbd_zc4 小时前
【Linux Nano Vim快捷键大全】
linux·运维·vim
Mapleay4 小时前
ubuntu 更新华为源
运维·服务器·ubuntu