How to get all transaction history against a chain

2019-03-16 13:51发布

问题:

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?

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



回答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.



回答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.



回答4:

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.



回答5:

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