github.com/darrenli6/fabric-sdk-example@v0.0.0-20220109053535-94b13b56df8c/examples/ccchecker/chaincodes/newkeyperinvoke/newkeyperinvoke.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/core/chaincode/shim"
    23  	pb "github.com/hyperledger/fabric/protos/peer"
    24  )
    25  
    26  // NewKeyPerInvoke is allows the following transactions
    27  //    "put", "key", val - returns "OK" on success
    28  //    "get", "key" - returns val stored previously
    29  type NewKeyPerInvoke struct {
    30  }
    31  
    32  //Init implements chaincode's Init interface
    33  func (t *NewKeyPerInvoke) Init(stub shim.ChaincodeStubInterface) pb.Response {
    34  	return shim.Success(nil)
    35  }
    36  
    37  //Invoke implements chaincode's Invoke interface
    38  func (t *NewKeyPerInvoke) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
    39  	args := stub.GetArgs()
    40  	if len(args) < 2 {
    41  		return shim.Error(fmt.Sprintf("invalid number of args %d", len(args)))
    42  	}
    43  	f := string(args[0])
    44  	if f == "put" {
    45  		if len(args) < 3 {
    46  			return shim.Error(fmt.Sprintf("invalid number of args for put %d", len(args)))
    47  		}
    48  		err := stub.PutState(string(args[1]), args[2])
    49  		if err != nil {
    50  			return shim.Error(err.Error())
    51  		}
    52  		return shim.Success([]byte("OK"))
    53  	} else if f == "get" {
    54  		// Get the state from the ledger
    55  		val, err := stub.GetState(string(args[1]))
    56  		if err != nil {
    57  			return shim.Error(err.Error())
    58  		}
    59  		return shim.Success(val)
    60  	}
    61  	return shim.Error(fmt.Sprintf("unknown function %s", f))
    62  }
    63  
    64  func main() {
    65  	err := shim.Start(new(NewKeyPerInvoke))
    66  	if err != nil {
    67  		fmt.Printf("Error starting New key per invoke: %s", err)
    68  	}
    69  }