Hyperledger Fabric Chaincode Examples: Notarization, Asset Transfer, Digital Currency, Diploma Verification, Energy Sharing, and Logistics
This article presents a series of Hyperledger Fabric chaincode examples written in Go, covering information notarization, asset trading, digital currency issuance, diploma verification, community energy sharing, and logistics supply chain, each with functional descriptions, key functions, data models, and REST‑API interaction details.
Chaincode Example 1: Information Notarization
Overview
The Go file chaincode_example01.go implements a simple key‑value store that can be initialized, read, and modified on the ledger.
Main Functions
read : read the value of a given key.
write : create or modify a key’s value.
init : initialize the key hello_world .
invoke : dispatch to init or write based on arguments.
query : call read to retrieve a value.
Execution Flow
The main function starts the chaincode by calling shim.Start . The three core functions init , invoke , and query use stub.PutState and stub.GetState to interact with the ledger.
REST API Interaction
Deployment and invocation are performed via JSON‑RPC requests. Example deployment payload:
{
"jsonrpc": "2.0",
"method": "deploy",
"params": {
"type": 1,
"chaincodeID": {"path": "https://github.com/ibm-blockchain/learn-chaincode/finished"},
"ctorMsg": {"function": "init", "args": ["hi there"]},
"secureContext": "jim"
},
"id": 1
}Invocation payload example:
{
"jsonrpc": "2.0",
"method": "invoke",
"params": {
"type": 1,
"chaincodeID": {"name": "
chaincode‑hash
"},
"ctorMsg": {"function": "init", "args": ["swb"]},
"secureContext": "jim"
},
"id": 2
}Chaincode Example 2: Asset Trading
Overview
The Go file chaincode_example02.go demonstrates initializing two accounts (A and B), transferring assets between them, querying balances, and deleting accounts.
Main Functions
init : create accounts A and B with initial balances.
invoke : perform a transfer between A and B.
query : retrieve the balance of a specified account.
delete : remove an account.
Dependencies
import (
"errors"
"fmt"
"strconv"
"github.com/hyperledger/fabric/core/chaincode/shim"
)Conversion between strings and integers is handled by strconv . The transfer logic adjusts balances based on the sign of the amount.
Digital Currency Issuance and Management
Overview
This smart contract models a simple commercial scenario with three roles: a central bank, commercial banks, and enterprises. The central bank can issue currency, banks can receive allocations, and enterprises can transfer digital coins.
Main Functions
init : set up the central bank and initial supply.
invoke : route to internal functions.
query : read state data.
createBank , createCompany : add banks or enterprises.
issueCoin , issueCoinToBank , issueCoinToCp : issue or allocate coins.
transfer : move coins between enterprises.
Various get* functions to retrieve banks, companies, transactions, and individual records.
write* functions to persist updated entities.
Data Model
CenterBank: Name, TotalNumber, RestNumber, ID (fixed 0).
Bank: Name, TotalNumber, RestNumber, ID.
Company: Name, Number, ID.
Transaction: FromType, FromID, ToType, ToID, Time, Number, ID.
Diploma Certification
Overview
The contract enables a simple credential management system where schools issue diplomas to individuals, and verification agencies can query them. Records are immutable on the blockchain, and schools can update or revoke diplomas.
Data Model
School: Name, Location, Address, PublicKey, PrivateKey, StudentList.
Student: Name, Address, PastDiplomas.
DiplomaInfo: ID, School, StartYear, EndYear, Status (0‑graduated, 1‑dropped).
Record: ID, SchoolAddress, SchoolSignature, StudentAddress, Timestamp, Operation (0‑graduate, 1‑drop, 2‑enroll).
Key Functions
init , invoke , query .
updateDiploma : school updates a student’s diploma status.
enrollStudent : school adds a new student.
createSchool , createStudent : add new entities.
Various get* functions to retrieve schools, students, diplomas, and records.
write* functions to persist changes.
Community Energy Sharing
Overview
This contract models a micro‑grid where households can produce solar energy and trade excess electricity with neighbors using a blockchain‑based marketplace.
Data Model
Household: Address, RemainingEnergy, Balance, ID, Status (0‑inactive, 1‑active), PublicKey, PrivateKey.
Transaction: BuyerAddress, SellerAddress, EnergyAmount, AmountPaid, ID, Timestamp.
Key Functions
init , invoke , query .
createUser : register a new household.
buyByAddress : purchase energy from another household.
getTransactionById , getTransactions , getHomes , getHomeByAddress , changeStatus , writeUser , writeTransaction .
Logistics Supply Chain Simple Case
Overview
The contract implements a basic logistics application where a single logistics company, multiple senders, and multiple receivers interact to create, update, and finalize shipping orders on the blockchain.
Data Model
ExpressOrder: ID, SenderAddress, ReceiverAddress, SenderContact, ReceiverContact, Fee, FeePayType (0‑sender, 1‑receiver), PrepaidFee, DeliveryInfo, ReceiverSignature.
Sender / Receiver: Name, Address, AccountAddress, PublicKey, PrivateKey (receiver), Contact, Balance.
LogisticsCompany: Name, Address, Contact, PublicKey, PrivateKey, Balance, List of ExpressPoints.
ExpressPoint: Name, Location, Contact, PublicKey, PrivateKey, AccountAddress.
Key Functions
init , invoke , query .
createUser , createExpress , createExpressPoint , createExpressOrder , finishExpressOrder , addExpressPointer , updateExpressOrder .
Query functions: getExpressOrderById , getExpress , getUserByAddress , getExpressPointByAddress .
Write functions: writeExpress , writeExpressOrder , writeUser , writeExpressPoint .
REST API Examples
All operations are invoked via JSON‑RPC with method set to deploy , invoke , or query and appropriate ctorMsg arguments as shown in the earlier examples.
Architects Research Society
A daily treasure trove for architects, expanding your view and depth. We share enterprise, business, application, data, technology, and security architecture, discuss frameworks, planning, governance, standards, and implementation, and explore emerging styles such as microservices, event‑driven, micro‑frontend, big data, data warehousing, IoT, and AI architecture.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.