Hyperledger Fabric sample Decentralized Energy on IBM Blockchain Platform 2.0
This code pattern demonstrates setting up a network on the IBM Blockchain Platform 2.0 and deploying the Decentralized smart contract on the network. Next, we generate client side certificates so the developer can subsequently enroll an application identity and then submit transactions on the smart contract. The application is setup with a Node.js server using the Fabric Node SDK to process requests to the network.
A key application of Blockchain being currently explored is a Decentralized Energy network. The idea stems from a neighborhood where certain Residents are producing energy through Solar panels or other means, and can sell excess energy to Residents needing energy. The transactions would be based on coins in each Resident's account. As per a pre-determined contract and rate, the coins would be debited from the consumer and credited to the producer, for a certain billing period. Each transaction would need to be atomic and added to a Blockchain ledger for trust and verification. The network can include Banks to transact coins for Fiat currency (USD). The network can have Utility Company who can buy or provide energy through the network.
The network consists of Residents, Banks and Utility Companies. Residents can exchange coins for energy among each other. The application assumes a pre-paid system where transactions occur after the energy is consumed and the values are updated. The Resident can exchange coins for Fiat money (USD) with Banks on the network. The Residents can also transact coins for energy with a Utility company on the network.
The code pattern demonstrates how a Node.js smart contract can be packaged using the IBM Blockchain Platform Extension for VS Code. Then, using the extension, you can set up a local instance of the Hyperledger Fabric network, on which you can install and instantiate the contract. Lastly, the application is setup with a Node.js server using the Fabric Node SDK to process transactions that communicate with the network.
When you have completed this code pattern, you will understand how to:
- Package the smart contract using IBM Blockchain Platform Extension for VS Code
- Setup a Hyperledger Fabric network on IBM Blockchain Platform 2.0
- Install and instantiate smart contract package onto the IBM Blockchain Platform 2.0
- Develop a Node.js server with the Hyperledger Fabric SDK to interact with the deployed network
- Interact with the contract and execute transactions using the SDK.
- The developer uses the IBM Blockchain Platform Extension for VS Code to package the Decentralized Energy smart contract.
- Launch the IBM Blockchain Platform 2.0 and Kubernetes Services on the IBM Cloud.
- Install chaincode on the peer node.
- Instantiate the chaincode on the peer node.
- Execute the decentralized energy smart contract transactions from a node.js application.
- IBM Blockchain Platform 2.0 gives you total control of your blockchain network with a user interface that can simplify and accelerate your journey to deploy and manage blockchain components on the IBM Cloud Kubernetes Service.
- IBM Cloud Kubernetes Service gcreates a cluster of compute hosts and deploys highly available containers. A Kubernetes cluster lets you securely manage the resources that you need to quickly deploy, update, and scale applications.
- IBM Blockchain Platform Extension for VS Code is designed to assist users in developing, testing, and deploying smart contracts -- including connecting to Hyperledger Fabric environments.
- Hyperledger Fabric v1.4 is a platform for distributed ledger solutions, underpinned by a modular architecture that delivers high degrees of confidentiality, resiliency, flexibility, and scalability.
- Node.js is an open source, cross-platform JavaScript run-time environment that executes server-side JavaScript code.
- IBM Cloud account
- Node v8.x or greater and npm v5.x or greater
- VSCode version 1.26 or greater
- IBM Blockchain Platform Extension for VSCode
Follow these steps to set up and run this code pattern. The steps are described in detail below.
- Clone the repo
- Package the smart contract
- Create IBM Cloud services
- Build a network
- Deploy Decentralized Energy Smart Contract on the network
- Connect application to the network
- Run the application
Clone this repository in a folder your choice:
git clone https://github.com/IBM/decentralized-energy-fabric-IBP20.git
We will use the IBM Blockchain Platform extension to package the smart contract.
-
Open Visual Studio code and open the
contract
folder from Decentralized Energy repository that was cloned earlier. -
Press the
F1
key to see the different VS code options. ChooseIBM Blockchain Platform: Package a Smart Contract Project
.
- Click the
IBM Blockchain Platform
extension button on the left. This will show the packaged contracts on top and the blockchain connections on the bottom.
-
Next, right click on the packaged contract (in this case, select [email protected]) to export it and choose
Export Package
. -
Choose a location on your machine and save
.cds
file. We will use this packages smart contract later to deploy on the IBM Blockchain Platform 2.0 service.
Now, we will start creating our Hyperledger Fabric network on the IBM Cloud.
- Create the IBM Cloud Kubernetes Service. You can find the service in the
Catalog
. For this code pattern, we can use theFree
cluster, and give it a name. Note, that the IBM Cloud allows one instance of a free cluster and expires after 30 days.
- Create the IBM Blockchain Platform 2.0 service on the IBM Cloud. You can find the service in the
Catalog
, and give a name.
- After your kubernetes cluster is up and running, you can deploy your IBM Blockchain Platform on the cluster. The service walks through few steps and finds your cluster on the IBM Cloud to deploy the service on.
- Once the Blockchain Platform is deployed on the Kubernetes cluster, you can launch the console to start operating on your blockchain network.
We will build a network as provided by the IBM Blockchain Platform documentation. This will include creating a channel with a single peer organization with its own MSP and CA (Certificate Authority), and an orderer organization with its own MSP and CA. We will create the respective identities to deploy peers and operate nodes.
-
- Click Add Certificate Authority.
- Click IBM Cloud under Create Certificate Authority and Next.
- Give it a Display name of
Org1 CA
. - Specify an Admin ID of
admin
and Admin Secret ofadminpw
.
-
- Select the Org 1 CA Certificate Authority that we created.
- First, we will register an admin for our organization "org1". Click on the Register User button. Give an Enroll ID of
org1admin
, and Enroll Secret oforg1adminpw
. Click Next. Set the Type for this identity asclient
and select from any of the affiliated organizations from the drop-down list. We will leave the Maximum enrollments and Add Attributes fields blank. - We will repeat the process to create an identity of the peer. Click on the Register User button. Give an Enroll ID of
peer1
, and Enroll Secret ofpeer1pw
. Click Next. Set the Type for this identity aspeer
and select from any of the affiliated organizations from the drop-down list. We will leave the Maximum enrollments and Add Attributes fields blank.
-
- Navigate to the Organizations tab in the left navigation and click Create MSP definition.
- Enter the MSP Display name as
Org1 MSP
and an MSP ID oforg1msp
. - Under Root Certificate Authority details, specify the peer CA that we created
Org1 CA
as the root CA for the organization. - Give the Enroll ID and Enroll secret for your organization admin,
org1admin
andorg1adminpw
. Then, give the Identity name,Org1 Admin
. - Click the Generate button to enroll this identity as the admin of your organization and export the identity to the wallet. Click Export to export the admin certificates to your file system. Finally click Create MSP definition.
- Create a peer
- On the Nodes page, click Add peer.
- Click IBM Cloud under Create a new peer and Next.
- Give your peer a Display name of
Peer Org1
. - On the next screen, select
Org1 CA
as your Certificate Authority. Then, give the Enroll ID and Enroll secret for the peer identity that you created for your peer,peer1
, andpeer1pw
. Then, select the Administrator Certificate (from MSP),Org1 MSP
, from the drop-down list and click Next. - Give the TLS Enroll ID,
admin
, and TLS Enroll secret,adminpw
, the same values are the Enroll ID and Enroll secret that you gave when creating the CA. Leave the TLS CSR hostname blank. - The last side panel will ask you to Associate an identity and make it the admin of your peer. Select your peer admin identity
Org1 Admin
. - Review the summary and click Submit.
-
- Click Add Certificate Authority.
- Click IBM Cloud under Create Certificate Authority and Next.
- Give it a unique Display name of
Orderer CA
. - Specify an Admin ID of
admin
and Admin Secret ofadminpw
.
-
- In the Nodes tab, select the Orderer CA Certificate Authority that we created.
- First, we will register an admin for our organization. Click on the Register User button. Give an Enroll ID of
ordereradmin
, and Enroll Secret ofordereradminpw
. Click Next. Set the Type for this identity asclient
and select from any of the affiliated organizations from the drop-down list. We will leave the Maximum enrollments and Add Attributes fields blank. - We will repeat the process to create an identity of the orderer. Click on the Register User button. Give an Enroll ID of
orderer1
, and Enroll Secret oforderer1pw
. Click Next. Set the Type for this identity aspeer
and select from any of the affiliated organizations from the drop-down list. We will leave the Maximum enrollments and Add Attributes fields blank.
-
- Navigate to the Organizations tab in the left navigation and click Create MSP definition.
- Enter the MSP Display name as
Orderer MSP
and an MSP ID oforderermsp
. - Under Root Certificate Authority details, specify the peer CA that we created
Orderer CA
as the root CA for the organization. - Give the Enroll ID and Enroll secret for your organization admin,
ordereradmin
andordereradminpw
. Then, give the Identity name,Orderer Admin
. - Click the Generate button to enroll this identity as the admin of your organization and export the identity to the wallet. Click Export to export the admin certificates to your file system. Finally click Create MSP definition.
-
- On the Nodes page, click Add orderer.
- Click IBM Cloud and proceed with Next.
- Give your peer a Display name of
Orderer
. - On the next screen, select
Orderer CA
as your Certificate Authority. Then, give the Enroll ID and Enroll secret for the peer identity that you created for your orderer,orderer1
, andorderer1pw
. Then, select the Administrator Certificate (from MSP),Orderer MSP
, from the drop-down list and click Next. - Give the TLS Enroll ID,
admin
, and TLS Enroll secret,adminpw
, the same values are the Enroll ID and Enroll secret that you gave when creating the CA. Leave the TLS CSR hostname blank. - The last side panel will ask to Associate an identity and make it the admin of your peer. Select your peer admin identity
Orderer Admin
. - Review the summary and click Submit.
-
- Navigate to the Nodes tab, and click on the Orderer that we created.
- Under Consortium Members, click Add organization.
- From the drop-down list, select
Org1 MSP
, as this is the MSP that represents the peer's organization org1. - Click Submit.
-
- Navigate to the Channels tab in the left navigation.
- Click Create channel.
- Give the channel a name,
mychannel
. - Select the orderer you created,
Orderer
from the orderers drop-down list. - Select the MSP identifying the organization of the channel creator from the drop-down list. This should be
Org1 MSP (org1msp)
. - Associate available identity as
Org1 Admin
. - Click Add next to your organization. Make your organization an Operator.
- Click Create.
-
- Click Join channel to launch the side panels.
- Select your
Orderer
and click Next. - Enter the name of the channel you just created.
mychannel
and click Next. - Select which peers you want to join the channel, click
Peer Org1
. - Click Submit.
-
- Click the Smart contracts tab to install the smart contract.
- Click Install smart contract to upload the Decentralized smart contract package file, which you packaged earlier using the Visual Studio code extension.
- Click on Add file and find your packaged smart contract.
- Once the contract is uploaded, click Install.
-
- On the smart contracts tab, find the smart contract from the list installed on your peers and click Instantiate from the overflow menu on the right side of the row.
- On the side panel that opens, select the channel,
mychannel
to instantiate the smart contract on. Click Next. - Select the organization members to be included in the policy,
org1msp
. Click Next. - Give Function name of
instantiate
and leave Arguments blank. Note:instantiate
is the method in themy-contract.js
file that initiates the smart contracts on the peer. Some may name thisinitLedger
. - Click Instantiate.
-
- Under the Instantiated Smart Contract, click on
Connect with SDK
from the overflow menu on the right side of the row. - Choose from the dropdown for MSP for connection,
org1msp
. - Choose from Certificate Authority dropdown,
Org1 CA
. - Download the connection profile by scrolling down and clicking Download Connection Profile. This will download the connection json which we will use soon to establish connection.
- You can click Close once the download completes.
- Under the Instantiated Smart Contract, click on
-
- Go to the Nodes tab on the left bar, and under Certif Authorities, choose your organization CA, Org1 CA.
- Click on Register user.
- Give an Enroll ID and Enroll Secret to administer your application users,
app-admin
andapp-adminpw
. - Choose
client
as Type and any organization for affiliation. We can pickorg1
to be consistent. - You can leave the Maximum enrollments blank.
- Under Attributes, click on Add attribute. Give attribute as
hf.Registrar.Roles
=*
. This will allow this identity to act as registrar and issues identities for our app. Click Add-attribute. - Click Register.
-
- Copy the connection profile you downloaded into server folder and application folder
- Update the config.json file with:
- The connection json file name you downloaded.
- The enroll id and enroll secret for your app admin, which we earlier provided as
app-admin
andapp-adminpw
. - The orgMSP ID, which we provided as
org1msp
. - The caName, which can be found in your connection json file under "organization" -> "org1msp" -> certificateAuthorities". This would be like an IP address and a port.
- The username you would like to register.
- Update gateway discovery to
{ enabled: true, asLocalhost: false }
to connect to IBP.
{
"connection_file": "mychannel_decentralizedenergy_profile.json",
"channel_name": "mychannel",
"smart_contract_name": "decentralizedenergy",
"appAdmin": "app-admin",
"appAdminSecret": "app-adminpw",
"orgMSPID": "org1msp",
"caName": "169.46.208.151:30404",
"userName": "user1",
"gatewayDiscovery": { "enabled": true, "asLocalhost": false }
}
-
-
First, navigate to the
web-app
directory, and install the node dependencies.cd web-app/server npm install
-
Run the
enrollAdmin.js
scriptnode enrollAdmin.js
-
You should see the following in the terminal:
msg: Successfully enrolled admin user app-admin and imported it into the wallet
-
-
-
From the
server
directory, start the server.npm start
-
-
-
In a new terminal, open the web client folder and install the dependencies.
cd web-app/angular-app npm install
-
Start the client:
npm start
-
You can find the app running at http://localhost:4200/
You can go to the IBM Blockchain Platform v2 console to monitor your network and get information on your channel.
-
Navigate to the
application
directory, and install the node dependencies.cd application npm install
-
Run the
enrollAdmin.js
scriptnode enrollAdmin.js
You should see the following in the terminal:
msg: Successfully enrolled admin user app-admin and imported it into the wallet
-
Now lets register each of our participants. We will register
R1
as resident,B1
as bank,U1
as utility company. Navigate toadd-participants
folder and register the resident identity:cd add-participants node registerResident.js
You should see the following in the terminal:
Successfully registered and enrolled user "R1" and imported it into the wallet
Similarly register bank and utility company on the network.
node registerBank.js
node registerUtilityCompany.js
-
Now add the participants on the state. The contract stores the id of the identity creating the participant as their
participantId
. Lets add our resident:node addResident.js
You should see the following in the terminal:
2019-02-27T06:38:29.252Z - info: [TransactionEventHandler]: _strategySuccess: strategy success for transaction "c092df4098775057a7b712db402e45f3c8420d98fc022dfc331accb580448d4a" ...
Similarly add bank and utility company on the network.
node addBank.js
node addUtilityCompany.js
-
Now lets perform the
EnergyTrade
andCashTrade
transactions. These transactions will verify the sender's id, as the id on the world state before updating the state. In our case that is our resident R1:cd ../invoker-tx/ node energy-trade.js
You should see the following in the terminal followed by updated state of the resident and utility company:
2019-02-27T06:38:29.252Z - info: [TransactionEventHandler]: _strategySuccess: strategy success for transaction "c092df4098775057a7b712db402e45f3c8420d98fc022dfc331accb580448d4a" ...
Similarly, lets do the
CashTrade
transaction between resident and bank.node cash-trade.js
You should see the following in the terminal followed by updated state of the resident and the bank:
2019-02-27T06:38:29.252Z - info: [TransactionEventHandler]: _strategySuccess: strategy success for transaction "c092df4098775057a7b712db402e45f3c8420d98fc022dfc331accb580448d4a" ...
-
If you receive the following error on submitting transaction:
error: [Client.js]: Channel not found for name mychannel
It is safe to ignore this error because the ibp2.0 beta has service discovery enabled. (In order to use service discovery to find other peers please define anchor peers for your channel in the ui). If you really want the message to go away you can add the channels section to the connection profile, but it is a warning rather than a true error telling the user the channel is found but not in the connection profile
As an example you can manually add the following json and updated the IP address and ports manually:
"channels": { "mychannel": { "orderers": [ "169.46.208.151:32078" ], "peers": { "169.46.208.151:31017": {} } } },
This code pattern is licensed under the Apache Software License, Version 2. Separate third-party code objects invoked within this code pattern are licensed by their respective providers pursuant to their own separate licenses. Contributions are subject to the Developer Certificate of Origin, Version 1.1 (DCO) and the Apache Software License, Version 2.