github.com/leonlxy/hyperledger@v1.0.0-alpha.0.20170427033203-34922035d248/core/scc/samplesyscc/samplesyscc.go (about) 1 /* 2 Copyright IBM Corp. 2016 All Rights Reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package samplesyscc 18 19 import ( 20 "github.com/hyperledger/fabric/core/chaincode/shim" 21 pb "github.com/hyperledger/fabric/protos/peer" 22 ) 23 24 // SampleSysCC example simple Chaincode implementation 25 type SampleSysCC struct { 26 } 27 28 // Init initializes the sample system chaincode by storing the key and value 29 // arguments passed in as parameters 30 func (t *SampleSysCC) Init(stub shim.ChaincodeStubInterface) pb.Response { 31 //as system chaincodes do not take part in consensus and are part of the system, 32 //best practice to do nothing (or very little) in Init. 33 34 return shim.Success(nil) 35 } 36 37 // Invoke gets the supplied key and if it exists, updates the key with the newly 38 // supplied value. 39 func (t *SampleSysCC) Invoke(stub shim.ChaincodeStubInterface) pb.Response { 40 f, args := stub.GetFunctionAndParameters() 41 42 switch f { 43 case "putval": 44 if len(args) != 2 { 45 return shim.Error("need 2 args (key and a value)") 46 } 47 48 // Initialize the chaincode 49 key := args[0] 50 val := args[1] 51 52 _, err := stub.GetState(key) 53 if err != nil { 54 jsonResp := "{\"Error\":\"Failed to get val for " + key + "\"}" 55 return shim.Error(jsonResp) 56 } 57 58 // Write the state to the ledger 59 err = stub.PutState(key, []byte(val)) 60 if err != nil { 61 return shim.Error(err.Error()) 62 } 63 64 return shim.Success(nil) 65 case "getval": 66 var err error 67 68 if len(args) != 1 { 69 return shim.Error("Incorrect number of arguments. Expecting key to query") 70 } 71 72 key := args[0] 73 74 // Get the state from the ledger 75 valbytes, err := stub.GetState(key) 76 if err != nil { 77 jsonResp := "{\"Error\":\"Failed to get state for " + key + "\"}" 78 return shim.Error(jsonResp) 79 } 80 81 if valbytes == nil { 82 jsonResp := "{\"Error\":\"Nil val for " + key + "\"}" 83 return shim.Error(jsonResp) 84 } 85 86 return shim.Success(valbytes) 87 default: 88 jsonResp := "{\"Error\":\"Unknown functon " + f + "\"}" 89 return shim.Error(jsonResp) 90 } 91 }