Hyperledger Fabric Tutorials | Chaincode Interface – ChaincodeStubInterface

Hyperledger Fabric Tutorials | Chaincode Interface – ChaincodeStubInterface

Chaincode is one of the most important part of Hyperledger Fabric Blockchain. In this post, we will explain about Chaincode API's which is ChaincodeStub and ChaincodeStubInterface.

 

What is Chaincode ?

Chaincode is the "smart contract" that runs on the peers and creates transactions. Chaincode implements a business logic agreed upon by participants of the blockchain network. Client application use Chaincode to interact with ledger where they query and update the ledger and generates a transaction proposal.

 

What is Chaincode Interface ?

Chaincode interface must be implemented by all chaincodes. Below is the syntax of that. As you can see there are two functions defined one is Init and other is Invoke so every chaincode need to implement these functions.

type Chaincode interface {
	// Init is called during Instantiate transaction after the chaincode container
	// has been established for the first time, allowing the chaincode to
	// initialize its internal data
	Init(stub ChaincodeStubInterface) pb.Response

	// Invoke is called to update or query the ledger in a proposal transaction.
	// Updated state variables are not committed to the ledger until the
	// transaction is committed.
	Invoke(stub ChaincodeStubInterface) pb.Response
}

 

  • Init
    Called when a chaincode receives an instantiate or upgrade transaction. This is where you will initialize any application state.
  • Invoke
    Called when the invoke transaction is received to process any transaction proposals.

 

As you see in above example, both these functions are using ChaincodeStubInterface as input parameter so let's understand that.

 

What is ChaincodeStubInterface ?

ChaincodeStubInterface provides the functions that are used to access and modify the ledger, and to make invocations between chaincodes. Below is short syntax of that.

As you see in below functions, there are many functions available that you can use in your chaincode to interact with level or counchDB and for other purposes.

 

type ChaincodeStubInterface interface {
	GetArgs() [][]byte
	GetStringArgs() []string
	GetFunctionAndParameters() (string, []string)
	GetArgsSlice() ([]byte, error)
	GetTxID() string
	GetChannelID() string
	InvokeChaincode(chaincodeName string, args [][]byte, channel string) pb.Response
	GetState(key string) ([]byte, error)
	PutState(key string, value []byte) error
	DelState(key string) error
	GetStateValidationParameter(key string) ([]byte, error)
	GetStateByRange(startKey, endKey string) (StateQueryIteratorInterface, error)
        --------
}

No Comments

Post a Reply

Inquire Now
close slider