How to get all transaction history against a chaincode in Hyperledger fabric

10,299

Solution 1

You can develop the proper indexing and query function in your chaincode.

Meaning for each transaction you store its details in the internal key/value store (stub.PutState) with the user as key and return all the transactions associated to a user in your query (stub.GetState).

Solution 2

/chain/blocks/{Block} endpoint carries ordered list of transactions in a specified block.

Use /chain endpoint to get the height (number of blocks) of your chain, and then retrieve transactions from each block using /chain/blocks/{Block} REST endpoint.

Solution 3

The best and simplest way is to use the shim package function

GetHistoryForKey(key string)

As the documentation says:

GetHistoryForKey function can be invoked by a chaincode to return a history of key values across time. GetHistoryForKey is intended to be used for read-only queries.

Solution 4

If you are using composer-client, you can simply use the Historian command.

 var historian = await businessNetworkConnection.getHistorian();
 historian.getAll().then(historianRecords => console.log(historianRecords));

Solution 5

IF anyone need Java SDk and go chaincode combination. There you go

answered here similar question

Java code

public List<HistoryDao> getUFOHistory(String key) throws Exception {
    String[] args = { key };
    Logger.getLogger(QueryChaincode.class.getName()).log(Level.INFO, "UFO communication history - " + args[0]);

    Collection<ProposalResponse> responses1Query = ucc.getChannelClient().queryByChainCode("skynetchaincode", "getHistoryForUFO", args);
    String stringResponse = null;
    ArrayList<HistoryDao> newArrayList = new ArrayList<>();
    for (ProposalResponse pres : responses1Query) {
        stringResponse = new String(pres.getChaincodeActionResponsePayload());
        Logger.getLogger(QueryChaincode.class.getName()).log(Level.INFO, stringResponse);
        newArrayList = gson.fromJson(stringResponse, new TypeToken<ArrayList<HistoryDao>>() {
        }.getType());
    }
    if (null == stringResponse)
        stringResponse = "Not able to find any ufo communication history";
    return newArrayList;
}

and you go chancode implemetation is as follows

Go code

func (t *SmartContract) getHistoryForUFO(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {

    if len(args) < 1 {
            return shim.Error("Incorrect number of arguments. Expecting 1")
    }

    ufoId := args[0]
    resultsIterator, err := APIstub.GetHistoryForKey(ufoId)
    if err != nil {
            return shim.Error(err.Error())
    }
    defer resultsIterator.Close()

    var buffer bytes.Buffer
    buffer.WriteString("[")

    bArrayMemberAlreadyWritten := false
    for resultsIterator.HasNext() {
            response, err := resultsIterator.Next()
            if err != nil {
                    return shim.Error(err.Error())
            }
            // Add a comma before array members, suppress it for the first array member
            if bArrayMemberAlreadyWritten == true {
                    buffer.WriteString(",")
            }
            buffer.WriteString("{\"TxId\":")
            buffer.WriteString("\"")
            buffer.WriteString(response.TxId)
            buffer.WriteString("\"")

            buffer.WriteString(", \"Value\":")
            // if it was a delete operation on given key, then we need to set the
            //corresponding value null. Else, we will write the response.Value
            //as-is (as the Value itself a JSON)
            if response.IsDelete {
                    buffer.WriteString("null")
            } else {
                    buffer.WriteString(string(response.Value))
            }

            buffer.WriteString(", \"Timestamp\":")
            buffer.WriteString("\"")
            buffer.WriteString(time.Unix(response.Timestamp.Seconds, int64(response.Timestamp.Nanos)).String())
            buffer.WriteString("\"")

            buffer.WriteString(", \"IsDelete\":")
            buffer.WriteString("\"")
            buffer.WriteString(strconv.FormatBool(response.IsDelete))
            buffer.WriteString("\"")

            buffer.WriteString("}")
            bArrayMemberAlreadyWritten = true
    }
    buffer.WriteString("]")

    fmt.Printf("- History returning:\n%s\n", buffer.String())
    return shim.Success(buffer.Bytes())

}

Let me know if you question.

Share:
10,299

Related videos on Youtube

Ahmed Shareef
Author by

Ahmed Shareef

Updated on October 09, 2022

Comments

  • Ahmed Shareef
    Ahmed Shareef over 1 year

    I am able to do transactions in Hyperledger (fabric implementation). I want to see all the transactions and its payload details initiated by a user by passing the user's key.

    for example:

    A transfers 10 units to B
    A transfers 5 units to C
    D transfers 8 units to A
    

    When I pass A's key then fabric must provide me all the transactions of A. Is there any way? Or which fabric API function call should I use?

  • Ahmed Shareef
    Ahmed Shareef over 7 years
    I think there should be the functionality to see at least all the transactions in one call, but fabric has given REST API GET/transactions/{tx_UUID}, using which we can see only one transaction at a time. For example Bitcoin Blockchain has provided that.
  • Ahmed Shareef
    Ahmed Shareef over 7 years
    Thanks but I resolved this issue by maintaining indexing approach suggested by Marc Campora, in this way I get all the transaction information at one call, It does not mean that your answer is wrong, but in your approach I have to loop to get data of each transaction.
  • morpheus
    morpheus over 4 years
    Note that prior to v2.0 this method does not return results in any chronological order. See the complete thread at lists.hyperledger.org/g/fabric/topic/33139463#6751
  • Vijay
    Vijay over 2 years
    This answer for get the state. you can visit this link for getting history of record gist.github.com/mrvijaycode/9692319998605372848bb85b37650aab
  • Vijay
    Vijay over 2 years
    for more detailed soultion for this refer the link gist.github.com/mrvijaycode/9692319998605372848bb85b37650aab