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
}
相关推荐
the_fat_bird3 分钟前
ubuntu install nvidia gpu driver
linux·运维·ubuntu
江南风月10 分钟前
WGCLOUD如果使用SQL Server数据库推荐哪个版本
运维·网络·zabbix·运维开发·prometheus
IMPYLH21 分钟前
Linux 的 tac 命令
linux·运维·服务器·bash
计算机安禾25 分钟前
【Linux从入门到精通】第50篇:专栏总结与Linux学习之路的未来展望
linux·运维·学习
yyuuuzz27 分钟前
企业出海技术落地的几个常见问题
运维
byoass37 分钟前
企业云盘高可用架构:主备切换、负载均衡与健康检查实战
运维·网络·安全·架构·云计算·负载均衡
白菜欣1 小时前
Linux —进程概念
linux·运维·服务器
iuu_star1 小时前
Vue+FastAPI 项目宝塔Linux部署指南
linux·运维·fastapi
杜哥无敌1 小时前
FreeSSHd vs FileZilla Server vs SFTPGo:Windows SFTP服务器易用性终极横向测评
运维·服务器·windows
IMPYLH1 小时前
Linux 的 tail 命令
linux·运维·服务器·bash