Build a Simple Blockchain & Cryptocurrency with Python, Django Web Framework & ReactJS

Mohammed Gumma
8 min readOct 18, 2019

--

“The best way to learn about blockchain is by building one“

When I first started learning about building blockchains & cryptocurrencies I wish I could find the simplest tutorials that would help me grasp all the fundamentals of the blockchain technology and allow me to have a technical perspective on how it’s built from the inside. Despite the great tutorials & articles out there, I felt like information is scattered. Which makes it difficult to wrap your head around the technical aspects on a beginner-level. This is why I decided to learn everything the hard way and write this simplified compact tutorial I wish I had when I started learning about building blockchains & cryptocurrencies.

Hopefully by the end of this tutorial series, you’ll have a profound technical intuition of how blockchains work and feel comfortable around the idea of building and maintaining blockchains & cryptocurrencies.

Our application’s final look

Prerequisites

1. Basic understanding of the building pillars of blockchains and cryptocurrencies: blocks, digital ledgers, transactions, nonce, consensus… etc.

2. High-school mathematics level.

3. Basic knowledge of Python & Django Web framework.

4. Basic understanding of ReactJS & components.

5. Basic knowledge of APIs & sending requests.

6. Basic understanding of package and dependencies management tools like pip & node package manager (npm)

If you’re unfamiliar with any of the prerequisite concepts or technologies, I’ll leave a reference at the end of the article that contains the best resources for each topic to get you well-oriented and up-to-speed with this tutorial.

This tutorial consists of three main parts. In part I & II, we’re going to be building the architecture of our blockchain’s backend and be able to send API requests to communicate with our blockchain network to mine blocks, retrieve our chain of blocks, connect nodes & synchronize network across nodes with our pythonic consensus protocol. In the last part, we’ll build the user interface & communicate with our network’s API to consume the API and also send Http requests to our network in a meaningful way.

The project and full code used in this tutorial are available on GitHub

I. Building the Blockchain

Getting started

First, make sure you have Python version 3.6 & pip installed. Then, install virtualenv with pip and create a virtual environment for our project on the terminal like so:

$ pip install virtualenv$ virtualenv venv$ source venv/bin/activate

Afterwards, install django 2.2.6 or above then create our project and application

$ pip install django==2.2.6$ django-admin createproject PyChain$ cd PyChain$ python manage.py createapp blockchain

Now that we have everything we need so far to get started with the backend, go to your favorite code editor and open up the project’s directory.

Edit the settings.py file to add our application

Now let's start implementing our blockchain’s logic and configure our URLs to serve as endpoints for the API of our network

Edit the views.py and add the following code:

The class contains all the building pieces of our blockchain we’ll need for now, once our server is running a blockchain object is created and the genesis block gets automatically added to our chain as the first block. I made very sure that the code is readable so that anyone could easily understand the logic behind it.

hash-operation represents the cryptographic puzzle required for mining blocks — I’ve used a simple one here but feel free to change it or implement complex ones when you feel comfortable around the code. The three request methods, mine_block , get_chain & is_valid are invoked whenever a GET request is sent to specific URL endpoints that are hooked with our methods.

Edit the urls.py and add the following code:

Now that we have our backend setup, open up your terminal and run the server:

Exit server and run python manage.py migrate to make this message in red go away

We need an API Client to be able to send Http requests to our API endpoints, You can use Httpie or Curl if you’re comfortable with CLI clients — alternatively, you can use a GUI client like Postman. Which is a great API multipurpose tool.

Open Postman and enter the /mine_block end-point, send more than one request and make sure you’re sending GET requests as shown below:

You should get a response similar to this one every time you mine for a block

Now let's see what our blockchain looks like by sending a GET request this time to our /get_chain endpoint — the response should be something like this:

To check if our chain is valid or not, send a GET request to /is_valid endpoint, the response should be this message if true:

II. Building the Cryptocurrency

In this section, we’re going to be putting all the necessary pieces of our cryptocurrency. We’ll create a cryptocurrency called Sudocoin, add transactions to our blocks and allow other nodes to connect to our network. Each node will be running an instance of our blockchain, we will also want to synchronize our blockchain across all the nodes connected to our network.

Edit views.py and add the new code:

Edit urls.py to configure our new API URL endpoints

Now that we’ve added all the necessary cryptocurrency logic, open two or more terminals — make sure venv is activated first then runserver from different ports like so

Each one of these servers represents a node that’s running an instance of our blockchain’s code

Now go to postman and send GET requests to each one of these nodes separately to mine for blocks, each node will have a different chain length than the other so we need to make sure that our blockchain’s state is synchronized across all nodes and that is achieved using the consensus mechanism we implemented in our replace_chain method that replaces any node’s current chain with the longest-running node’s chain among all of the nodes connected to our network.

We need our current node to discover the other running nodes, we’ll do so by sending a POST request to the endpoint /connect_node — we’ll send a JSON object the contains the other node(s) in our POST request to the current running node we’re communicating with like so:

After sending the request you should get the response seen on the right. Do the same for the other node(s) running. Now that nodes are aware of each other, mine for blocks on every node and then try /replace_chain to make sure that our node is in sync with the blockchain’s latest state or to get the latest state of our blockchain from the node that has the longest-running chain.

I know that for now, it seems like we’re doing all the work for our blockchain, in a real-world example — everything should be done in an autonomous and seamless way , this is why in the next and last part of this tutorial we’ll build a ReactJS front-end interface that’ll make our interactions with the network a lot easier.

III. Build a user interface with ReactJS

Getting started

Before we start building our front-end interface there are a few things we need to do. First, we need to set up our frontend within our project directory and install all the necessary dependencies. Then, we need to run our node server and then tell django where to communicate with our frontend server.

We’ll use create-react-app to build our front-end, it’ll save us the hassle to install and configure our react app.

Open a new terminal, make sure you have npm installed (You can use yarn alternatively) then run this command

 $ npm install create-react-app

After it installs successfully, let's go to our project directory and create our frontend app:

 $ create-react-app frontend 

It’s going to take a few minutes to setup our react app. After it’s finished navigate to our frontend directory and the following commands:

$ cd frontend$ npm start

A new web tab should open and tell us that our react app is up and running.

Now let's install our frontend dependencies, run the following command:

$ npm install axios react-bootstrap bootstrap font-awesome --save

We’ll use Axios to send get & post requests to our API but before we do that we need to establish a connection between the frontend and backend servers

To do this add the following lines at the end of settings.py:

CORS_ORIGIN_ALLOW_ALL = TrueCORS_ALLOW_CREDENTIALS = True

Then add this line to our package.json file:

This line will tell axios to direct all of our requests to this domain.

Finally, add this line to our header tag in public/index.html

<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity=”sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T” crossorigin=”anonymous”/>

Now that we’re good to go, our frontend will be broken down into three components status, send & transactions from top to bottom.

Create a components folder inside src

Create the following files in /src/components and add the following code:

status.js

send.js

transactions.js

Now let's glow our components together in App.js

At last let's start our servers and start interacting with our application, runserver from django’s terminal and npm start from our frontend terminal.

Our application is very simple for now and has many limitations for the sake of making this tutorial as simple as possible. Get comfortable around the code and when you feel like you’ve grasped all the technical aspects of blockchains & cryptocurrencies, play around with the code & think about ways you can overcome these limitations to scale this application up and take it to the next level.

Congratulations you’ve made it all the way to the end, pat yourself on the back for accomplishing this and feel free to hit me up if you have any questions!😀

--

--