1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
| from typing import Protocol, runtime_checkable from abc import ABC, abstractmethod import pickle from pathlib import Path
@runtime_checkable class MerkleProtocol(Protocol): """Protocol defining Merkle Tree interface""" @abstractmethod def root(self) -> bytes: """Get root hash""" pass @abstractmethod def insert(self, data: bytes) -> int: """Insert data and return index""" pass @abstractmethod def get_proof(self, index: int) -> List[bytes]: """Get inclusion proof for index""" pass @abstractmethod def verify(self, data: bytes, proof: List[bytes]) -> bool: """Verify data with proof""" pass
class ProductionMerkleSystem: """ Production-ready Merkle Tree system with: - Persistence - Cache - Monitoring - Fault tolerance """ def __init__(self, storage_path: Path, cache_size: int = 10000, backup_interval: int = 3600): self.storage_path = storage_path self.cache = LRUCache(cache_size) self.backup_interval = backup_interval self.metrics = { 'inserts': 0, 'proofs_generated': 0, 'verifications': 0, 'cache_hits': 0, 'cache_misses': 0 } storage_path.mkdir(parents=True, exist_ok=True) self.tree = self._load_or_create_tree() self._start_backup_scheduler() def _load_or_create_tree(self) -> MerkleTree: """Load existing tree or create new one""" tree_file = self.storage_path / 'tree_state.pkl' if tree_file.exists(): try: with open(tree_file, 'rb') as f: return pickle.load(f) except Exception as e: print(f"Failed to load tree: {e}. Creating new tree.") return MerkleTree([b'initial']) def _start_backup_scheduler(self): """Start periodic backup""" import threading def backup_task(): while True: time.sleep(self.backup_interval) self._backup_tree() thread = threading.Thread(target=backup_task, daemon=True) thread.start() def _backup_tree(self): """Backup tree state""" backup_file = self.storage_path / f'backup_{int(time.time())}.pkl' try: with open(backup_file, 'wb') as f: pickle.dump(self.tree, f) backups = sorted(self.storage_path.glob('backup_*.pkl')) for old_backup in backups[:-10]: old_backup.unlink() except Exception as e: print(f"Backup failed: {e}") def insert_data(self, data: bytes) -> Dict[str, Any]: """Insert data with monitoring and caching""" start_time = time.time() current_leaves = self.tree.leaves.copy() current_leaves.append(data) new_tree = MerkleTree([leaf.data for leaf in current_leaves if leaf.data]) old_root = self.tree.root.hash self.tree = new_tree new_index = len(current_leaves) - 1 proof = self.tree.get_proof(new_index) self.cache[new_index] = { 'data': data, 'proof': proof, 'timestamp': time.time() } self.metrics['inserts'] += 1 return { 'index': new_index, 'root': self.tree.root.hash.hex(), 'old_root': old_root.hex(), 'proof': proof, 'processing_time': time.time() - start_time } def get_proof_cached(self, index: int) -> Optional[Dict]: """Get proof with cache lookup""" self.metrics['proofs_generated'] += 1 if index in self.cache: self.metrics['cache_hits'] += 1 return self.cache[index] self.metrics['cache_misses'] += 1 if 0 <= index < len(self.tree.leaves): proof = self.tree.get_proof(index) result = { 'data': self.tree.leaves[index].data, 'proof': proof, 'timestamp': time.time() } self.cache[index] = result return result return None def get_metrics(self) -> Dict: """Get system metrics""" return { **self.metrics, 'tree_size': len(self.tree.leaves), 'cache_size': len(self.cache), 'storage_path': str(self.storage_path) } def verify_data(self, data: bytes, proof: List[bytes], expected_root: bytes = None) -> bool: """Verify data with proof""" self.metrics['verifications'] += 1 if expected_root is None: expected_root = self.tree.root.hash leaf_hash = sha256(data).digest() return MerkleTree.verify_proof( leaf_hash, [(h, 'right') for h in proof], expected_root, sha256 )
if __name__ == "__main__": system = ProductionMerkleSystem(Path('./merkle_storage')) for i in range(100): data = f"Transaction {i}: {random.randint(1, 1000)}".encode() result = system.insert_data(data) print(f"Inserted: {result['index']}, Root: {result['root'][:16]}...") proof_data = system.get_proof_cached(42) if proof_data: print(f"Data: {proof_data['data'][:50]}...") print(f"Proof length: {len(proof_data['proof'])} hashes") is_valid = system.verify_data( proof_data['data'], proof_data['proof'] ) print(f"Verification: {'PASS' if is_valid else 'FAIL'}") metrics = system.get_metrics() print(f"\nSystem Metrics:") for key, value in metrics.items(): print(f" {key}: {value}")
|