What is chaincode?


What is chaincode?

Chaincode is a piece of code that is deployed into a network of Hyperledger fabric peer nodes that enables interaction with that network's shared ledger.

In other words, Chaincode (can be called smart contract), is essentially the business logic that governs how the different entities or parties in a blockchain network interact or transact with each other. 

Sample Chaincode.

package main

import "fmt"
import "github.com/hyperledger/fabric/core/chaincode/shim"

// The SampleChaincode is the struct that is required to implement the shim.Chaincode interface, which has three methods — Init, Query, and Invoke — for it to be considered a valid Chaincode type by the shim package.
type SampleChaincode struct {
}

// The Init method is called when the chaincode is first deployed onto the blockchain network and will be executed by each peer that deploys its own instance of the chaincode. This method can be used for any tasks related to initialization, bootstrapping, or setup.
func (t *SampleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
   return nil, nil
}

// The Query method is invoked whenever any read/get/query operation needs to be performed on the blockchain state. Depending upon the complexity of the chaincode, this method can hold your read/get/query logic, or it could be outsourced to separate methods that can be invoked from within the Query method. The Query method is not intended to change the state of the underlying blockchain, and hence does not run within a transactional context. Also, because this method is only for reading the state of the blockchain, its invocations are not recorded on the blockchain.
func (t *SampleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
   return nil, nil
}

// The Invoke method is invoked whenever the state of the blockchain is to be modified. Simply put, all create, update, and delete operations should be encapsulated within the Invoke method. Because this method will modify the state of the blockchain, the blockchain Fabric code will automatically create a transaction context inside which this method will get executed. All invocations of this method are recorded on the blockchain as transactions, which ultimately get written into blocks.
func (t *SampleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {    return nil, nil
}

// The starting point for any Go program is the main function, and hence it's used for bootstrapping starting the chaincode. When the peer deploys its instance of the chaincode, the main function gets executed.
func main() {
   err := shim.Start(new(SampleChaincode))
   if err != nil {
      fmt.Println("Could not start SampleChaincode")
   } else {
      fmt.Println("SampleChaincode successfully started")
   }
}

No comments:

Post a Comment