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
}
相关推荐
CS Beginner23 分钟前
【Linux】快速配置wifi和SSH服务
linux·运维·ssh
我也要当昏君23 分钟前
第一节(代入排除法)
运维
become__better23 分钟前
判断ceph osd 节点磁盘异常
linux·运维·ceph
计算机小手31 分钟前
Kong + Konga 网关入门实践:Docker 部署、反向代理与插件使用指南
运维·经验分享·网络协议·docker·kong·开源软件
回忆是昨天里的海1 小时前
docker自定义网络-简单总结
运维·docker·容器
小鹏linux1 小时前
【linux】进程与服务管理命令 - at
linux·运维·服务器
.生产的驴1 小时前
DockerCompoe 部署注册中心Nacos 一键部署 单机+Mysql8
java·linux·运维·spring boot·缓存·docker·doc
FIT2CLOUD飞致云2 小时前
操作教程丨通过1Panel轻松安装和管理MySQL开源数据库
linux·运维·服务器·mysql·开源·1panel
222you2 小时前
前后端分离项目在云服务器上的部署(Spring Boot + Vue)
运维·服务器·spring boot
QT 小鲜肉2 小时前
【Linux命令大全】001.文件管理之lsattr命令(实操篇)
linux·运维·服务器·笔记·elasticsearch