Search code examples
hyperledger-fabrichyperledger-chaincode

How to write a function to be used inside chaincode only (no invoke operation by any peer)?


Example scenario

I have stored the passwords of users, with usernames as key. I want to use a function as a helper function to get that password.

So that I don't have to do error handling every time I want to get password, for matching user entered password in other functions.

Example code:

type User struct {
    Password string `json:"password"`
    Name     string `json:"name"`
}

// Helper fucntion
func (s *SmartContract) GetPassword(ctx contractapi.TransactionContextInterface, _username string) (string, error) {

    dataAsBytes, err := ctx.GetStub().GetState(_username)

    if err != nil {
        return nil, fmt.Errorf("Failed to read from world state. %s", err.Error())
    }

    if dataAsBytes == nil {
        return nil, fmt.Errorf("%s does not exist", _username)
    }

    user := new(User)
    err = json.Unmarshal(dataAsBytes, &user)

    if err != nil {
        return nil, fmt.Errorf("Can't Unmarshal Data")
    }

    return user.Password, nil
}

// Here I used helper function, similarly I will use it in other functions
func (s *SmartContract) AddAsset(ctx contractapi.TransactionContextInterface, _username string, _password string, value string) error {

    temp_password, err := GetPassword(_username, _password)
    if err != nil { return err }
    
    if _password ==  temp_password {
        // Do something
    }

    return nil
}

What could be done, so that only the current chaincode can use the helper function. For additional security, like private methods in Java.


Solution

  • The go contract api honours the public/private pattern that GoLang employs, ie if the method starts with an upper case letter it's exposed and can be called as a transaction, if it starts with a lower case letter then it's not exposed and cannot be called as a transaction. So create a method such as getPasswordHelper and have your transactions use that