Last active
January 17, 2019 16:54
-
-
Save javaguirre/53ae0acc97f4cf8d73a45645fe6ed666 to your computer and use it in GitHub Desktop.
Chaincode code example for Hyperledger Fabric
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "github.com/hyperledger/fabric/core/chaincode/shim" | |
| sc "github.com/hyperledger/fabric/protos/peer" | |
| ) | |
| type SmartContract struct { | |
| // Here we can store specific smartcontract data | |
| } | |
| type Asset struct { | |
| Name string `json:"name"` | |
| } | |
| /* | |
| * The Invoke method is called as a result of an application request to run the Smart Contract | |
| * The calling application program has also specified the particular smart contract function to be called, with arguments | |
| */ | |
| func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface) sc.Response { | |
| function, args := APIstub.GetFunctionAndParameters() | |
| switch function { | |
| case "getAsset": | |
| return s.getAsset(APIstub, args) | |
| } | |
| return shim.Error("Invalid Smart Contract function name.") | |
| } | |
| func (s *SmartContract) getAsset( | |
| APIstub shim.ChaincodeStubInterface, args []string) sc.Response { | |
| if len(args) != 1 { | |
| return shim.Error("Incorrect number of arguments. Expecting 1") | |
| } | |
| assetAsBytes, err := APIstub.GetState(args[0]) | |
| if err != nil || len(assetAsBytes) == 0 { | |
| return shim.Error(fmt.Sprintf("No asset with ID: %s", args[0])) | |
| } | |
| return shim.Success(s.getObjectAsBytes(assetLocalID, assetAsBytes)) | |
| } | |
| func (s *SmartContract) getObjectAsBytes( | |
| identificator string, objectAsBytes []byte) []byte { | |
| var buffer bytes.Buffer | |
| buffer.WriteString("{\"Key\":") | |
| buffer.WriteString("\"") | |
| buffer.WriteString(identificator) | |
| buffer.WriteString("\"") | |
| buffer.WriteString(", \"Record\":") | |
| buffer.WriteString(string(objectAsBytes)) | |
| buffer.WriteString("}") | |
| return buffer.Bytes() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment