As ledger contains a sequence of transaction, How can I query the current state of ledger and Historic data from ledger.
Asked
Active
Viewed 6,573 times
2 Answers
3
If you interested in history data in context of the chaincode, you could use ChaincodeStubInterface
API, e.g.
// GetHistoryForKey returns a history of key values across time.
// For each historic key update, the historic value and associated
// transaction id and timestamp are returned. The timestamp is the
// timestamp provided by the client in the proposal header.
// GetHistoryForKey requires peer configuration
// core.ledger.history.enableHistoryDatabase to be true.
// The query is NOT re-executed during validation phase, phantom reads are
// not detected. That is, other committed transactions may have updated
// the key concurrently, impacting the result set, and this would not be
// detected at validation/commit time. Applications susceptible to this
// should therefore not use GetHistoryForKey as part of transactions that
// update ledger, and should limit use to read-only chaincode operations.
GetHistoryForKey(key string) (HistoryQueryIteratorInterface, error)
which is capable to retrieve entire history for given key, you receiving back iterator, which will provide you insight on historical changes of the the given key, for example:
historyIer, err := stub.GetHistoryForKey(yourKeyIsHere)
if err != nil {
fmt.Println(errMsg)
return shim.Error(errMsg)
}
if historyIer.HasNext() {
modification, err := historyIer.Next()
if err != nil {
fmt.Println(errMsg)
return shim.Error(errMsg)
}
fmt.Println("Returning information about", string(modification.Value))
}
Also note, that you need to make sure history db is enabled, in core.yaml
file part of the ledger section:
ledger:
history:
# enableHistoryDatabase - options are true or false
# Indicates if the history of key updates should be stored.
# All history 'index' will be stored in goleveldb, regardless if using
# CouchDB or alternate database for the state.
enableHistoryDatabase: true

Artem Barger
- 40,769
- 9
- 59
- 81
-
@ Hi Artem: can we query ledger based on transaction Id. – Manoj Indian Jul 13 '17 at 11:30
-
1There is no way with shim API to query ledger for txID, while at applicatin level, you can do it with SDK, see example here: https://fabric-sdk-node.github.io/Channel.html#queryTransaction – Artem Barger Jul 13 '17 at 12:14
-
Hi, I wonder if the historyDB is used to store the modification history of a key? Is that correct? – 4t8dds May 15 '18 at 23:30
-
@Wandy yes, it is. – Artem Barger May 16 '18 at 05:10
-
@ArtemBarger where does GetHistoryForKey pull data from? since World State does not store history data is it directly fetched from the blockchain? – Pool Aug 04 '20 at 04:50
-
From history database – Artem Barger Aug 04 '20 at 21:16