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: