Hyperledger Fabric Chaincode and Network Setup: Asset Transfer Example, Test Network and Client Calls
What Is Chaincode?
Chaincode is the program that defines assets and the rules to change them. It reads and writes the world state through a stub. Fabric supports Go, Java and JavaScript or TypeScript.
A Small Go Example (Idea)
go
package main
import (
"encoding/json"
"fmt"
"github.com/hyperledger/fabric-contract-api-go/v2/contractapi"
)
type Asset struct {
ID string `json:"ID"`
Color string `json:"color"`
Owner string `json:"owner"`
Value int `json:"value"`
}
type AssetContract struct {
contractapi.Contract
}
func (c *AssetContract) CreateAsset(ctx contractapi.TransactionContextInterface, id, color, owner string, value int) error {
exists, err := c.AssetExists(ctx, id)
if err != nil {
return err
}
if exists {
return fmt.Errorf("asset %s already exists", id)
}
asset := Asset{ID: id, Color: color, Owner: owner, Value: value}
data, _ := json.Marshal(asset)
return ctx.GetStub().PutState(id, data)
}
func (c *AssetContract) ReadAsset(ctx contractapi.TransactionContextInterface, id string) (*Asset, error) {
data, err := ctx.GetStub().GetState(id)
if err != nil {
return nil, err
}
if data == nil {
return nil, fmt.Errorf("asset %s does not exist", id)
}
var asset Asset
if err := json.Unmarshal(data, &asset); err != nil {
return nil, err
}
return &asset, nil
}
func (c *AssetContract) AssetExists(ctx contractapi.TransactionContextInterface, id string) (bool, error) {
data, err := ctx.GetStub().GetState(id)
return data != nil, err
}
func main() {
cc, err := contractapi.NewChaincode(&AssetContract{})
if err != nil {
panic(err)
}
if err := cc.Start(); err != nil {
panic(err)
}
}
PutState writes a key and value to the ledger
GetState reads the current value
- Returning an error rejects the transaction
- Chaincode must be deterministic: no random numbers or local time
Sample code This is a teaching sketch. Always start from the official asset-transfer-basic sample in the fabric-samples repository, which matches the Fabric version you install.
Run the Test Network
You need Docker, Docker Compose, Git, Go and Node installed. Use the official fabric-samples repository and its install script.
bash
git clone https://github.com/hyperledger/fabric-samples.git
cd fabric-samples
curl -sSLO https://raw.githubusercontent.com/hyperledger/fabric/main/scripts/install-fabric.sh && chmod +x install-fabric.sh
./install-fabric.sh docker samples binary
cd test-network
./network.sh up createChannel -c mychannel -ca
./network.sh deployCC -ccn basic -ccp ../asset-transfer-basic/chaincode-go -ccl go
Check the docs Script options change between releases. Follow the Using the Fabric test network page of the documentation for your version.
Invoke and Query With the Peer CLI
After setting the environment variables shown in the official tutorial for Org1:
bash
peer chaincode query -C mychannel -n basic -c '{"Args":["GetAllAssets"]}'
peer chaincode invoke -C mychannel -n basic -c '{"function":"TransferAsset","Args":["asset1","Asha"]}' \
--orderer localhost:7050 --ordererTLSHostnameOverride orderer.example.com \
--tls --cafile "$ORDERER_CA"
- Query reads from one peer only and does not create a transaction
- Invoke goes through endorsement, ordering and validation
Shutdown
bash
./network.sh dow
Practice
- List the assets and transfer one
- Why must chaincode be deterministic?
- What is the difference between query and invoke?
Conclusion
Chaincode defines assets and rules using PutState and GetState. The Fabric test network lets you deploy, invoke and query a sample on your own machine.
Quick Summary: chaincode; Go example; test network; CLI; shutdown.