import hashlib
import bisect
class Node:
"""
Represents a node in the DHT.
Each node stores its local data.
"""
def __init__(self, node_id: str):
self.node_id = node_id
self.data = {} # key -> value storage
def __repr__(self):
return f"Node({self.node_id}, data_size={len(self.data)})"
class DHT:
"""
Distributed Hash Table using Consistent Hashing with Virtual Nodes.
- Uses MD5 hash modulo 2^32 for ring positions (0 to 4294967295).
- Supports multiple virtual nodes per physical node for better load balancing.
- Keys are assigned to the successor node on the hash ring.
- Node join/leave updates the ring with minimal disruption.
"""
RING_SIZE = 1 << 32 # 2^32, a large circle
def __init__(self):
self.ring = [] # Sorted list of (hash_position: int, node: Node)
def _hash(self, key: str) -> int:
"""Consistent hash function: MD5 hexdigest as int % RING_SIZE."""
hash Digest = hashlib.md5(key.encode('utf-8')).hexdigest()
return int(hash_digest, 16) % self.RING_SIZE
def add_node(self, node: Node, num_vnodes: int = 3):
"""
Add a node to the DHT with multiple virtual nodes for load balancing.
"""
for i in range(num_vnodes):
vnode_hash = self._hash(f"{node.node_id}:{i}")
vnode = (vnode_hash, node)
bisect.insort(self.ring, vnode)
print(f"Added node {node.node_id} with {num_vnodes} vnodes.")
def remove_node(self, node: Node):
"""
Remove a node and all its virtual nodes from the ring.
Note: Data on the node is NOT automatically migrated (for simplicity).
In a real DHT, data would be transferred to the new successor.
"""
before_len = len(self.ring)
self.ring = [(pos, n) for pos, n in self.ring if n != node]
print(f"Removed node {node.node_id}. Ring size: {before_len} -> {len(self.ring)}")
def find_successor(self, key_hash: int) -> Node:
"""
Find the successor node for a given key hash on the ring.
Uses binary search (bisect) for O(log N) lookup.
"""
if not self.ring:
raise ValueError("No nodes in the DHT")
pos = bisect.bisect_left(self.ring, (key_hash, None))
if pos == len(self.ring):
return self.ring[0][1] # Wrap around to first node
return self.ring[pos][1]
def put(self, key: str, value: any):
"""Store a key-value pair. Assigns to successor node."""
key_hash = self._hash(key)
successor = self.find_successor(key_hash)
successor.data[key] = value
print(f"Stored '{key}' -> {value} on {successor.node_id}")
def get(self, key: str) -> any:
"""Retrieve value for key from its successor node."""
key_hash = self._hash(key)
successor = self.find_successor(key_hash)
return successor.data.get(key)
def dump_ring(self):
"""Debug: Print the current ring state."""
print("Hash Ring (positions -> nodes):")
for pos, node in self.ring:
print(f" {pos}: {node.node_id}")
def dump_data(self):
"""Debug: Print data distribution across nodes."""
print("Data distribution:")
for node in set(n for _, n in self.ring):
if node.data:
print(f" {node}: {dict(list(node.data.items())[:3])}...") # First 3 items
else:
print(f" {node}: (empty)")
# Example usage and demonstration
if __name__ == "__main__":
dht = DHT()
# Create nodes
node1 = Node("node1")
node2 = Node("node2")
node3 = Node("node3")
# Add initial nodes
dht.add_node(node1, num_vnodes=3)
dht.add_node(node2, num_vnodes=3)
dht.add_node(node3, num_vnodes=3)
dht.dump_ring()
# Insert some data
test_keys = ["key1", "key2", "key3", "key4", "key5", "key6"]
for key in test_keys:
dht.put(key, f"value-{key}")
dht.dump_data()
# Test gets
print("\nGets:")
for key in test_keys:
value = dht.get(key)
print(f"get('{key}') = {value}")
# Simulate node join: Add node4
print("\n--- Node join ---")
node4 = Node("node4")
dht.add_node(node4, num_vnodes=3)
dht.dump_ring()
# Insert more data - should balance better
for i in range(7, 13):
key = f"key{i}"
dht.put(key, f"value-{key}")
dht.dump_data()
# Simulate node leave: Remove node2
print("\n--- Node leave ---")
dht.remove_node(node2)
dht.dump_ring()
dht.dump_data()
# Data on node2 is lost (in real impl, migrate to new successor)
print(f"get('key2') after node2 removal: {dht.get('key2')}")
Key Features
- Consistent Hashing: Keys and vnodes are hashed to a fixed ring. Successor lookup ensures even distribution.
- Virtual Nodes:
num_vnodes per physical node prevents hotspots.
- Efficient Operations:
O(log N) lookups via binary search on sorted ring.
- Fault Tolerance Demo: Node removal shows ring adapts, but data migration is left as an exercise (real DHTs like Chord/Kademlia handle this).
- Deterministic Hash: MD5-based, consistent across runs.
Run the script to see it in action! Data redistributes minimally on changes. Extend with RPC/networking for true distribution.