Help Center > > Developer Guide> Chaincode Development and Debugging> Chaincode Development

Chaincode Development

Updated at: Apr 21, 2020 GMT+08:00

Chaincode is also called smart contract, which is the service logic of interaction between parties in a blockchain network. A chaincode encapsulates service transaction data into code, which runs in a Docker container. Currently, HUAWEI CLOUD BCS supports Golang and Node.js for programming. The following uses Golang as an example.

Each chaincode is a Golang file. After creating such a file, you can perform operations such as function development.

Procedure

  1. Set up the Go development environment and editor.

    • Download and install Go. Version 1.11.12 is recommended.
    • Use an editor you prefer. GoLand is recommended.

  2. Download Fabric source code package as the third-party repository.

    Download link: https://github.com/hyperledger/fabric

    The Fabric source code package must match the BCS service version. If your BCS service is of version 2.x.x (corresponding to Fabric v1.1.0), the Fabric code version should be 1.1. If your BCS service is of version 3.x.x (corresponding to Fabric v1.4.0), the Fabric code version should be 1.4.

  3. Create a project, create a chaincode file, and import package shim.

    Package shim provides APIs to enable your chaincode to interact with the underlying blockchain network to access status variables, transaction contexts, invoker certificates and attributes, and perform other operations such as invoking other chaincodes.

    package test
    
    import (
       "fmt"
       "strconv"
    
       "github.com/hyperledger/fabric/core/chaincode/shim"
       pb "github.com/hyperledger/fabric/protos/peer"
    )

  4. Compile the main function.

    All Golang programs start with the main function, which is used to start a chaincode. When a chaincode instance is deployed on a peer, the main function is executed.

    // SimpleChaincode example simple Chaincode implementation
    type SimpleChaincode struct {
    }
    func main() {
       err := shim.Start(new(SimpleChaincode))
       if err != nil {
          fmt.Printf("Error starting Simple chaincode: %s", err)
       }
    }

  5. Implement the init method.

    The init method is called when a chaincode is deployed on a blockchain network for the first time and is executed by each peer where instances of this chaincode are deployed. This method can be used for all initialization, boot, or configuration tasks.

    func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
       fmt.Println("ex02 Init")
       _, args := stub.GetFunctionAndParameters()
       var A, B string    // Entities
       var Aval, Bval int // Asset holdings
       var err error
    
       if len(args) != 4 {
          return shim.Error("Incorrect number of arguments. Expecting 4")
       }
    
       // Initialize the chaincode
       A = args[0]
       Aval, err = strconv.Atoi(args[1])
       if err != nil {
          return shim.Error("Expecting integer value for asset holding")
       }
       B = args[2]
       Bval, err = strconv.Atoi(args[3])
       if err != nil {
          return shim.Error("Expecting integer value for asset holding")
       }
       fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)
    
       // Write the state to the ledger
       err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
       if err != nil {
          return shim.Error(err.Error())
       }
    
       err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
       if err != nil {
          return shim.Error(err.Error())
       }
    
       return shim.Success(nil)
    }

  6. Implement the invoke method.

    The invoke method is invoked if the status of a blockchain is to be changed. All creation, update, and deletion operations must be encapsulated in the invoke method. This method changes the blockchain status. Therefore, the Fabric code of a blockchain automatically creates a transaction context for this method to be executed. Each invocation of this method is recorded as a transaction in a block.

    func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
       fmt.Println("ex02 Invoke")
       function, args := stub.GetFunctionAndParameters()
       if function == "invoke" {
          // Make payment of X units from A to B
          return t.invoke(stub, args)
       } else if function == "delete" {
          // Deletes an entity from its state
          return t.delete(stub, args)
       } else if function == "query" {
          // the old "Query" is now implemtned in invoke
          return t.query(stub, args)
       }
    
       return shim.Error("Invalid invoke function name. Expecting \"invoke\" \"delete\" \"query\"")
    }
    // Transaction makes payment of X units from A to B
    func (t *SimpleChaincode) invoke(stub shim.ChaincodeStubInterface, args []string) pb.Response {
       var A, B string    // Entities
       var Aval, Bval int // Asset holdings
       var X int          // Transaction value
       var err error
    
       if len(args) != 3 {
          return shim.Error("Incorrect number of arguments. Expecting 3")
       }
    
       A = args[0]
       B = args[1]
    
       // Get the state from the ledger
       // TODO: will be nice to have a GetAllState call to ledger
       Avalbytes, err := stub.GetState(A)
       if err != nil {
          return shim.Error("Failed to get state")
       }
       if Avalbytes == nil {
          return shim.Error("Entity not found")
       }
       Aval, _ = strconv.Atoi(string(Avalbytes))
    
       Bvalbytes, err := stub.GetState(B)
       if err != nil {
          return shim.Error("Failed to get state")
       }
       if Bvalbytes == nil {
          return shim.Error("Entity not found")
       }
       Bval, _ = strconv.Atoi(string(Bvalbytes))
    
       // Perform the execution
       X, err = strconv.Atoi(args[2])
       if err != nil {
          return shim.Error("Invalid transaction amount, expecting a integer value")
       }
       Aval = Aval - X
       Bval = Bval + X
       fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)
    
       // Write the state back to the ledger
       err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
       if err != nil {
          return shim.Error(err.Error())
       }
    
       err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
       if err != nil {
          return shim.Error(err.Error())
       }
    
       return shim.Success(nil)
    }
    
    // Deletes an entity from state
    func (t *SimpleChaincode) delete(stub shim.ChaincodeStubInterface, args []string) pb.Response {
       if len(args) != 1 {
          return shim.Error("Incorrect number of arguments. Expecting 1")
       }
    
       A := args[0]
    
       // Delete the key from the state in ledger
       err := stub.DelState(A)
       if err != nil {
          return shim.Error("Failed to delete state")
       }
    
       return shim.Success(nil)
    }
    // query callback representing the query of a chaincode
    func (t *SimpleChaincode) query(stub shim.ChaincodeStubInterface, args []string) pb.Response {
       var A string // Entities
       var err error
    
       if len(args) != 1 {
          return shim.Error("Incorrect number of arguments. Expecting name of the person to query")
       }
    
       A = args[0]
    
       // Get the state from the ledger
       Avalbytes, err := stub.GetState(A)
       if err != nil {
          jsonResp := "{\"Error\":\"Failed to get state for " + A + "\"}"
          return shim.Error(jsonResp)
       }
    
       if Avalbytes == nil {
          jsonResp := "{\"Error\":\"Nil amount for " + A + "\"}"
          return shim.Error(jsonResp)
       }
    
       jsonResp := "{\"Name\":\"" + A + "\",\"Amount\":\"" + string(Avalbytes) + "\"}"
       fmt.Printf("Query Response:%s\n", jsonResp)
       return shim.Success(Avalbytes)
    }

Did you find this page helpful?

Submit successfully!

Thank you for your feedback. Your feedback helps make our documentation better.

Failed to submit the feedback. Please try again later.

Which of the following issues have you encountered?







Please complete at least one feedback item.

Content most length 200 character

Content is empty.

OK Cancel