Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
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)

    }

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.2k users

Browse Categories

...