Develop a blockchain & Cryptocurrency using Python, Flask & Postman

aena verma
6 min readMar 10, 2021

Here is the link to Github Repository for the Project https://github.com/Aena11/blockchain/tree/main/create%20cryptocurrency

Developing your own basic Blockchain & Cryptocurrency using Python, Flask, and a demo using postman.

Getting Started

Install Necessary Software

  • Download Anaconda
Click here to download
  • Download Postman
Click here to download

Install Dependencies

Flask — pip install flask

Flask-Cors — pip install -U flask-cors

Type the above command in the anaconda prompt.

Phases of Blockchain Project

# Part 1 — Building a Blockchain

Chain of Blocks: This phase involves creating a chain of blocks in which each block in the chain contains “index”, “previous_hash”, “transaction”, “proof of work number (a.k.a nonce)” and “timestamp” as it’s data.The index is the index number of the block, previous_hash contains the hash of the previous block in the blockchain, the transaction contains a list of transactions and proof of work number is the number generated automatically upon successful mining of the block.

class Blockchain:def __init__(self):
self.chain = []
self.transactions = []
self.create_block(proof = 1, previous_hash = '0')
self.nodes = set()

def create_block(self, proof, previous_hash):
block = {'index': len(self.chain) + 1,
'timestamp': str(datetime.datetime.now()),
'proof': proof,
'previous_hash': previous_hash,
'transactions': self.transactions}
self.transactions = []
self.chain.append(block)
return block

Hashing the blocks: We need to hash the blocks in order to avoid the manipulation of blockchain is such a way that someone cannot alter the value of 2nd block in our blockchain (of 10 blocks) to something else.So, we use the SHA256 algorithm for hashing the blocks. Through hashing we get the hash of the previous block in the next block of our blockchain and if the hash matches then the block is valid else invalid.

def proof_of_work(self, previous_proof):
new_proof = 1
check_proof = False
while check_proof is False:
hash_operation = hashlib.sha256(str(new_proof**2 - previous_proof**2).encode()).hexdigest()
if hash_operation[:4] == '0000':
check_proof = True
else:
new_proof += 1
return new_proof

def is_chain_valid(self, chain):
previous_block = chain[0]
block_index = 1
while block_index < len(chain):
block = chain[block_index]
if block['previous_hash'] != self.hash(previous_block):
return False
previous_proof = previous_block['proof']
proof = block['proof']
hash_operation = hashlib.sha256(str(proof**2 - previous_proof**2).encode()).hexdigest()
if hash_operation[:4] != '0000':
return False
previous_block = block
block_index += 1
return True

# Part 2 — Mining our Blockchain

Add Routes: In this phase, we use Flask to create routes. Now, routes are nothing but endpoints and endpoints are simply URLs which have to be accessed in order to perform some action. For example, when you use localhost:5000/mine API call where “localhost:5000/mine” is a URL, you are requesting the URL to perform the Mining Block action for you. So, in order to test all the functionalities in the project, similar API calls have been created using Flask. API calls can be found in the node.py file. Below is one section of that file, it includes Creating a wallet which is a POST request and fetching a wallet which is a GET request.

# Mining a new block
@app.route('/mine_block', methods = ['GET'])
def mine_block():
previous_block = blockchain.get_previous_block()
previous_proof = previous_block['proof']
proof = blockchain.proof_of_work(previous_proof)
previous_hash = blockchain.hash(previous_block)
blockchain.add_transaction(sender = node_address, receiver = 'You', amount = 1)
block = blockchain.create_block(proof, previous_hash)
response = {'message': 'Congratulations, you just mined a block!',
'index': block['index'],
'timestamp': block['timestamp'],
'proof': block['proof'],
'previous_hash': block['previous_hash'],
'transactions': block['transactions']}
return jsonify(response), 200

# Part 3 — Decentralizing our Blockchain

def replace_chain():
is_chain_replaced = blockchain.replace_chain()
if is_chain_replaced:
response = {'message': 'The nodes had different chains so the chain was replaced by the longest one.',
'new_chain': blockchain.chain}
else:
response = {'message': 'All good. The chain is the largest one.',
'actual_chain': blockchain.chain}
return jsonify(response), 200
# Running the app
app.run(host = '0.0.0.0', port = 5003)

In the above phases, I’ve explained in short about what we generally do in each other those phases, for a brief explanation, please refer to the files in the Github repository which contains docstrings and comments explaining everything.

Running the Project

  • Download the GitHub Repository to your system
  • Launch Spyder in anaconda and open the above file in it
  • Here basically we are going to do a transaction between 3 nodes of a blockchain with our cryptocurrency.
  • now select all the code of file cryptocurrency_node_5001.py and press ctrl + enter.
  • open a new tab in the console and do the same for both files cryptocurrency_node_5002 and cryptocurrency_node_5003.
  • doubletake on the postman to lunch it and interact with our blockchain.
  • Well, we will create two more tabs here. Each of them will be for each of our nodes and in GET request> type address mention in the image below.
  • By changing the port type same GET request for the other 2 nodes.
  • Click on the “Send” Button in every node.
  • u will get Genesis block on each node.(first node)
  • Now, we will make our first post request to do that select post in postman for each node.>http://127.0.0.1:5001/connect_node
  • go to >body, select>raw, select >JSON (file type) paste the same code below in fig (it is there in GitHub file), click>enter.
  • this will connect the node with 5001 with the other 2 nodes (notice the port ). do the same for the other 2 nodes. u will get a successful message in the body.
  • Now, it's time to mine a new for our blockchain .make a Get request >http://127.0.0.1:5002/mine_block and click >enter.
  • let’s check >make a GET request>http://127.0.0.1:5002/get_chain >you will get 2 blocks previous block and the new block you mined just now.
  • as we know in the blockchain each node has the same blockchain now as we mined a block in node one it should get updated in the blockchain that is newly mined block should be in the other 2 nodes
  • In node 2 and make GET request >http://127.0.0.1:5002/replace_chain and click>enter. this way we will get the same chain in node 2. Do the same for node 3 .make a get chain request and u can see 2 blocks in all nodes
  • Finally it time to make ur first transaction from node 1 to node 2
  • node 1 >hadelin, node2 >kirill, node3> You.
  • make a POST request >http://127.0.0.1:5001/add_transaction,click >body, click>raw, select>JSON,paste this code in fig.(it is there in GitHub repository)
  • we made a successful transaction
  • we have to mine block to save this transaction for that make a get request>http://127.0.0.1:5001/mine_block,we can index 3 that means its third block of our blockchain .here 2 transaction is there one is default one and another is a transaction we did above.
  • make a GET request >http://127.0.0.1:5001/get_chain to see all transaction in blockchain in node 1.make a GET request in node 2 and 3 >http://127.0.0.1:5002/replace_chain
  • same u can do trnsaction with other node as well.
  • This way we can make our simple digital currency ,if u want u can want add more function in ur blockchain to make it better.

Thank you for Reading!

--

--