The user wants a simple blockchain implementation with a graphical interface. Let me create a comprehensive blockchain visualization that includes:
A blockchain with multiple blocks
Each block containing:
Index
Timestamp
Data/Transactions
Previous hash
Current hash
Nonce (for proof of work)
Features to include:
Add new blocks
Visual representation of the chain
Hash visualization
Proof of work mining simulation
Chain validation
Tamper detection
I'll use Tkinter for the GUI since it's built-in and doesn't require additional packages for the core functionality. I'll create an engaging visual interface that shows the blockchain structure clearly.
Let me design this:
Left panel: Controls (add block, mine, validate chain)
Right panel: Visual representation of blocks in the chain
Each block shown as a card with its details
Color coding for valid/invalid blocks
Mining animation
Hash comparison visualization
I'll implement:
Block class with hashing
Blockchain class with chain management
Proof of work algorithm
GUI with Tkinter
Visual chain display
Tamper detection demo
Simple Blockchain Implementation with GUI
This is a complete blockchain implementation with a graphical interface that demonstrates core blockchain concepts including hashing, mining, chain validation, and tamper detection.
Installation
bash
pip install tkinter
Note: Tkinter usually comes pre-installed with Python. If not, install it via your system's package manager.
Complete Code
python
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import hashlib
import time
import json
from datetime import datetime
import threading
class Block:
"""Represents a single block in the blockchain."""
def __init__(self, index, timestamp, data, previous_hash):
self.index = index
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash
self.nonce = 0
self.hash = self.calculate_hash()
def calculate_hash(self):
"""Calculate the hash of the block using SHA-256."""
block_string = f"{self.index}{self.timestamp}{json.dumps(self.data, sort_keys=True)}{self.previous_hash}{self.nonce}"
return hashlib.sha256(block_string.encode()).hexdigest()
def mine_block(self, difficulty):
"""Mine the block by finding a hash with the required number of leading zeros."""
target = "0" * difficulty
attempts = 0
while self.hash[:difficulty] != target:
self.nonce += 1
attempts += 1
self.hash = self.calculate_hash()
return attempts
def to_dict(self):
"""Convert block to dictionary."""
return {
"index": self.index,
"timestamp": self.timestamp,
"data": self.data,
"previous_hash": self.previous_hash,
"nonce": self.nonce,
"hash": self.hash
}
class Blockchain:
"""Represents the blockchain."""
def __init__(self, difficulty=3):
self.chain = [self.create_genesis_block()]
self.difficulty = difficulty
self.pending_transactions = []
def create_genesis_block(self):
"""Create the first block in the chain."""
return Block(0, time.time(), "Genesis Block", "0")
def get_latest_block(self):
"""Get the most recent block."""
return self.chain[-1]
def add_block(self, data, mining_callback=None):
"""Add a new block to the chain with mining."""
new_block = Block(
len(self.chain),
time.time(),
data,
self.get_latest_block().hash
)
# Mine the block
if mining_callback:
mining_callback(True)
attempts = new_block.mine_block(self.difficulty)
if mining_callback:
mining_callback(False)
self.chain.append(new_block)
return new_block, attempts
def is_chain_valid(self):
"""Validate the entire blockchain."""
for i in range(1, len(self.chain)):
current_block = self.chain[i]
previous_block = self.chain[i - 1]
# Check if current block's hash is valid
if current_block.hash != current_block.calculate_hash():
return False, i, "Invalid hash"
# Check if current block points to correct previous hash
if current_block.previous_hash != previous_block.hash:
return False, i, "Broken chain link"
return True, -1, "Chain is valid"
def tamper_with_block(self, block_index, new_data):
"""Simulate tampering with a block (for demonstration)."""
if 0 < block_index < len(self.chain):
self.chain[block_index].data = new_data
return True
return False
class BlockchainGUI:
"""Graphical User Interface for the Blockchain."""
def __init__(self, root):
self.root = root
self.root.title("🔗 Blockchain Simulator")
self.root.geometry("1200x800")
self.root.configure(bg='#1a1a2e')
# Initialize blockchain
self.blockchain = Blockchain(difficulty=3)
self.block_widgets = []
self.is_mining = False
# Style configuration
self.setup_styles()
# Create GUI
self.create_widgets()
# Display initial chain
self.refresh_chain_display()
def setup_styles(self):
"""Configure ttk styles."""
self.colors = {
'bg_dark': '#1a1a2e',
'bg_medium': '#16213e',
'bg_light': '#0f3460',
'accent': '#e94560',
'text_light': '#eaeaea',
'text_dim': '#a0a0a0',
'success': '#00d9a5',
'warning': '#ffc107',
'hash_color': '#7b68ee'
}
style = ttk.Style()
style.theme_use('clam')
style.configure('Title.TLabel',
background=self.colors['bg_dark'],
foreground=self.colors['text_light'],
font=('Helvetica', 24, 'bold'))
style.configure('Header.TLabel',
background=self.colors['bg_medium'],
foreground=self.colors['text_light'],
font=('Helvetica', 12, 'bold'))
style.configure('Custom.TButton',
font=('Helvetica', 10, 'bold'),
padding=10)
style.configure('Custom.TEntry',
fieldbackground=self.colors['bg_light'],
foreground=self.colors['text_light'])
def create_widgets(self):
"""Create the main GUI widgets."""
# Main container
main_container = tk.Frame(self.root, bg=self.colors['bg_dark'])
main_container.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
# Title
title_frame = tk.Frame(main_container, bg=self.colors['bg_dark'])
title_frame.pack(fill=tk.X, pady=(0, 20))
title_label = tk.Label(title_frame,
text="🔗 Blockchain Simulator",
font=('Helvetica', 28, 'bold'),
bg=self.colors['bg_dark'],
fg=self.colors['text_light'])
title_label.pack(side=tk.LEFT)
# Stats label
self.stats_label = tk.Label(title_frame,
text="Blocks: 1 | Difficulty: 3",
font=('Helvetica', 12),
bg=self.colors['bg_dark'],
fg=self.colors['text_dim'])
self.stats_label.pack(side=tk.RIGHT)
# Control panel and chain display side by side
content_frame = tk.Frame(main_container, bg=self.colors['bg_dark'])
content_frame.pack(fill=tk.BOTH, expand=True)
# Left panel - Controls
left_panel = tk.Frame(content_frame, bg=self.colors['bg_medium'], width=350)
left_panel.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 20))
left_panel.pack_propagate(False)
self.create_control_panel(left_panel)
# Right panel - Chain display
right_panel = tk.Frame(content_frame, bg=self.colors['bg_dark'])
right_panel.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.create_chain_display(right_panel)
def create_control_panel(self, parent):
"""Create the control panel."""
# Header
header = tk.Label(parent,
text="⚙️ Controls",
font=('Helvetica', 16, 'bold'),
bg=self.colors['bg_medium'],
fg=self.colors['text_light'])
header.pack(pady=(20, 15), padx=20, anchor='w')
# Add Block Section
add_frame = tk.LabelFrame(parent,
text=" Add New Block ",
font=('Helvetica', 11, 'bold'),
bg=self.colors['bg_medium'],
fg=self.colors['text_light'],
bd=2,
relief=tk.GROOVE)
add_frame.pack(fill=tk.X, padx=20, pady=10)
# Block data input
tk.Label(add_frame,
text="Block Data:",
font=('Helvetica', 10),
bg=self.colors['bg_medium'],
fg=self.colors['text_dim']).pack(anchor='w', padx=10, pady=(10, 5))
self.data_text = scrolledtext.ScrolledText(add_frame,
height=4,
width=35,
font=('Consolas', 10),
bg=self.colors['bg_light'],
fg=self.colors['text_light'],
insertbackground=self.colors['text_light'],
wrap=tk.WORD)
self.data_text.pack(padx=10, pady=5)
self.data_text.insert(tk.END, "Transaction: Alice sends 10 BTC to Bob")
# Mining info
self.mining_status = tk.Label(add_frame,
text="Ready to mine",
font=('Helvetica', 9),
bg=self.colors['bg_medium'],
fg=self.colors['text_dim'])
self.mining_status.pack(pady=5)
# Add block button
self.add_btn = tk.Button(add_frame,
text="⛏️ Mine & Add Block",
font=('Helvetica', 11, 'bold'),
bg=self.colors['accent'],
fg='white',
activebackground='#ff6b6b',
activeforeground='white',
cursor='hand2',
relief=tk.FLAT,
command=self.add_block)
self.add_btn.pack(fill=tk.X, padx=10, pady=10)
# Difficulty Section
diff_frame = tk.LabelFrame(parent,
text=" Mining Difficulty ",
font=('Helvetica', 11, 'bold'),
bg=self.colors['bg_medium'],
fg=self.colors['text_light'],
bd=2,
relief=tk.GROOVE)
diff_frame.pack(fill=tk.X, padx=20, pady=10)
tk.Label(diff_frame,
text="Higher difficulty = Longer mining time",
font=('Helvetica', 9),
bg=self.colors['bg_medium'],
fg=self.colors['text_dim']).pack(pady=(10, 5))
self.difficulty_var = tk.IntVar(value=3)
difficulty_scale = tk.Scale(diff_frame,
from_=1,
to=5,
orient=tk.HORIZONTAL,
variable=self.difficulty_var,
font=('Helvetica', 10),
bg=self.colors['bg_medium'],
fg=self.colors['text_light'],
troughcolor=self.colors['bg_light'],
highlightthickness=0,
command=self.update_difficulty)
difficulty_scale.pack(fill=tk.X, padx=10, pady=(0, 10))
# Validation Section
val_frame = tk.LabelFrame(parent,
text=" Chain Validation ",
font=('Helvetica', 11, 'bold'),
bg=self.colors['bg_medium'],
fg=self.colors['text_light'],
bd=2,
relief=tk.GROOVE)
val_frame.pack(fill=tk.X, padx=20, pady=10)
validate_btn = tk.Button(val_frame,
text="✅ Validate Chain",
font=('Helvetica', 11, 'bold'),
bg=self.colors['success'],
fg='white',
activebackground='#00b386',
cursor='hand2',
relief=tk.FLAT,
command=self.validate_chain)
validate_btn.pack(fill=tk.X, padx=10, pady=10)
# Tamper Section
tamper_frame = tk.LabelFrame(parent,
text=" Tamper Demo ",
font=('Helvetica', 11, 'bold'),
bg=self.colors['bg_medium'],
fg=self.colors['text_light'],
bd=2,
relief=tk.GROOVE)
tamper_frame.pack(fill=tk.X, padx=20, pady=10)
tk.Label(tamper_frame,
text="Block Index:",
font=('Helvetica', 10),
bg=self.colors['bg_medium'],
fg=self.colors['text_dim']).pack(anchor='w', padx=10, pady=(10, 0))
self.tamper_index = tk.Entry(tamper_frame,
font=('Helvetica', 10),
bg=self.colors['bg_light'],
fg=self.colors['text_light'],
insertbackground=self.colors['text_light'],
width=10)
self.tamper_index.pack(anchor='w', padx=10, pady=5)
self.tamper_index.insert(0, "1")
tamper_btn = tk.Button(tamper_frame,
text="🔓 Tamper with Block",
font=('Helvetica', 11, 'bold'),
bg=self.colors['warning'],
fg='black',
activebackground='#e6ac00',
cursor='hand2',
relief=tk.FLAT,
command=self.tamper_block)
tamper_btn.pack(fill=tk.X, padx=10, pady=10)
# Reset button
reset_btn = tk.Button(parent,
text="🔄 Reset Blockchain",
font=('Helvetica', 10),
bg=self.colors['bg_light'],
fg=self.colors['text_light'],
activebackground=self.colors['accent'],
cursor='hand2',
relief=tk.FLAT,
command=self.reset_blockchain)
reset_btn.pack(fill=tk.X, padx=20, pady=20)
def create_chain_display(self, parent):
"""Create the blockchain display area."""
# Header
header = tk.Label(parent,
text="📦 Blockchain",
font=('Helvetica', 16, 'bold'),
bg=self.colors['bg_dark'],
fg=self.colors['text_light'])
header.pack(anchor='w', pady=(0, 15))
# Canvas with scrollbar for chain
canvas_frame = tk.Frame(parent, bg=self.colors['bg_dark'])
canvas_frame.pack(fill=tk.BOTH, expand=True)
self.canvas = tk.Canvas(canvas_frame,
bg=self.colors['bg_dark'],
highlightthickness=0)
scrollbar = ttk.Scrollbar(canvas_frame, orient=tk.VERTICAL, command=self.canvas.yview)
self.scrollable_frame = tk.Frame(self.canvas, bg=self.colors['bg_dark'])
self.scrollable_frame.bind(
"<Configure>",
lambda e: self.canvas.configure(scrollregion=self.canvas.bbox("all"))
)
self.canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
self.canvas.configure(yscrollcommand=scrollbar.set)
self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# Enable mouse wheel scrolling
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
def _on_mousewheel(self, event):
"""Handle mouse wheel scrolling."""
self.canvas.yview_scroll(int(-1*(event.delta/120)), "units")
def refresh_chain_display(self):
"""Refresh the blockchain display."""
# Clear existing widgets
for widget in self.scrollable_frame.winfo_children():
widget.destroy()
self.block_widgets = []
# Display each block
for i, block in enumerate(self.blockchain.chain):
self.create_block_widget(block, i)
# Update stats
self.stats_label.config(
text=f"Blocks: {len(self.blockchain.chain)} | Difficulty: {self.blockchain.difficulty}"
)
def create_block_widget(self, block, index):
"""Create a visual widget for a block."""
is_genesis = block.index == 0
# Block container
block_frame = tk.Frame(self.scrollable_frame,
bg=self.colors['bg_light'],
bd=2,
relief=tk.RAISED)
block_frame.pack(fill=tk.X, pady=8, padx=5)
# Block header with index
header_color = self.colors['accent'] if is_genesis else self.colors['success']
header = tk.Frame(block_frame, bg=header_color)
header.pack(fill=tk.X)
header_text = f"🧱 Block #{block.index}" if not is_genesis else "🌟 Genesis Block"
tk.Label(header,
text=header_text,
font=('Helvetica', 12, 'bold'),
bg=header_color,
fg='white').pack(side=tk.LEFT, padx=10, pady=8)
# Show hash status indicator
hash_label = tk.Label(header,
text="✓ VALID" if block.hash == block.calculate_hash() else "✗ TAMPERED",
font=('Helvetica', 10, 'bold'),
bg=header_color,
fg='white')
hash_label.pack(side=tk.RIGHT, padx=10, pady=8)
# Block content
content = tk.Frame(block_frame, bg=self.colors['bg_light'])
content.pack(fill=tk.X, padx=10, pady=10)
# Create info grid
info_items = [
("📅 Timestamp:", datetime.fromtimestamp(block.timestamp).strftime('%Y-%m-%d %H:%M:%S')),
("📝 Data:", str(block.data)[:50] + "..." if len(str(block.data)) > 50 else str(block.data)),
("🔗 Previous Hash:", block.previous_hash[:32] + "..."),
("#️⃣ Hash:", block.hash[:32] + "..."),
("🎲 Nonce:", str(block.nonce))
]
for i, (label_text, value_text) in enumerate(info_items):
row_frame = tk.Frame(content, bg=self.colors['bg_light'])
row_frame.pack(fill=tk.X, pady=2)
tk.Label(row_frame,
text=label_text,
font=('Helvetica', 9, 'bold'),
bg=self.colors['bg_light'],
fg=self.colors['text_dim'],
width=15,
anchor='w').pack(side=tk.LEFT)
tk.Label(row_frame,
text=value_text,
font=('Consolas', 9),
bg=self.colors['bg_light'],
fg=self.colors['hash_color'] if 'Hash' in label_text else self.colors['text_light'],
anchor='w').pack(side=tk.LEFT, fill=tk.X, expand=True)
# Chain link arrow (except for last block)
if index < len(self.blockchain.chain) - 1:
arrow_frame = tk.Frame(self.scrollable_frame, bg=self.colors['bg_dark'])
arrow_frame.pack()
tk.Label(arrow_frame,
text="⬇️",
font=('Helvetica', 20),
bg=self.colors['bg_dark'],
fg=self.colors['accent']).pack()
self.block_widgets.append(block_frame)
def add_block(self):
"""Add a new block to the blockchain."""
if self.is_mining:
return
data = self.data_text.get("1.0", tk.END).strip()
if not data:
messagebox.showwarning("Warning", "Please enter block data!")
return
def mine():
self.is_mining = True
self.add_btn.config(state=tk.DISABLED)
self.mining_status.config(text="⛏️ Mining in progress...", fg=self.colors['warning'])
start_time = time.time()
new_block, attempts = self.blockchain.add_block(data, self.update_mining_status)
elapsed = time.time() - start_time
self.root.after(0, lambda: self.mining_status.config(
text=f"✅ Mined! Nonce: {attempts:,} attempts ({elapsed:.2f}s)",
fg=self.colors['success']
))
self.root.after(0, self.refresh_chain_display)
self.root.after(0, lambda: self.add_btn.config(state=tk.NORMAL))
self.is_mining = False
thread = threading.Thread(target=mine)
thread.start()
def update_mining_status(self, is_mining):
"""Update mining status indicator."""
if is_mining:
self.root.after(0, lambda: self.mining_status.config(
text="⛏️ Mining... Finding valid hash...",
fg=self.colors['warning']
))
def update_difficulty(self, value):
"""Update mining difficulty."""
self.blockchain.difficulty = int(value)
self.stats_label.config(
text=f"Blocks: {len(self.blockchain.chain)} | Difficulty: {self.blockchain.difficulty}"
)
def validate_chain(self):
"""Validate the entire blockchain."""
is_valid, invalid_index, message = self.blockchain.is_chain_valid()
if is_valid:
messagebox.showinfo("✅ Validation Result",
f"The blockchain is valid!\n\n"
f"Total blocks: {len(self.blockchain.chain)}\n"
f"All hashes are correct and chain links are intact.")
else:
messagebox.showerror("❌ Validation Failed",
f"Blockchain is INVALID!\n\n"
f"Issue found at Block #{invalid_index}\n"
f"Reason: {message}")
self.refresh_chain_display()
def tamper_block(self):
"""Simulate tampering with a block."""
try:
index = int(self.tamper_index.get())
if index <= 0 or index >= len(self.blockchain.chain):
messagebox.showwarning("Warning",
f"Please enter a valid block index (1-{len(self.blockchain.chain)-1})")
return
# Tamper with the block
original_data = self.blockchain.chain[index].data
self.blockchain.chain[index].data = f"TAMPERED: {original_data}"
messagebox.showinfo("🔓 Block Tampered",
f"Block #{index} has been tampered with!\n\n"
f"The data was modified but the hash was NOT recalculated.\n"
f"Try validating the chain to see the effect.\n\n"
f"Original: {original_data}\n"
f"New: {self.blockchain.chain[index].data}")
self.refresh_chain_display()
except ValueError:
messagebox.showerror("Error", "Please enter a valid number!")
def reset_blockchain(self):
"""Reset the blockchain."""
if messagebox.askyesno("Reset Blockchain",
"Are you sure you want to reset the blockchain?\n"
"This will delete all blocks except the genesis block."):
self.blockchain = Blockchain(difficulty=self.difficulty_var.get())
self.refresh_chain_display()
self.mining_status.config(text="Ready to mine", fg=self.colors['text_dim'])
def main():
"""Main entry point."""
root = tk.Tk()
# Set minimum window size
root.minsize(1000, 600)
# Center window on screen
root.update_idletasks()
width = 1200
height = 800
x = (root.winfo_screenwidth() // 2) - (width // 2)
y = (root.winfo_screenheight() // 2) - (height // 2)
root.geometry(f'{width}x{height}+{x}+{y}')
app = BlockchainGUI(root)
root.mainloop()
if __name__ == "__main__":
main()
Features
This blockchain implementation includes:
🔗 Core Blockchain Features
SHA-256 Hashing - Each block is hashed using cryptographic SHA-256
Proof of Work Mining - Blocks must be mined by finding a hash with leading zeros
Chain Validation - Verify the integrity of the entire blockchain
Tamper Detection - Any modification to a block invalidates the chain
🎨 GUI Features
Visual Block Display - See each block with all its details
Mining Animation - Real-time mining status updates
Difficulty Adjustment - Control how hard mining is (1-5)
Tamper Demo - Simulate attacks on the blockchain
Color-coded Status - Green for valid, red for tampered blocks
How to Run
bash
python blockchain.py
Screenshot Preview
The interface shows:
Left Panel: Controls for adding blocks, adjusting difficulty, validation, and tampering
Right Panel: Visual representation of the blockchain with all block details