Table of Contents
- Introduction
- Prerequisites
- Installation
- Creating the Blockchain
- Creating the Cryptocurrency
- Mining
- Transactions
- Summary
Introduction
In this tutorial, we will learn how to build a basic blockchain and a cryptocurrency system using Python. Blockchain, the underlying technology of cryptocurrencies, is a distributed digital ledger that records transactions across multiple computers. By the end of this tutorial, you will be able to understand the fundamentals of blockchain, create a basic blockchain system, and build a simple cryptocurrency.
Prerequisites
Before starting this tutorial, you should have a basic understanding of Python programming language, object-oriented programming concepts, and web development using Python. It would also be helpful if you have some knowledge of the blockchain technology and cryptocurrencies.
Installation
To get started, you need to have Python installed on your system. You can download the latest version of Python from the official website and follow the installation instructions specific to your operating system.
Once you have Python installed, you will also need to install some external libraries for this project. Open your terminal or command prompt and run the following commands:
bash
pip install hashlib
pip install Flask
These commands will install the hashlib
library for cryptographic functions and the Flask
library for building web applications.
Creating the Blockchain
First, let’s create a basic blockchain system. Open your text editor and create a new file called blockchain.py
. We will start by importing the required libraries:
python
import hashlib
import json
from time import time
from flask import Flask, jsonify
Next, let’s define the Blockchain
class:
```python
class Blockchain:
def init(self):
self.chain = []
self.current_transactions = []
# Create genesis block
self.new_block(previous_hash='1', proof=100)
``` Here, we initialize the blockchain with an empty list for storing blocks and another empty list for storing transactions.
Next, let’s define the new_block
method:
```python
def new_block(self, proof, previous_hash=None):
block = {
‘index’: len(self.chain) + 1,
‘timestamp’: time(),
‘transactions’: self.current_transactions,
‘proof’: proof,
‘previous_hash’: previous_hash or self.hash(self.chain[-1])
}
# Reset the current list of transactions
self.current_transactions = []
# Append the block to the chain
self.chain.append(block)
``` In this method, we create a new block with the given proof and previous hash. We also include the current list of transactions, timestamp, and an index for the block. After creating the block, we reset the current list of transactions.
Next, let’s define the new_transaction
method:
```python
def new_transaction(self, sender, recipient, amount):
self.current_transactions.append({
‘sender’: sender,
‘recipient’: recipient,
‘amount’: amount
})
# Return the index of the next block that will contain this transaction
return self.last_block['index'] + 1
``` In this method, we create a new transaction with the given sender, recipient, and amount. We append the transaction to the current list of transactions and return the index of the next block that will contain this transaction.
Next, let’s define some additional methods: ```python @property def last_block(self): return self.chain[-1]
def hash(self, block):
# Convert the block dictionary to a JSON string
block_string = json.dumps(block, sort_keys=True).encode()
# Calculate the hash of the JSON string using SHA-256 algorithm
return hashlib.sha256(block_string).hexdigest()
``` Here, the `last_block` property returns the last block in the chain. The `hash` method takes a block dictionary, converts it to a JSON string, and calculates the hash using SHA-256 algorithm.
Finally, let’s add the code to create a Flask web application: ```python # Instantiate the Node app = Flask(name)
# Instantiate the Blockchain
blockchain = Blockchain()
@app.route('/mine', methods=['GET'])
def mine():
# We will implement this later
pass
@app.route('/transactions/new', methods=['POST'])
def new_transaction_route():
# We will implement this later
pass
@app.route('/chain', methods=['GET'])
def get_chain():
response = {
'chain': blockchain.chain,
'length': len(blockchain.chain)
}
return jsonify(response), 200
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
``` Here, we define three routes for the Flask application: `/mine` for mining new blocks, `/transactions/new` for creating new transactions, and `/chain` for retrieving the entire blockchain.
Creating the Cryptocurrency
Now that we have created the basic blockchain system, let’s implement a simple cryptocurrency. In the new_transaction_route
function, modify the code as follows:
```python
@app.route(‘/transactions/new’, methods=[‘POST’])
def new_transaction_route():
values = request.get_json()
required_fields = ['sender', 'recipient', 'amount']
if not all(field in values for field in required_fields):
return 'Missing values', 400
index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])
response = {'message': f'Transaction will be added to Block {index}'}
return jsonify(response), 201
``` Here, we retrieve the JSON data sent in the request and check if it contains the required fields: sender, recipient, and amount. If any of the fields are missing, we return an error response.
Next, let’s implement the /mine
route to mine new blocks. Modify the code as follows:
```python
@app.route(‘/mine’, methods=[‘GET’])
def mine():
# We will implement this later
# Get the proof from the mining proof algorithm
proof = blockchain.proof_of_work()
# Forge the new block by adding it to the chain
previous_hash = blockchain.hash(blockchain.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 jsonify(response), 200
``` In this modified code, we first retrieve the proof from the proof of work algorithm (which we will define later). Then, we forge the new block by adding it to the chain. Finally, we return a response containing the information about the new block.
Mining
Now, let’s implement the proof of work algorithm. Add the following code to the Blockchain
class:
```python
def proof_of_work(self):
proof = 0
while self.valid_proof(proof) is False:
proof += 1
return proof
def valid_proof(self, proof):
guess = f'{proof}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:4] == "0000"
``` Here, the `proof_of_work` method tries different values of `proof` until it finds a valid proof. The `valid_proof` method checks if the proof is valid by calculating the hash and checking if the first four characters are zeros.
Transactions
Finally, let’s test our blockchain and cryptocurrency system. Run the following command in your terminal or command prompt to start the Flask application:
bash
python blockchain.py
Now, open your web browser and navigate to http://localhost:5000/
. You should see a JSON response containing the current blockchain.
To create a new transaction, you can use a tool like cURL or Postman to send a POST request to http://localhost:5000/transactions/new
with the following JSON payload:
json
{
"sender": "sender-address",
"recipient": "recipient-address",
"amount": 1
}
To mine a new block, send a GET request to http://localhost:5000/mine
. You should receive a response containing the details of the mined block.
Summary
In this tutorial, we have learned how to build a basic blockchain system and a simple cryptocurrency using Python. We started by creating a blockchain class with methods for adding blocks and transactions. Then, we created a Flask web application to interact with the blockchain. Finally, we implemented the proof of work algorithm to mine new blocks.
By understanding the fundamentals of blockchain and cryptocurrencies, you can now explore more advanced topics such as consensus algorithms, smart contracts, and decentralized applications.