Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Blockchain by (4.1k points)

Is there a chaincode shim function with which I can retrieve all the keys (maybe including values) of the world state in a Hyperledger Fabric chaincode?

1 Answer

0 votes
by (14.4k points)

It is indeed possible to run a loop over all the keys in the chaincode state of a particular Smart Contract. You can use the stub.GetStateByRange() function to do that. 

Here's how:

    keysIter, error := stub.GetStateByRange(startKey, endKey)

    if error != nil {

        return shim.Error(fmt.Sprintf("keys operation failed. Error accessing state: %s", error))

    }

    defer keysIter.Close()

    var keys []string

    for keysIter.HasNext() {

        key, _, iterErr := keysIter.Next()

        if iterErr != nil {

            return shim.Error(fmt.Sprintf("keys operation failed. Error accessing state: %s", error))

        }

        keys = append(keys, key)

    }

Browse Categories

...