github.com/kaituanwang/hyperledger@v2.0.1+incompatible/core/chaincode/testdata/src/chaincodes/passthru/passthru.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 main 18 19 import ( 20 "fmt" 21 22 "github.com/hyperledger/fabric-chaincode-go/shim" 23 pb "github.com/hyperledger/fabric-protos-go/peer" 24 ) 25 26 // PassthruChaincode passes thru invoke and query to another chaincode where 27 // called ChaincodeID = args[0] 28 // called chaincode's function = args[1] 29 // called chaincode's args = args[2:len-2] 30 // called ChannelID = args[len-1] 31 type PassthruChaincode struct { 32 } 33 34 func toChaincodeArgs(args ...string) [][]byte { 35 bargs := make([][]byte, len(args)) 36 for i, arg := range args { 37 bargs[i] = []byte(arg) 38 } 39 return bargs 40 } 41 42 func (p *PassthruChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response { 43 fmt.Println("passthru Init") 44 function, _ := stub.GetFunctionAndParameters() 45 return shim.Success([]byte(function)) 46 } 47 48 // helper 49 func (p *PassthruChaincode) iq(stub shim.ChaincodeStubInterface, chaincode string, args []string, channel string) pb.Response { 50 return stub.InvokeChaincode(chaincode, toChaincodeArgs(args...), channel) 51 } 52 53 // Invoke passes through the invoke call 54 // The chaincode ID to call MUST be specified as first argument 55 // The channel ID to call the chaincode on MUST be specified as the last argument 56 func (p *PassthruChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response { 57 args := stub.GetStringArgs() 58 fmt.Println("passthru Invoke ", args) 59 60 if len(args) < 2 { 61 return shim.Error("Channel to call on not provided") 62 } 63 channelToCallOn := args[len(args)-1] 64 if len(args) < 1 { 65 return shim.Error("Chaincode to call not provided") 66 } 67 chaincodeToCall := args[0] 68 69 response := p.iq(stub, chaincodeToCall, args[1:len(args)-1], channelToCallOn) 70 if response.Status != shim.OK { 71 msg := response.Message 72 if response.Payload != nil { 73 msg = string(response.Payload) 74 } 75 errStr := fmt.Sprintf("Failed to invoke chaincode. Got error: %s", msg) 76 fmt.Printf(errStr) 77 return shim.Error(errStr) 78 } 79 return response 80 } 81 82 func main() { 83 err := shim.Start(new(PassthruChaincode)) 84 if err != nil { 85 fmt.Printf("Error starting Passthru chaincode: %s", err) 86 } 87 }