DEV Community

Cover image for Learn Blockchain by creating one, Part 2
Sampark Sharma
Sampark Sharma

Posted on • Updated on

Learn Blockchain by creating one, Part 2

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. 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. 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:

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:

{
 "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:

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.

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

Photo by Maxime Horlaville on Unsplash

Top comments (0)