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 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
| import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import hashlib import time import secrets from dataclasses import dataclass from typing import List, Tuple
def generate_safe_prime_params(): """Generate safe cryptographic parameters for demonstration""" p = 2**127 - 1 g = 2 q = (p - 1) // 2 return p, g, q
def mod_exp(base, exp, mod): """Fast modular exponentiation""" return pow(int(base), int(exp), int(mod))
def random_in_range(upper_bound): """Generate cryptographically secure random number in range [1, upper_bound)""" if upper_bound <= 2**63: return secrets.randbelow(upper_bound - 1) + 1 else: num_bytes = (upper_bound.bit_length() + 7) // 8 while True: random_bytes = secrets.token_bytes(num_bytes) random_num = int.from_bytes(random_bytes, 'big') if 1 <= random_num < upper_bound: return random_num
@dataclass class ProofMetrics: """Metrics for proof communication complexity""" rounds: int proof_size_bits: int computation_time: float soundness_error: float
class InteractiveSchnorrProtocol: """Interactive Schnorr protocol for discrete log""" def __init__(self, p: int, g: int, q: int, security_param: int = 128): self.p = p self.g = g self.q = q self.security_param = security_param self.repetitions = security_param def prove_interactive(self, x: int, h: int) -> ProofMetrics: """Interactive proof with multiple rounds""" start_time = time.time() total_commitment_bits = self.repetitions * 128 total_challenge_bits = self.repetitions * 1 total_response_bits = self.repetitions * 128 for _ in range(self.repetitions): r = random_in_range(self.q) commitment = mod_exp(self.g, r, self.p) challenge = secrets.randbelow(2) response = (r + challenge * x) % self.q left = mod_exp(self.g, response, self.p) right = (commitment * mod_exp(h, challenge, self.p)) % self.p assert left == right, "Verification failed" computation_time = time.time() - start_time rounds = 3 proof_size = total_commitment_bits + total_challenge_bits + total_response_bits soundness_error = 2 ** (-self.repetitions) return ProofMetrics(rounds, proof_size, computation_time, soundness_error) def prove_non_interactive(self, x: int, h: int) -> ProofMetrics: """Non-interactive proof using Fiat-Shamir heuristic""" start_time = time.time() r = random_in_range(self.q) commitment = mod_exp(self.g, r, self.p) hash_input = f"{self.g}{h}{commitment}".encode() challenge_hash = hashlib.sha256(hash_input).digest() challenge = int.from_bytes(challenge_hash, 'big') % self.q response = (r + challenge * x) % self.q left = mod_exp(self.g, response, self.p) right = (commitment * mod_exp(h, challenge, self.p)) % self.p assert left == right, "Verification failed" computation_time = time.time() - start_time rounds = 1 proof_size = 128 + 128 soundness_error = 2 ** (-128) return ProofMetrics(rounds, proof_size, computation_time, soundness_error)
class OptimizedBatchProtocol: """Optimized protocol with batching and compression""" def __init__(self, p: int, g: int, q: int, security_param: int = 128): self.p = p self.g = g self.q = q self.security_param = security_param def prove_batch(self, secrets: List[int], publics: List[int]) -> ProofMetrics: """Batch proof for multiple statements""" start_time = time.time() n = len(secrets) r = random_in_range(self.q) commitment = mod_exp(self.g, r, self.p) hash_input = f"{self.g}{''.join(map(str, publics))}{commitment}".encode() challenge = int.from_bytes(hashlib.sha256(hash_input).digest(), 'big') % self.q response = r for i, x in enumerate(secrets): weight = mod_exp(challenge, i + 1, self.q) response = (response + weight * x) % self.q computation_time = time.time() - start_time rounds = 1 proof_size = 128 + 128 soundness_error = 2 ** (-128) return ProofMetrics(rounds, proof_size, computation_time, soundness_error)
def compare_protocols(): """Compare different protocol variants""" p, g, q = generate_safe_prime_params() x = random_in_range(q) h = mod_exp(g, x, p) security_params = [32, 64, 96, 128, 160, 192, 224, 256] interactive_results = [] non_interactive_results = [] print("Testing Interactive Protocol...") for sec_param in security_params: protocol = InteractiveSchnorrProtocol(p, g, q, sec_param) metrics = protocol.prove_interactive(x, h) interactive_results.append(metrics) print(f"Security={sec_param}: Rounds={metrics.rounds}, Size={metrics.proof_size_bits} bits, Time={metrics.computation_time:.4f}s") print("\nTesting Non-Interactive Protocol...") for sec_param in security_params: protocol = InteractiveSchnorrProtocol(p, g, q, sec_param) metrics = protocol.prove_non_interactive(x, h) non_interactive_results.append(metrics) print(f"Security={sec_param}: Rounds={metrics.rounds}, Size={metrics.proof_size_bits} bits, Time={metrics.computation_time:.4f}s") print("\nTesting Batch Protocol...") batch_sizes = [1, 2, 4, 8, 16, 32, 64, 128] batch_results = [] for batch_size in batch_sizes: secrets = [random_in_range(q) for _ in range(batch_size)] publics = [mod_exp(g, secret, p) for secret in secrets] protocol = OptimizedBatchProtocol(p, g, q, 128) metrics = protocol.prove_batch(secrets, publics) batch_results.append(metrics) print(f"Batch size={batch_size}: Size={metrics.proof_size_bits} bits, Time={metrics.computation_time:.4f}s") return security_params, interactive_results, non_interactive_results, batch_sizes, batch_results
def visualize_results(security_params, interactive_results, non_interactive_results, batch_sizes, batch_results): """Create comprehensive visualizations""" fig = plt.figure(figsize=(20, 12)) ax1 = fig.add_subplot(2, 3, 1) interactive_sizes = [m.proof_size_bits for m in interactive_results] non_interactive_sizes = [m.proof_size_bits for m in non_interactive_results] ax1.plot(security_params, interactive_sizes, 'o-', label='Interactive', linewidth=2, markersize=8) ax1.plot(security_params, non_interactive_sizes, 's-', label='Non-Interactive (Fiat-Shamir)', linewidth=2, markersize=8) ax1.set_xlabel('Security Parameter λ (bits)', fontsize=12) ax1.set_ylabel('Proof Size (bits)', fontsize=12) ax1.set_title('Communication Complexity vs Security', fontsize=14, fontweight='bold') ax1.legend(fontsize=10) ax1.grid(True, alpha=0.3) ax2 = fig.add_subplot(2, 3, 2) interactive_rounds = [m.rounds for m in interactive_results] non_interactive_rounds = [m.rounds for m in non_interactive_results] ax2.bar(np.arange(len(security_params)) - 0.2, interactive_rounds, 0.4, label='Interactive', alpha=0.8) ax2.bar(np.arange(len(security_params)) + 0.2, non_interactive_rounds, 0.4, label='Non-Interactive', alpha=0.8) ax2.set_xlabel('Security Parameter λ (bits)', fontsize=12) ax2.set_ylabel('Number of Rounds', fontsize=12) ax2.set_title('Round Complexity Comparison', fontsize=14, fontweight='bold') ax2.set_xticks(np.arange(len(security_params))) ax2.set_xticklabels(security_params, rotation=45) ax2.legend(fontsize=10) ax2.grid(True, alpha=0.3, axis='y') ax3 = fig.add_subplot(2, 3, 3) interactive_times = [m.computation_time * 1000 for m in interactive_results] non_interactive_times = [m.computation_time * 1000 for m in non_interactive_results] ax3.semilogy(security_params, interactive_times, 'o-', label='Interactive', linewidth=2, markersize=8) ax3.semilogy(security_params, non_interactive_times, 's-', label='Non-Interactive', linewidth=2, markersize=8) ax3.set_xlabel('Security Parameter λ (bits)', fontsize=12) ax3.set_ylabel('Computation Time (ms)', fontsize=12) ax3.set_title('Computational Overhead', fontsize=14, fontweight='bold') ax3.legend(fontsize=10) ax3.grid(True, alpha=0.3) ax4 = fig.add_subplot(2, 3, 4) batch_sizes_list = batch_sizes batch_proof_sizes = [m.proof_size_bits for m in batch_results] naive_sizes = [256 * size for size in batch_sizes_list] ax4.plot(batch_sizes_list, naive_sizes, 'o-', label='Naive (No Batching)', linewidth=2, markersize=8) ax4.plot(batch_sizes_list, batch_proof_sizes, 's-', label='Optimized Batch', linewidth=2, markersize=8) ax4.set_xlabel('Number of Statements', fontsize=12) ax4.set_ylabel('Total Proof Size (bits)', fontsize=12) ax4.set_title('Batch Proof Efficiency', fontsize=14, fontweight='bold') ax4.legend(fontsize=10) ax4.grid(True, alpha=0.3) ax4.set_xscale('log', base=2) ax5 = fig.add_subplot(2, 3, 5) interactive_errors = [-np.log2(m.soundness_error) for m in interactive_results] non_interactive_errors = [-np.log2(m.soundness_error) for m in non_interactive_results] ax5.plot(security_params, interactive_errors, 'o-', label='Interactive', linewidth=2, markersize=8) ax5.plot(security_params, non_interactive_errors, 's-', label='Non-Interactive', linewidth=2, markersize=8) ax5.plot(security_params, security_params, '--', label='Target Security', linewidth=2, alpha=0.5) ax5.set_xlabel('Security Parameter λ (bits)', fontsize=12) ax5.set_ylabel('Achieved Security -log₂(ε)', fontsize=12) ax5.set_title('Soundness Error Analysis', fontsize=14, fontweight='bold') ax5.legend(fontsize=10) ax5.grid(True, alpha=0.3) ax6 = fig.add_subplot(2, 3, 6, projection='3d') X, Y = np.meshgrid(security_params, [1, 3]) Z_size = np.zeros_like(X, dtype=float) for i, sec_param in enumerate(security_params): Z_size[0, i] = non_interactive_results[i].proof_size_bits Z_size[1, i] = interactive_results[i].proof_size_bits surf = ax6.plot_surface(X, Y, Z_size, cmap='viridis', alpha=0.8, edgecolor='none') ax6.set_xlabel('Security λ (bits)', fontsize=10) ax6.set_ylabel('Rounds', fontsize=10) ax6.set_zlabel('Proof Size (bits)', fontsize=10) ax6.set_title('3D Trade-off: Security vs Rounds vs Size', fontsize=12, fontweight='bold') fig.colorbar(surf, ax=ax6, shrink=0.5) plt.tight_layout() plt.savefig('zkp_communication_analysis.png', dpi=300, bbox_inches='tight') plt.show() fig2 = plt.figure(figsize=(14, 6)) ax7 = fig2.add_subplot(1, 2, 1, projection='3d') batch_x = np.array(batch_sizes_list) batch_y = np.array([m.proof_size_bits for m in batch_results]) batch_z = np.array([m.computation_time * 1000 for m in batch_results]) ax7.scatter(batch_x, batch_y, batch_z, c=batch_z, cmap='plasma', s=100, alpha=0.8) ax7.plot(batch_x, batch_y, batch_z, 'b-', alpha=0.5, linewidth=2) ax7.set_xlabel('Batch Size', fontsize=11) ax7.set_ylabel('Proof Size (bits)', fontsize=11) ax7.set_zlabel('Time (ms)', fontsize=11) ax7.set_title('Batch Protocol: Size-Time Trade-off', fontsize=13, fontweight='bold') ax8 = fig2.add_subplot(1, 2, 2, projection='3d') batch_array = np.array(batch_sizes_list) efficiency_naive = batch_array * 256 efficiency_batch = np.array([m.proof_size_bits for m in batch_results]) compression_ratio = efficiency_naive / efficiency_batch X_batch = np.tile(batch_array.reshape(-1, 1), (1, 2)) Y_methods = np.tile(np.array([0, 1]).reshape(1, -1), (len(batch_array), 1)) Z_efficiency = np.column_stack([efficiency_batch, efficiency_naive]) for i in range(len(batch_array)): ax8.plot([batch_array[i], batch_array[i]], [0, 1], [efficiency_batch[i], efficiency_naive[i]], 'gray', alpha=0.3) ax8.scatter(X_batch[:, 0], Y_methods[:, 0], Z_efficiency[:, 0], c='green', s=100, label='Batch', alpha=0.8) ax8.scatter(X_batch[:, 1], Y_methods[:, 1], Z_efficiency[:, 1], c='red', s=100, label='Naive', alpha=0.8) ax8.set_xlabel('Number of Statements', fontsize=11) ax8.set_ylabel('Method', fontsize=11) ax8.set_zlabel('Total Proof Size (bits)', fontsize=11) ax8.set_yticks([0, 1]) ax8.set_yticklabels(['Batch', 'Naive']) ax8.set_title('Batching Compression Advantage', fontsize=13, fontweight='bold') ax8.legend(fontsize=10) plt.tight_layout() plt.savefig('zkp_batch_analysis_3d.png', dpi=300, bbox_inches='tight') plt.show()
def print_summary_table(security_params, interactive_results, non_interactive_results): """Print detailed comparison table""" print("\n" + "="*100) print("COMPREHENSIVE COMPARISON TABLE") print("="*100) print(f"{'Security λ':<12} {'Protocol':<20} {'Rounds':<8} {'Size (bits)':<12} {'Time (ms)':<12} {'Soundness':<15}") print("-"*100) for i, sec_param in enumerate(security_params): inter = interactive_results[i] non_inter = non_interactive_results[i] print(f"{sec_param:<12} {'Interactive':<20} {inter.rounds:<8} {inter.proof_size_bits:<12} " f"{inter.computation_time*1000:<12.4f} {inter.soundness_error:<15.2e}") print(f"{'':<12} {'Non-Interactive':<20} {non_inter.rounds:<8} {non_inter.proof_size_bits:<12} " f"{non_inter.computation_time*1000:<12.4f} {non_inter.soundness_error:<15.2e}") print("-"*100)
print("Zero-Knowledge Proof Communication Complexity Analysis") print("="*60) print("\nInitializing cryptographic parameters...")
security_params, interactive_results, non_interactive_results, batch_sizes, batch_results = compare_protocols()
print_summary_table(security_params, interactive_results, non_interactive_results)
print("\n" + "="*100) print("BATCH PROTOCOL ANALYSIS") print("="*100) print(f"{'Batch Size':<12} {'Proof Size (bits)':<20} {'Naive Size (bits)':<20} {'Compression Ratio':<20} {'Time (ms)':<12}") print("-"*100)
for i, batch_size in enumerate(batch_sizes): naive_size = batch_size * 256 actual_size = batch_results[i].proof_size_bits ratio = naive_size / actual_size time_ms = batch_results[i].computation_time * 1000 print(f"{batch_size:<12} {actual_size:<20} {naive_size:<20} {ratio:<20.2f}x {time_ms:<12.4f}")
print("\n" + "="*100) print("\nGenerating visualizations...") visualize_results(security_params, interactive_results, non_interactive_results, batch_sizes, batch_results)
print("\nAnalysis complete! Graphs saved as 'zkp_communication_analysis.png' and 'zkp_batch_analysis_3d.png'")
|