How to create a backend in NodeJS for Hyperledger Fabric 🤖➡⛓

Written by waltermontes | Published 2018/12/31
Tech Story Tags: blockchain | hyperledger | nodejs | convector | javascript

TLDRvia the TL;DR App

Start your 2019 journey learning the right skills to become a Blockchain programmer with this tutorial on how to create a backend for Hyperledger Fabric.

2018 was a great year for Blockchain in the enterprise, one of my favorites projects is Fabric, from the Hyperledger Project.

Fabric is a framework to create permissioned Blockchain/DLT networks. It provides the tools to install and configure the protocol which on top of it can host smart contracts (called chaincodes).

This is a continuation post from Hyperledger Fabric + Convector + Convector CLI (JavaScript only), in which I show cased how to create a smart contract using Convector (Open source JavaScript Framework).

In this post, I will show how to create a backend in NodeJS for a blockchain application.

Basically what a backend does is call the blockchain nodes to submit requests or make queries. With Fabric we also have a CouchDB or a LevelDB database that allows for complex queries.

Fabric’s nodes have some APIs and we can use the Fabric Node SDK to make those calls. I assume that you already followed this previous tutorial to set up your Convector project or downloaded this code: https://github.com/worldsibu/convector-example-fabcar

# Download the source code from githubgit clone https://github.com/worldsibu/convector-example-fabcar.gitcd convector-example-fabcar/

# The repo already has a backend so for you to be able to create it from scratch, switch to a branch with not backendgit checkout learning/just-cc

This project has a smart contract ready to be installed with a JavaScript version of the FabCar official example from Fabric Samples repo.

Launch the project to create a blockchain network and install the smart contract:

npm i# Wake yourself up a dev blockchain - run this at any time to destroy and recreate a new blockchain for you!npm run env:restart# Now install the chaincode!npm run cc:start -- car 1

Congratulations! 🎊 You have installed a whole blockchain network on your computer. If you are curious about what was created, check here the details of what the Dev Env created for you with just that command line.

Backend with Node JS

Now that you have a protocol running plus an easy smart contract it is time to make a backend exposing the data.

The reason you need a backend is that something has to hold the identity querying the blockchain. Yes, an end user will make the request, but for the communication, you need some certificates so usually, the pattern is to have an Application making the call on behalf of the user. Also, the backend will return data from CouchDB for complex queries (this I will keep it out of the tutorial, for now, everything will come and go directly from the smart contract) and also send transactions to the blockchain.

Create a new folder for your backend code. Let’s use a Yeoman generator to avoid wasting time on the basic plumbing. Outside the blockchain project create a new project like this:

# make sure to be in the root ./convector-example/fabcarcd packages

npm install generator-express-no-stress-typescriptyo express-no-stress-typescript myapp

# type ENTER a few times

cd myapp

Compile and run the backend project.

npx lerna run compile --scope myappnpx lerna run dev:debug --scope myapp

Open http://localhost:3000/ in your browser to see the project running. We won’t create an UI but it will let you see if everything works so far.

If you have this, your backend is running well.

A few details about the folders and files:

  • FOLDER ./.convector-dev-env: this contains all the cryptographic materials (crypto materials) for you to communicate and run the blockchain network.
  • FOLDER ./convector-dev-env/examples: this folder mainly *.network-profile.yaml files, which are files ConvectorCLI includes so that you don’t have to create them from scratch, however you need to adapt its paths to match your project structure, I will detail later about this.
  • FOLDER./chaincode: includes your smart contract compiled to JavaScript.
  • FILE ./org1.car.config.json: is the smart contract configuration file. It includes the network topology for the Fabric SDK to resolve the nodes of the network. It is used to install and upgrade the chaincode as you need it.
  • FOLDER ./packages: includes all your source code. We use Lerna to be able to have multiple projects on a same folder so it is easier to make dependencies without uploading code during development to NPM for example.

Next step is to setup the Node JS project dependencies for Fabric communication.

# To send transactions to the blockchainnpx lerna add @worldsibu/convector-adapter-fabric --scope myapp

# To query the couchdb laternpx lerna add @worldsibu/convector-storage-couchdb --scope myapp

npx lerna add fabric-client --scope myappnpx lerna add fabric-ca-client --scope myapp

npx lerna add @types/bytebuffer --scope myapp

Also add experimentaDecorators flag to the server ./packages/myapp/tsconfig.json file, inside compilerOptions.

"experimentalDecorators": true,

Since we are using Convector you can import the models and controllers to reuse code made for the smart contract. For your backend to recognize your Smart Contract files, simply run:

# now you won't have to replicate the model or the functions (interface) in your backendnpx lerna add car-cc --scope myapp

We use a lot of environment variables to setup our project, so we need to make sure to have the right variables for our project. In your ./packages/myapp/.env file be sure to have the following:

Import and reuse the controller and model from the smart contract to NodeJS

Create a file to pass the network configuration to the SDK at ./packages/myapp/server server create a file selfgenfabriccontext.ts and include the following.

To call the blockchain we will reuse the CarController created in the smart contract, so create a file called smartContractControllers.ts and paste this contents at ./packages/myapp/server.

Now we need to configure the model file from the smart contract to understand that it is in another layer, in this case in nodejs rather than Hyperledger Fabric. Create a file smartContractModels.ts at ./packages/myapp/server and paste the following.

Last but not least, make the Swagger API recognize our Car model structure.

Go to ./packages/myapp/server/common/swagger/Api.yaml and replace from line 19 with the following contents:

All setup! Call the blockchain

At this point you have a running blockchain network, a smart contract installed and working, and a backend almost ready to query and send transaction to the blockchain.

What we need next is to tell your node backend to call the blockchain and how to communicate with it.

Locate the existing API called examples from the Yeoman generator and replace its contents ./packages/myapp/server/api/controllers/examples/controller.ts

Change its contents for this:

Finally, we need to tell the SDK how to communicate and send transactions. For that matter, Fabric requires a Network Profile yaml file. In your path ./packages/myapp/server create a new folder called config , create a file called org1.network-profile.yamland paste the following.

At this point, you need to be sure you have your NodeJS Application running as well your blockchain network. During this post, we already ran this commands, but just in case I’m adding them here again:

# Start the backend NodeJsnpx lerna run dev:debug --scope myapp

# Wake yourself up a dev blockchain - run this at any time to destroy and recreate a new blockchain for you!npm run env:restart# Now install the chaincode!npm run cc:start -- car 1

API Calls

Start Postman and try it yourself. You can make calls which can very well come from an Angular or React front end as well. All the available endpoints from the Nodejs app are:

GET localhost:3000/api/v1/examples

GET localhost:3000/api/v1/examples/1

POST localhost:3000/api/v1/examples/Body{"make":"Volkswagen","model":"Jetta","colour":"gray","owner":"Walter Montes","id":"1"}

You now have a way to add items to the blockchain, as well to make the necessary calls to retrieve the data.

That is all for now. For my next post, I will show how to easily integrate calls to your CouchDB.

Part 1 of this post here.

💻 The source code for this project is here.

Contributors

We constantly look for Convector contributors. We do know a lot of people are using Convector to build their innovations and businesses, so it would be great to have feedback from you and why not a PR adding a feature you’d love to see live in Convector. Join the community here!


Written by waltermontes | CEO @ WorldSibu
Published by HackerNoon on 2018/12/31