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
}
相关推荐
AC赳赳老秦8 分钟前
OpenClaw text-translate技能:多语言批量翻译,解决跨境工作沟通难题
大数据·运维·数据库·人工智能·python·deepseek·openclaw
andeyeluguo26 分钟前
docker总结
运维·docker·容器
w61001046628 分钟前
cka-2026-etcd
运维·服务器·etcd·cka
航Hang*42 分钟前
VMware vSphere 云平台运维与管理基础——第5章:VMware vSphere 5.5 高级特性
运维·服务器·开发语言·windows·学习·虚拟化
Benszen1 小时前
Linux容器:轻量级虚拟化革命
java·linux·运维
问简1 小时前
ubuntu 字体相关问题
运维·服务器·ubuntu
勿忘,瞬间1 小时前
网络编程套接字
运维·服务器·网络
weixin_413838561 小时前
基于区块链的校园二手书交易系统
vue.js·spring·区块链·fabric
funnycoffee1232 小时前
华为USG防火墙的HRP逃逸是什么机制?
运维·服务器·网络·华为usg
开开心心就好2 小时前
能把网页藏在Word里的实用摸鱼工具
linux·运维·服务器·windows·随机森林·逻辑回归·excel