Go back to Blogs
Blockchain: Core concepts, structure and implementation
This blog article will walk you through the concepts, structure, implementation, and validation of a simple blockchain structure.
Introduction
Blockchain Myths
Before discussing what blockchain is, let’s see some of the myths surrounding blockchain:
- Blockchain is the same thing as cryptocurrency – Blockchain is not equivalent to cryptocurrency, whether Bitcoin or any other cryptocurrency. Blockchain is a technology, whereas Bitcoin / cryptocurrency makes use of blockchain technology. Blockchain has many applications outside of the crypto world.
- Blockchain can solve all security issues – Blockchain cannot solve all issues related to security or fraudulent activities. Careful considerations need to be addressed to which security issues should be addressed using blockchain.
- Blockchain is equivalent to distributed databases – Blockchain and distributed databases are two different technologies, each with its own merits and demerits and different potential to solve different problems.
Then What is a Blockchain?
A Blockchain is an append-only, immutable, never-ending chain of data where data, once added, cannot be deleted or modified, achieving a tamper-proof system. It provides transparency, security, and efficiency, which are crucial for various applications, from cryptocurrencies to supply chain management. It is a decentralized digital ledger that records transactions across many computers in such a way that the registered transactions cannot be altered retroactively.
Decentralization refers to the distribution of power or authority away from a single central entity to multiple individuals or groups. In the context of technology, it refers to systems or networks that operate without a central authority controlling them.
The figure below gives an overview of centralized and decentralized architecture:
The remarkable attention and interest surrounding blockchain technology can be attributed to several key features that are illustrated in the figure below:
Blockchain Framework
A blockchain framework is a set of protocols, rules, and standards that define the structure and operations of a blockchain network. The five major layers of a blockchain framework is illustrated in the following figure:
Structure of a Block
A block is an essential component of a blockchain, typically comprising a collection of transactions. Its structure consists of a preamble that stores metadata such as a timestamp and reference to the previous block (known as the parent block) and a body that contains the actual transaction data. The unique cryptographic hash of each block ensures the chain’s integrity. Blocks are chained together in chronological order to create a secure and immutable ledger.
Each block in a blockchain contains the following main components:
- Timestamp: The time when the block was created.
- Previous Hash: The hash of the previous block.
- Nonce: A number used for cryptographic computations, essential for the proof-of-work mechanism.
- Block Hash: A unique digital fingerprint of the block, created using the block’s contents.
- Difficulty Target: A measure of how difficult it is to mine the blockchain block, or in other words, how difficult it is to find the blockhash.
- Data / Transaction List: The information or transactions stored in the block.
Structure of a Blockchain
A blockchain is a sequence of blocks linked together, where each block points to the previous one via its hash. This linking forms a secure and immutable chain, starting from the genesis block (the first block).
The diagram below illustrates the Structure of the Blockchain:
Simplified blockchain Implementation in Python
Below we’ll present a simplified implementation of a blockchain in Python using two main classes: Block and Blockchain.
Block Class: represents each block in the blockchain.
import hashlib
import json
import logging
# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Define block structure
class Block:
def __init__(self, timestamp, data, previous_hash):
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash
self.nonce = 0
self.hash = self.compute_hash()
# Calculate SHA256 hash of the block
def compute_hash(self):
try:
block_string = f"{self.timestamp}{self.data}{self.previous_hash}{self.nonce}"
return hashlib.sha256(block_string.encode()).hexdigest()
except Exception as e:
logging.exception("Error computing hash ", e)
def to_dict(self):
return self.__dict__
def __str__(self):
return json.dump(self.__dict__, sort_keys=True, indent=4)
Blockchain Class – The class that manages the chain of blocks is provided below:
from block import Block
from time import time
import json
import logging
# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Define Blockchain structure
class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]
# Create first (genesis) block
@staticmethod
def create_genesis_block():
return Block(time(), "Genesis Block", "0")
# Get the last block in the blockchain
def get_latest_block(self):
return self.chain[-1]
# Add new block to the blockchain
def add_block(self, new_block):
try:
new_block.previous_hash = self.get_latest_block().hash
new_block.hash = self.proof_of_work(new_block)
self.chain.append(new_block)
except Exception as e:
logging.exception("Error adding new block ", e)
# Proof of work Algorithm
@staticmethod
def proof_of_work(block, difficulty=4):
try:
target = '0' * difficulty
while block.hash[:difficulty] != target:
block.nonce += 1
block.hash = block.compute_hash()
return block.hash
except Exception as e:
logging.exception(e)
# Validate the blockchain structure
def validate_chain(self):
try:
for i in range(1, len(self.chain)):
current_block = self.chain[i]
previous_block = self.chain[i - 1]
if current_block.hash != current_block.compute_hash():
logging.info(f"Block {i} has been tampered with!")
return False
if current_block.previous_hash != previous_block.hash:
logging.info(f"Block {i}'s previous hash does not match the previous block's hash!")
return False
return True
except Exception as e:
logging.exception("Error validating chain", e)
return False
def __str__(self):
return json.dumps([block.to_dict() for block in self.chain], sort_keys=True, indent=4)
Adding and Validating Blocks – Now, let’s create a blockchain and add four blocks to it in the application main:
from block import Block
from blockchain import Blockchain
from time import time
import logging
# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
if __name__ == '__main__':
try:
# Create a new blockchain with the Genesis block
blockchain = Blockchain()
# Add new blocks to the chain
blockchain.add_block(Block(time(), {"amount": 4}, blockchain.get_latest_block().hash))
blockchain.add_block(Block(time(), {"amount": 10}, blockchain.get_latest_block().hash))
blockchain.add_block(Block(time(), {"amount": 7}, blockchain.get_latest_block().hash))
blockchain.add_block(Block(time(), {"amount": 2}, blockchain.get_latest_block().hash))
# Validate the blockchain
logging.info("Is blockchain valid? " + str(blockchain.validate_chain()))
# Display the current blockchain
logging.info(blockchain)
except Exception as em:
logging.exception("Exception in main ", em)
Results
By running the above python script of a blockchain implementation, we can see that we achieved a basic but functional blockchain application. Below is a sample JSON output of the blockchain containing five blocks, including the genesis block:
2024-07-02 14:52:16,595 - INFO - Is blockchain valid? True
2024-07-02 14:52:16,595 - INFO - [
{
"data": "Genesis Block",
"hash": "903d1c7bfece0e5f2712e006c602f0323300f9d5cf513a960d4b0a55ae43bc24",
"nonce": 0,
"previous_hash": "0",
"timestamp": 1719924736.211645
},
{
"data": {
"amount": 4
},
"hash": "00002ccd392d8b0d49420e5166f82c4e9517dad7f5933627eb94d35613db0f31",
"nonce": 60203,
"previous_hash": "903d1c7bfece0e5f2712e006c602f0323300f9d5cf513a960d4b0a55ae43bc24",
"timestamp": 1719924736.211662
},
{
"data": {
"amount": 10
},
"hash": "00007852994122002ca4fa6b7f1a5ae2806b7a8b5db44e3e723be4dae46e557f",
"nonce": 30619,
"previous_hash": "00002ccd392d8b0d49420e5166f82c4e9517dad7f5933627eb94d35613db0f31",
"timestamp": 1719924736.2964811
},
{
"data": {
"amount": 7
},
"hash": "00008cdae4833c2fabff1f570a332439911a9a7fa8d5f924a579726413693d3c",
"nonce": 34769,
"previous_hash": "00007852994122002ca4fa6b7f1a5ae2806b7a8b5db44e3e723be4dae46e557f",
"timestamp": 1719924736.3350961
},
{
"data": {
"amount": 2
},
"hash": "0000248c1de4bcc73f5bdda7148079ebde8dfbf79f759e707e6308fefaf4b6da",
"nonce": 177436,
"previous_hash": "00008cdae4833c2fabff1f570a332439911a9a7fa8d5f924a579726413693d3c",
"timestamp": 1719924736.37853
}
]
Conclusion
In this comprehensive blog article, we dived into the functional principles of blockchain technology and demonstrated the implementation using Python with five blocks including the genesis block. We started by exploring the core concepts, features, and structure of blocks and blockchain. The concepts were then translated into a practical implementation, where we constructed a blockchain with blocks containing essential properties such as timestamp, previous hash, nonce, block hash, difficulty target and data. By understanding the fundamental components and processes, such as block creation, hashing, proof-of-work, and chain validation, you gain a solid foundation in blockchain technology.
Future Direction
- Enhancements and Features: Adding features like transaction management, smart contracts and decentralized consensus mechanism.
- Integration and real world applications: Integrating with other technologies and platforms to create real world applications such as cryptocurrency systems, supply chain tracking and secure voting systems.
- Security and scalability: Enhancing security measures to protect against attack such as 51% attacks and double-spending and exploring scalability solutions like sharding and layer-2 protocols to handle increased transaction volumes.
References
- Bitcoin: A Peer-to-Peer Electronic Cash System.
- Mastering Bitcoin
- Blockchain Basics by Daniel Drescher: An introduction to the concepts and technologies behind blockchain.