11

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?

5 Answers 5

5

/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.

1
  • 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. Nov 25, 2016 at 7:11
3

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).

2
  • 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. Nov 8, 2016 at 5:27
  • This answer for get the state. you can visit this link for getting history of record gist.github.com/mrvijaycode/9692319998605372848bb85b37650aab
    – Vijay
    Aug 26, 2021 at 0:50
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.

2
1

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.

0
1

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));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.