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