Learn Blockchain by creating one, Part 2
Tags: python, flask, blockchain
Published: 2020-08-03 08:30:08

# Welcome back
For the people new here, I have create a blog before this blog and this is just the continuation for the previous blog. Link to the previous blog is [here](https://dev.to/phantsure/learn-blockchain-by-creating-one-23dc). If you are already through that blog, let's move ahead.
 
In the previous blog we made the `Blockchain` class and gave a structure to our blockchain. Now let's interact with our chain.

## Step 2: Our Blockchain as an API
We're going to use the Python Flask Framework. It's a micro-framework and it makes it easy to map endpoints to Python functions. This allows us talk to our blockchain over the web using [HTTP requests](https://www.w3schools.com/tags/ref_httpmethods.asp). It is like normal talking between people but instead of people there are programs talking to each other. Let's see ahead.

We'll create three methods:
- `/transactions/new` To create a new transaction to a block
- `/mine` To tell our server to mine/create/find a new block.
- `/chain` To return the full Blockchain.

### Setting up Flask
Our _server_ will form a single node in our Blockchain network. Let's create some boilerplate code in `app.py`:
```python
from blockchain import Blockchain
import json

from uuid import uuid4
from flask import Flask, request, Response

# Instantiate our Node
app = Flask(__name__)

# Generate a globally unique address for this node
node_identifier = str(uuid4()).replace('-', '')

# Instantiate the Blockchain
blockchain = Blockchain()


@app.route('/mine', methods=['GET'])
def mine():
    return "We'll mine a new Block"
  
@app.route('/transactions/new', methods=['POST'])
def new_transaction():
    return "We'll add a new transaction"

@app.route('/chain', methods=['GET'])
def full_chain():
    response = {
        'chain': blockchain.chain,
        'length': len(blockchain.chain),
    }
    return Response(json.dumps(response), content_type='application/json; charset=utf-8'), 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
```

_What is all that code I didn't understand?!_

Lets go step by step:
- **Line 8:** Instantiates our app, or in this case our `node`. 
- **Line 11:** Creates a random name for our node.
- **Line 14:** Instantiate an object of `Blockchain` class.
- **Line 18:** Create the `/mine` endpoint, which is a `GET` request.
- **Line 22:** Create the `/transaction/new` endpoint, which is a `POST` request, since we'll be sending data to it.
- **Line 26:** Create the `/chain` endpoint, which returns the full Blockchain.
- **Last Line:** Runs the server at localhost at port _5000_.
All the functions return _Json_ response.

### The Transactions Endpoint
This is what the request for a transaction will look like. It's what the user sends to the server:

```python
{
 "sender": "my address",
 "recipient": "someone else's address",
 "amount": 100
}
```

Since we already have our class methods for adding transactions to a block, the rest is easy. Let's write the function for adding transactions:
```python
from blockchain import Blockchain
import json

from uuid import uuid4
from flask import Flask, request, Response

...

@app.route('/transactions/new', methods=['POST'])
def new_transaction():
    values = request.get_json()

    # Check that the required fields are in the POSTed data
    required = ['sender', 'recipient', 'amount']
    if not all(k in values for k in required):
        return 'Missing values', 400

    # Create a new Transaction
    index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])

    response = {'message': f'Transaction will be added to Block {index}'}
    return Response(json.dumps(response), content_type='application/json; charset=utf-8'), 201
```
_(A method for creating Transactions)_


### The Mining Endpoint
This is the place where you will earn _Money_!!

Just kidding. But you will understand what happens in  here. It has to do 3 things:
- Calculate the Proof of Work
- Reward the miner (us) by adding a transaction granting us 1 coin
- Forge the new block by adding it to the chain

Let's add the code for the same in `app.py`.

```python
from blockchain import Blockchain
import json

from uuid import uuid4
from flask import Flask, request, Response

@app.route('/mine', methods=['GET'])
def mine():
    # We run the proof of work algo to get the next proof...
    last_block = blockchain.last_block
    last_proof = last_block['proof']
    proof = blockchain.proof_of_work(last_proof)

    # We must receive a reward for finding the proof ...
    # The sender is "0" to signify that this node has mined a new coin
    blockchain.new_transaction(
        sender="0",
        recipient=node_indentifier,
        amount=1,
    )

    # Forge the new Block by adding it to the chain
    previous_hash = blockchain.hash(last_block)
    block = blockchain.new_block(proof, previous_hash)
    
    response = {
        'message': "New Block Forged",
        'index': block['index'],
        'transactions': block['transactions'],
        'proof': block['proof'],
        'previous_hash': block['previous_hash'],
    }
    return Response(json.dumps(response), content_type='application/json; charset=utf-8'), 200
```
Note that the recipient of the mined block is the address of our node. And most of what we’ve done here is just interact with the methods on our Blockchain class. At this point, we’re done, and can start interacting with our blockchain.

Next step would be interacting with our `Blockchain` which I will cover in next blog. Link to which would be shared soon.

## Credits
<span>Photo by <a href="https://unsplash.com/@mxhpics?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Maxime Horlaville</a> on <a href="https://unsplash.com/s/photos/chains?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span>