Blockchain Medium
Blockchain Medium
Open in app
10
Search
Get unlimited access to the best of Medium for less than $1/week. Become a member
If you do not wish to download all the fabric samples and set them up, you can use
managed blockchain networks provided by Amazon or any other tech giant,
however, you have to pay for their service. Follow along if you have your own
network or if you only need to learn about blockchains; otherwise, set up the test
network and come back.
Our Requirement
https://medium.com/impelsys/certificate-credentialing-service-writing-chaincode-blog-2-6c94d0c2cf6b 1/21
4/23/25, 9:49 PM Certificate Credentialing Service, Writing Chaincode: Blog 2 | by Muhammed Musthafa Shahal V | Impelsys | Medium
To write a chaincode that can create a certificate, store it in the ledger, retrieve
certificate details upon providing the certificate number, and display all certificates
in the ledger.
Firstly, start by importing the fabric contract API. Use the code shown below. Also,
use the “contract API” or “fabric shim” API; both of these APIs are critical
components that provide a bridge between the system chaincode and the
underlying Hyperledger Fabric platform.
'use strict';
Next, create a class called FabCar and export it, refer to the below code. If required
change the class name but you have to change the test network configuration and
the chaincode SDK as well. As I’m using the test network provided by the
Hyperledger Foundation, I’m keeping the same name, and changing the entire
name is out the of scope of this blog.
module.exports = FabCar;
https://medium.com/impelsys/certificate-credentialing-service-writing-chaincode-blog-2-6c94d0c2cf6b 2/21
4/23/25, 9:49 PM Certificate Credentialing Service, Writing Chaincode: Blog 2 | by Muhammed Musthafa Shahal V | Impelsys | Medium
Now create the chaincode functions as per our business requirements and create 4
functions inside the Fabcar Class in the same order.
1. Init Function
Init Function
As a first step, we will proceed with the Init function. If necessary, you can leave the
Init function empty. When the opportunity arises for Chaincode deployment, this
method will be executed automatically to ensure successful deployment. It is a good
practice to keep some code or initialize some values in the Init method to determine
if the deployment has been successful or not.
To write data into the ledger, you can use the “putState” method. This method will
update the ledger and write the key-value pair into it.
In this case, I will assign a dummy certificate value as the initial value.
async initLedger(ctx) {
console.info('============= START : Initialize Ledger ===========');
const certificate =
{
"name": "Blackacre",
"email": "[email protected]",
"course": "BLS Provider",
"orgCode": "TC0101",
"courseCode": "2022-1234",
"completionDate": "10-10-2023",
"expiryDate": "10-10-2025"
}
const key ="CERT123";
await ctx.stub.putState(key, Buffer.from(JSON.stringify(certificate)));
console.info('Added <--> ', certificate);
console.info('============= END : Initialize Ledger ===========');
}
https://medium.com/impelsys/certificate-credentialing-service-writing-chaincode-blog-2-6c94d0c2cf6b 3/21
4/23/25, 9:49 PM Certificate Credentialing Service, Writing Chaincode: Blog 2 | by Muhammed Musthafa Shahal V | Impelsys | Medium
Next, write the Create Certificate Function which accepts the certificate number
and the certificate details as parameters.
const certificateData = {
name,
email,
course,
orgCode,
courseCode,
completionDate,
expiryDate,
};
https://medium.com/impelsys/certificate-credentialing-service-writing-chaincode-blog-2-6c94d0c2cf6b 4/21
4/23/25, 9:49 PM Certificate Credentialing Service, Writing Chaincode: Blog 2 | by Muhammed Musthafa Shahal V | Impelsys | Medium
Finally, use the Query All Certificates Function. This function does not accept any
parameters but will return all the certificate information available in the database.
async queryAllCertificates(ctx) {
const startKey = '';
const endKey = '';
const allResults = [];
for await (const {key, value} of ctx.stub.getStateByRange(startKey, end
const strValue = Buffer.from(value).toString('utf8');
let record;
try {
record = JSON.parse(strValue);
} catch (err) {
console.log(err);
record = strValue;
}
allResults.push({ Key: key, Record: record });
}
console.info(allResults);
return JSON.stringify(allResults);
}
'use strict';
const {
Contract
} = require('fabric-contract-api');
const certificateData = {
name,
email,
course,
orgCode,
courseCode,
completionDate,
expiryDate,
};
async queryAllCertificates(ctx) {
const startKey = '';
const endKey = '';
const allResults = [];
for await (const {
key,
value
}
of ctx.stub.getStateByRange(startKey, endKey)) {
const strValue = Buffer.from(value).toString('utf8');
let record;
try {
record = JSON.parse(strValue);
} catch (err) {
console.log(err);
record = strValue;
}
allResults.push({
Key: key,
Record: record
});
}
console.info(allResults);
return JSON.stringify(allResults);
https://medium.com/impelsys/certificate-credentialing-service-writing-chaincode-blog-2-6c94d0c2cf6b 6/21
4/23/25, 9:49 PM Certificate Credentialing Service, Writing Chaincode: Blog 2 | by Muhammed Musthafa Shahal V | Impelsys | Medium
}
}
module.exports = FabCar;
The script will deploy the Go version of chaincode by default if you did not mention
javascript. If you would like to use any other programming language, please indicate
it.
The “startFabric.sh” script will start the network and deploy our chaincode. It will
create two organizations and one peer for each. Then it will create a test channel,
package our chaincode, and deploy it. Refer to the below Chain code. It provides the
channel name, chaincode name, chaincode language, etc.
After packaging the chaincode, it will wait for approval from each peer in the
network. Once it’s approved, it will deploy the chaincode.
https://medium.com/impelsys/certificate-credentialing-service-writing-chaincode-blog-2-6c94d0c2cf6b 7/21
4/23/25, 9:49 PM Certificate Credentialing Service, Writing Chaincode: Blog 2 | by Muhammed Musthafa Shahal V | Impelsys | Medium
fabric-samples/fabcar$ docker ps
The test network by default uses the Couchdb as the ledger in the BlockChain. In
the containers list, you can see two instances of the CouchDB database created by
the Fabric test network for each organization on PORTs 5984 and 7984, respectively.
To confirm your chaincode is successfully deployed head-over to any of the
Couchdb database ports mentioned, use the result provided by the “docker ps”
command.
https://medium.com/impelsys/certificate-credentialing-service-writing-chaincode-blog-2-6c94d0c2cf6b 8/21
4/23/25, 9:49 PM Certificate Credentialing Service, Writing Chaincode: Blog 2 | by Muhammed Musthafa Shahal V | Impelsys | Medium
I’m using the first instance of Couchdb running on port 5984. Head over to
“http://localhost:5984/_utils” and login using the default username “admin” and
password “adminpw”.
Go inside “my channel” fabcar ledger. This is the ledger created by the network for
us. Inside that, you can see “CERT123.” Click on it, and then you will be able to see
the entire certificate details that we mentioned in the chaincode Init Function. This
indicates that our chaincode was successfully deployed and the certificate was
added to the ledger.
https://medium.com/impelsys/certificate-credentialing-service-writing-chaincode-blog-2-6c94d0c2cf6b 9/21
4/23/25, 9:49 PM Certificate Credentialing Service, Writing Chaincode: Blog 2 | by Muhammed Musthafa Shahal V | Impelsys | Medium
After successfully deploying our chaincode, it is now time to invoke it and execute
transactions. Rather than writing the code on the command line for executing
transactions, Hyperledger Fabric provides SDKs for each programming language for
automating transaction execution. First, we will create an admin user, and then,
utilizing the admin user, we will create an end user to interact with the chaincode.
1. Create an Admin user for getting access to the network
Head over to “fabric-samples/fabcar/javascript/” and run “npm install” to install the
dependencies.
https://medium.com/impelsys/certificate-credentialing-service-writing-chaincode-blog-2-6c94d0c2cf6b 10/21
4/23/25, 9:49 PM Certificate Credentialing Service, Writing Chaincode: Blog 2 | by Muhammed Musthafa Shahal V | Impelsys | Medium
Once done, save the file and run the “invoke.js” file to submit the transaction to the
blockchain. It will sum up the transaction. When the transaction has been
endorsed, you will receive the following response.
Once the transaction has been submitted, you will be able to view the newly created
certificate when you refresh the Couchdb website.
https://medium.com/impelsys/certificate-credentialing-service-writing-chaincode-blog-2-6c94d0c2cf6b 11/21
4/23/25, 9:49 PM Certificate Credentialing Service, Writing Chaincode: Blog 2 | by Muhammed Musthafa Shahal V | Impelsys | Medium
Save the file and run it using “node query.js”. All the certificates will be printed on
the console.
https://medium.com/impelsys/certificate-credentialing-service-writing-chaincode-blog-2-6c94d0c2cf6b 12/21
4/23/25, 9:49 PM Certificate Credentialing Service, Writing Chaincode: Blog 2 | by Muhammed Musthafa Shahal V | Impelsys | Medium
Save the file and run it using “node query.js”. If the certificate is present with the
key you provided you will see the following response.
If the certificate does not exist with the key you provided, you will get an error
message showing that the “key does not exist”.
Conclusion:
We have successfully written our first chaincode and deployed it to our test network.
Happy Coding, and Good Luck.
Follow
https://medium.com/impelsys/certificate-credentialing-service-writing-chaincode-blog-2-6c94d0c2cf6b 13/21
4/23/25, 9:49 PM Certificate Credentialing Service, Writing Chaincode: Blog 2 | by Muhammed Musthafa Shahal V | Impelsys | Medium
Published in Impelsys
30 Followers · Last published Apr 3, 2025
Impelsys is a global leader in delivering impactful, engaging & adaptable online learning solutions for global
publishers, education providers, & enterprises.
Edit profile
No responses yet
https://medium.com/impelsys/certificate-credentialing-service-writing-chaincode-blog-2-6c94d0c2cf6b 14/21