I'm now focusing on the core mechanism: a Distributed Hash Table (DHT). The initial goal of building a P2P file-sharing protocol has me considering how to deconstruct requests and efficiently locate files within a distributed network. I'm exploring the most efficient structures for file storage and retrieval within a DHT.
Designing the Architecture
I've been working on the architecture, specifically the node structure and message types. The K-Buckets within the routing table will use lists to represent peer "distance" based on XOR, which is pretty standard. I'm focusing on the essential message types: PING, STORE, and FIND_NODE, to lay the foundation for a functional DHT.
Adding File Sharing Functionality
I'm now integrating the file-sharing aspect. Uploads will involve hashing filenames to generate keys and storing (Key, IP:Port) pairs in the DHT. Downloads will involve querying the DHT using the hash key to retrieve the provider's IP, then establishing a direct connection for file transfer.
Implementing Core Logic
I've decided to implement a simplified Kademlia-like DHT using Python's threading and socketserver. It'll be runnable. This includes a Node class, core DHT logic for storage and lookups, and a rudimentary network simulation for demonstration purposes initially, maybe replaced with actual socket interaction. The protocol will involve file registration by hashing filenames to keys and storing (key, IP:Port) pairs. File lookups will retrieve peer addresses, and transfers will use TCP. The DHT node will have a UDP listener thread, a storage dictionary, and a recursive find_value architecture.
Simplifying Routing Logic
I'm now streamlining the DHT implementation. Full Kademlia routing is excessive, so I've chosen to implement a Kademlia-Lite approach to reduce complexity while retaining core functionality, focussing on the logical buckets and recursive search.
\n\n
My next step is to write out the structural skeleton of the code, so it's readable and able to execute. This involves defining all needed classes for this simple project. I'm focusing on key components: the DHTNode class and the P2PClient class. Within these, functions like command_store and command_find will be critical for core operations.
Focusing on Core Logic
I've simplified my implementation. It's now crucial to clearly define the separation of duties: the DHT finds the file location, and the peer provides the content. I'm leveraging UDP for DHT messages and TCP for file transfers. Data will be stored as a routing_table of peers and a data_store of hosted files. The use of hash tables is necessary for storing the meta-data associated with a peer.
Refining Search Strategy
I'm simplifying the network traversal logic. Recursive lookups are now preferred to avoid the added complexity of iterative node navigation. To streamline the project, I'm integrating a dedicated FileServer within each node to handle file downloads via TCP. I will now integrate these solutions to create the final draft.
This is a complex task that involves networking, data structures, and concurrency. To keep this understandable and runnable, I will implement a simplified version of the Kademlia protocol (the standard for P2P DHTs).
Architecture Design
The DHT Layer (UDP): Used to locate who has a specific file.
Nodes: Have unique 160-bit IDs (SHA-1).
Distance: Calculated using XOR metric (id1 ^ id2).
Operations:PING, STORE (publish mapping), FIND_VALUE (query mapping).
The File Transfer Layer (TCP): Used to actually transfer the file content once the peer is located.
Python Implementation
This implementation uses standard libraries (socket, threading, json, hashlib).
python
Simulation Script
Here is how you would run this to verify it works. This script spawns 3 nodes locally, publishes a file on Node 1, and downloads it from Node 3.
python
def run_simulation():
# 1. Create dummy file for Node A to share
with open("secret.txt", "w") as f:
f.write("This is the secret content decentralized.")
# 2. Start Node A (Bootstrap)
node_a = DHTNode('127.0.0.1', 5000)
# Monkey patch the full handler for responses
node_a.handle_dht_message = node_a.handle_dht_message_full
node_a.last_search_result = None
node_a.start()
# 3. Start Node B (Connects to A)
node_b = DHTNode('127.0.0.1', 5001, bootstrap_node=('127.0.0.1', 5000, node_a.id))
node_b.handle_dht_message = node_b.handle_dht_message_full
node_b.last_search_result = None
node_b.start()
# 4. Start Node C (Connects to B, forming a chain)
node_c = DHTNode('127.0.0.1', 5002, bootstrap_node=('127.0.0.1', 5001, node_b.id))
node_c.handle_dht_message = node_c.handle_dht_message_full
node_c.last_search_result = None
node_c.start()
time.sleep(1)
print("\n--- Network Initialized ---\n")
# 5. Node A publishes 'secret.txt'
# This will hash 'secret.txt' and store the location (Node A's IP)
# on the node closest to that hash (could be B or C)
node_a.publish_file("secret.txt")
time.sleep(1)
print("\n--- Starting Download Request from Node C ---\n")
# 6. Node C attempts to download 'secret.txt'
# Step A: Find the provider (UDP query)
filename = "secret.txt"
file_hash = str(get_hash(filename))
# Send query to known peer (B)
msg = {'type': 'FIND_VALUE', 'key': file_hash, 'node_id': node_c.id}
# In this simplified demo, we just flood neighbors
node_c.send_udp(msg, ('127.0.0.1', 5001))
# Wait for async UDP response
print("Node C waiting for DHT lookup...")
attempts = 0
while node_c.last_search_result is None and attempts < 5:
time.sleep(1)
attempts += 1
if node_c.last_search_result:
provider_ip, provider_port = node_c.last_search_result.split(':')
# Step B: Download content (TCP)
node_c.request_tcp_download(provider_ip, provider_port, filename)
# Verify content
if os.path.exists(f"downloaded_5002_{filename}"):
print("\nSUCCESS: File downloaded via P2P DHT!")
with open(f"downloaded_5002_{filename}", "r") as f:
print(f"Content: {f.read()}")
else:
print("FAILURE: Could not locate file in DHT.")
# Cleanup
os._exit(0)
if __name__ == "__main__":
try:
run_simulation()
except KeyboardInterrupt:
pass
How it Works
XOR Metric: The distance between nodes is calculated using bitwise XOR (int(id1) ^ int(id2)). This is the defining characteristic of Kademlia, allowing efficient routing.
Publishing (STORE):
Node A hashes the filename ("secret.txt") to get a Key.
Node A calculates which Node ID is closest to that Key.
Node A sends a UDP STORE message to that node containing: {Key: FileHash, Value: "127.0.0.1:6000"}.
(Note: TCP port is usually UDP port + offset).
Searching (FIND_VALUE):
Node C wants "secret.txt". It hashes the name.
It asks its neighbors (UDP).
If a neighbor has the Key in its self.data dict, it returns FOUND_VALUE.
If not, the neighbor forwards the request to the peer in its routing table closest to the key (Recurisve routing utilized here for code brevity, normally it is Iterative).
Downloading (TCP):
Once Node C receives the IP:Port, it opens a direct TCP socket to Node A.
Node A acts as a file server and streams the bytes.
Key Limitations of this Simple Implementation
Recursion vs Iteration: Real Kademlia is usually iterative (Node A asks B, B says "I don't know, ask C", Node A asks C). This script does recursive (A -> B -> C -> A) to save lines of code, but this is dangerous in large networks due to timeouts and open connections.
Buckets: Real Kademlia uses K-Buckets (lists of lists) to manage thousands of peers. This implementation uses a simple list.
Republishing: Data should expire and be republished every hour. This script stores data indefinitely in memory.
import socket
import threading
import json
import hashlib
import time
import os
import random
# Configuration
DHT_PORT_BASE = 5000
FILE_PORT_BASE = 6000
BUFFER_SIZE = 4096
def get_hash(key_flow):
"""Generates a 160-bit SHA1 hash (ID) from a string."""
return int(hashlib.sha1(key_flow.encode()).hexdigest(), 16)
def xor_distance(id1, id2):
return id1 ^ id2
class DHTNode:
def __init__(self, host, port, bootstrap_node=None):
self.host = host
self.port = port
self.id = get_hash(f"{host}:{port}")
self.peers = [] # Simplified routing table (list of tuples (host, port, id))
self.data = {} # Storage for DHT key-values {file_hash: owner_address}
# DHT Networking (UDP)
self.udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.udp_sock.bind((self.host, self.port))
# File Server (TCP)
self.tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.tcp_sock.bind((self.host, self.port + 1000)) # Offset for file port
self.tcp_sock.listen(5)
self.running = True
# Join network
if bootstrap_node:
self.peers.append(bootstrap_node)
self.bootstrap(bootstrap_node)
def start(self):
"""Start listening threads."""
threading.Thread(target=self.listen_udp, daemon=True).start()
threading.Thread(target=self.listen_tcp, daemon=True).start()
print(f"[Node {self.port}] Started using ID: {self.id}")
# --- DHT Protocol (UDP) ---
def listen_udp(self):
while self.running:
try:
msg, addr = self.udp_sock.recvfrom(BUFFER_SIZE)
data = json.loads(msg.decode())
self.handle_dht_message(data, addr)
except Exception as e:
print(f"UDP Error: {e}")
def send_udp(self, message, addr):
self.udp_sock.sendto(json.dumps(message).encode(), addr)
def handle_dht_message(self, message, addr):
msg_type = message.get('type')
# Update known peers passively
sender_id = message.get('node_id')
if sender_id and addr not in [(p[0], p[1]) for p in self.peers]:
self.peers.append((addr[0], addr[1], sender_id))
if msg_type == 'PING':
self.send_udp({'type': 'PONG', 'node_id': self.id}, addr)
elif msg_type == 'STORE':
# Store file_hash -> provider_ip:port mapping
key = message['key']
value = message['value']
self.data[key] = value
print(f"[Node {self.port}] Stored key {key[:5]}... mapped to {value}")
elif msg_type == 'FIND_VALUE':
key = message['key']
if key in self.data:
# Found the file owner
response = {'type': 'FOUND_VALUE', 'value': self.data[key], 'node_id': self.id}
self.send_udp(response, addr)
else:
# Simplified recursive lookup: Forward to closest known peer
closest_peer = self.get_closest_peer(key)
if closest_peer:
# In a real DHT, we return K-closest nodes (iterative).
# Here, strictly for demo, we forward the request (recursive).
self.send_udp(message, (closest_peer[0], closest_peer[1]))
else:
# Dead end
self.send_udp({'type': 'NOT_FOUND', 'node_id': self.id}, addr)
def get_closest_peer(self, target_key_int):
"""Finds peer with ID closest to target_key (XOR metric)."""
if not self.peers: return None
# target_key might be string in dict, convert to int if needed for math
if isinstance(target_key_int, str): target_key_int = int(target_key_int)
best_peer = min(self.peers, key=lambda p: xor_distance(p[2], target_key_int))
return best_peer
def bootstrap(self, node_addr):
self.send_udp({'type': 'PING', 'node_id': self.id}, (node_addr[0], node_addr[1]))
# --- User Actions ---
def publish_file(self, filename):
"""Announce to the DHT that this node has a file."""
if not os.path.exists(filename):
print("File does not exist.")
return
file_hash = str(get_hash(filename)) # Hash the filename to get Key
# Value is OUR specific address where we serve files (TCP port)
my_file_address = f"{self.host}:{self.port + 1000}"
msg = {
'type': 'STORE',
'key': file_hash,
'value': my_file_address,
'node_id': self.id
}
# In Kademlia, you store data on the k nodes closest to the key.
# Here, we send to our closest peer to disseminate.
target = self.get_closest_peer(int(file_hash))
if target:
self.send_udp(msg, (target[0], target[1]))
print(f"[Node {self.port}] Published {filename} to network.")
else:
# If we are alone, store locally
self.data[file_hash] = my_file_address
print(f"[Node {self.port}] Stored {filename} locally (no peers).")
def download_file(self, filename):
"""Query DHT for file location, then connect via TCP to download."""
file_hash = str(get_hash(filename))
print(f"[Node {self.port}] Searching for {filename} (Hash: {file_hash[:5]}...)")
# 1. Find who has it (UDP)
# We create a temporary listener for the response to keep code linear
found_provider = None
def wait_for_response():
nonlocal found_provider
start = time.time()
while time.time() - start < 3: # 3 sec timeout
try:
# Peek at socket or simplified shared state handle?
# Note: In a real app, use async/promises.
# This is a hacky blocking check on the main thread logic not shown here exactly.
pass
except: pass
# Sending the FIND request
msg = {'type': 'FIND_VALUE', 'key': file_hash, 'node_id': self.id}
# Send to all peers to increase odds (flooding for simplified demo)
for peer in self.peers:
self.send_udp(msg, (peer[0], peer[1]))
# NOTE: In this synchronous demo script, we can't easily await the UDP response
# inside this function without complex event loops.
# *Simulation hack*: We will sleep and assume the main UDP listener updates a variable.
# In production, use asyncio.
time.sleep(1) # Wait for responses to propagate
# Check if we found it in our local cache (populated by FOUND_VALUE response in listen_udp)
# To make this work, listen_udp needs to handle FOUND_VALUE.
# Let's modify handle_dht_message briefly to handle FOUND_VALUE response:
# (See Modification Note below code block)
# --- File Transfer (TCP) ---
def listen_tcp(self):
while self.running:
client, addr = self.tcp_sock.accept()
threading.Thread(target=self.handle_file_upload, args=(client,)).start()
def handle_file_upload(self, client_sock):
"""Sends the requested file to the connected peer."""
try:
filename = client_sock.recv(1024).decode()
if os.path.exists(filename):
client_sock.send(b"OK")
with open(filename, 'rb') as f:
while chunk := f.read(BUFFER_SIZE):
client_sock.send(chunk)
else:
client_sock.send(b"ERR")
except Exception as e:
print(f"Upload Error: {e}")
finally:
client_sock.close()
def request_tcp_download(self, ip, port, filename):
"""Connects to peer and downloads file."""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, int(port)))
s.send(filename.encode())
status = s.recv(2) # Wait for OK
if status == b"OK":
with open(f"downloaded_{self.port}_{filename}", 'wb') as f:
while True:
data = s.recv(BUFFER_SIZE)
if not data: break
f.write(data)
print(f"[Node {self.port}] Successfully downloaded {filename}")
else:
print(f"[Node {self.port}] File not found on peer.")
s.close()
except Exception as e:
print(f"[Node {self.port}] Download failed: {e}")
# Handling the response for search
def handle_search_response(self, message):
if message['type'] == 'FOUND_VALUE':
val = message['value'] # "IP:PORT"
print(f"[Node {self.port}] Found file provider: {val}")
# Trigger download
ip, port = val.split(':')
# In a real app, we need the original filename.
# We assume the user knows what they asked for.
return ip, port
return None
# Monkey patch the handle_dht_message to support client response
def handle_dht_message_full(self, message, addr):
if message['type'] == 'FOUND_VALUE':
self.last_search_result = message['value']
else:
self.handle_dht_message(message, addr)