Hyperledger Cookbook
上QQ阅读APP看书,第一时间看更新

The query and getHistory functions

ChaincodeStubInterface provides GetState, query functions. We can call this functions by passing assetId. This will trigger chaincode to get the corresponding result.

The getHistory function is used to view the records returned from the transaction history; all records are associated with assetId. Each record contains a related transaction ID and timestamp. With the timestamp, we know when the asset status was updated in the past.

Once the data is saved to blockchain, the application needs to query the chaincode data to check the OrgAsset information, shown as follows:

func (c *AssetMgr) getHistory(stub shim.ChaincodeStubInterface, args []string) pb.Response {
type AuditHistory struct {
TxId string `json:"txId"`
Value OrgAsset `json:"value"`
}
var history []AuditHistory
var orgAsset OrgAsset
assetId := args[0]
// Get History
resultsIterator, err := stub.GetHistoryForKey(assetId)
defer resultsIterator.Close()
for resultsIterator.HasNext() {
historyData, err := resultsIterator.Next()
var tx AuditHistory
tx.TxId = historyData.TxId
json.Unmarshal(historyData.Value, &orgAsset)
tx.Value = orgAsset //copy orgAsset over
history = append(history, tx) //add this tx to the list
}
..
}