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
}
相关推荐
馨羽的玩具25 分钟前
查哪个程序一直登录sql server失败
运维·服务器·数据库
苹果醋334 分钟前
[MySQL] MySQL 版本不支持 ST_Distance_Sphere替代方案和解决方案
java·运维·spring boot·mysql·nginx
F_D_Z1 小时前
【解决办法】pip install albumentations安装下载遇19kB/s超级慢细水管
linux·运维·python·pip
luoqice1 小时前
在嵌入式 Linux 系统中,配置 DNS 以实现内网或外网连接
linux·运维·服务器
中心观察者1 小时前
haproxy应用详解
运维
青草地溪水旁1 小时前
Ubuntu上开通Samba网络共享
linux·运维·ubuntu·samba
芥子沫1 小时前
ElasticSearch 的3种数据迁移方案
运维·elasticsearch·搜索引擎
IvanCodes1 小时前
三、Linux用户与权限管理详解
linux·运维·服务器
蝉明✘2 小时前
HAproxy负载均衡
运维·负载均衡
格发许可优化管理系统2 小时前
GTSuite许可证性能优化建议
大数据·运维·数据库·安全·性能优化·数据分析