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
}
相关推荐
IT成长日记23 分钟前
【Docker基础】Docker数据卷管理:docker volume ls及其参数详解
运维·docker·容器·volume ls
zkmall2 小时前
企业电商解决方案哪家好?ZKmall模块商城全渠道支持 + 定制化服务更省心
大数据·运维·重构·架构·开源
绝不偷吃4 小时前
ELK日志分析系统
运维·elk·jenkins
朱包林5 小时前
day45-nginx复杂跳转与https
linux·运维·服务器·网络·云计算
孙克旭_5 小时前
day045-nginx跳转功能补充与https
linux·运维·nginx·https
Hacker_Oldv7 小时前
软件测试(功能、工具、接口、性能、自动化、测开)详解
运维·自动化
Java樱木7 小时前
使用字节Trae + MCP,UI 到网页自动化。
运维·自动化
无敌暴龙兽z9 小时前
离线环境安装elk及设置密码认证
运维·elk
好奇的菜鸟10 小时前
如何在 Ubuntu 24.04 (Noble) 上使用阿里源
linux·运维·ubuntu
bcbobo21cn10 小时前
初步了解Linux etc/profile文件
linux·运维·服务器·shell·profile