This repository was archived by the owner on Apr 13, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDragon___Edition-v120.py
More file actions
4550 lines (3567 loc) · 156 KB
/
Dragon___Edition-v120.py
File metadata and controls
4550 lines (3567 loc) · 156 KB
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Hi Realy hope you get me any Donation from Any Puzzles you Succeed to Break Using The Code_ 1NEJcwfcEm7Aax8oJNjRUnY3hEavCjNrai /////
#============================================================================================
"""
TODO: The Qiskit Code will Be Converted To Guppy ) Quantum programming language ---> NEXT We Can Use it in Q-Nexus Platformes.
=========🐉 DRAGON__CODE v120 🐉🔥=============
🏆 Ultimate Quantum ECDLP Solver - 41 optimized Modes
🔢 Features: Full Draper/QPE Oracles, Advanced Mitigation, Smart Mode Selection
💰 Donation: 1NEJcwfcEm7Aax8oJNjRUnY3hEavCjNrai
📌 Components:
- 41 quantum modes with best oracles total the First One is mod_0_porb Just for Futur_use for Google Quantum QPU 1 PHisical Qubit ~ 1 million Logical Qubits.
- Complete Draper 1D/2D/Scalar + QPE oracle implementations
- Advanced error mitigation and ZNE
- Powerful post-processing with window scanning
- Full circuit analysis and visualization
- Smart mode selection based on backend capabilities
"""
# Qiskit Imports
from IPython.display import display, HTML
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.circuit.library import QFTGate, HGate, CXGate, CCXGate, QFT
from qiskit.synthesis import synth_qft_full
from qiskit.visualization import plot_histogram
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Options
from qiskit_ibm_runtime.fake_provider import FakeVigoV2, FakeLagosV2, FakeManilaV2
from qiskit_aer import AerSimulator
from qiskit.circuit.parameterexpression import Parameter
from qiskit import synthesis, QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.synthesis import synth_qft_full
from qiskit.primitives.containers.primitive_result import PrimitiveResult
from qiskit.circuit.controlflow.break_loop import BreakLoopPlaceholder
from qiskit.circuit.library import UnitaryGate
from qiskit.circuit.library import ZGate, MCXGate, RYGate, QFTGate, HGate, CXGate, CCXGate
from qiskit.visualization import plot_histogram, plot_distribution
from qiskit_ibm_runtime import Estimator, QiskitRuntimeService, Options, SamplerV2 as Sampler
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
import logging
import math
import os
import time
import json
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict
from typing import Optional, List, Dict, Tuple
import hashlib
import base58
import pandas as pd
from math import gcd, pi, ceil, log2
from typing import Optional, Tuple, List, Dict, Union, Any
import pickle, os, time, sys, json, warnings
from datetime import datetime
from fractions import Fraction
from collections import Counter, defaultdict
from Crypto.Hash import RIPEMD160, SHA256
from ecdsa import SigningKey, SECP256k1
from Crypto.PublicKey import ECC
from ecdsa.ellipticcurve import Point, CurveFp
from ecdsa import numbertheory
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
"""
def custom_transpile(qc, backend, optimization_level=3):
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import (
Unroller,
Optimize1qGates,
CXCancellation,
SabreSwap,
SabreLayout,
TrivialLayout,
RemoveDiagonalGatesBeforeMeasure,
Depth,
Width,
Size,
CommutativeCancellation,
OptimizeSwapBeforeMeasure,
Collect2qBlocks,
ConsolidateBlocks,
GateDirection,
PadDynamicalDecoupling,
RemoveResetInZeroState,
RemoveBarriers,
CheckMap,
SetLayout,
FullAncillaAllocation,
EnlargeWithAncilla,
ApplyLayout,
BarrierBeforeFinalMeasurements,
FixedPoint,
CheckCXDirection,
CheckGateDirection,
OptimizeCliffs,
Optimize1qGatesDecomposition,
OptimizePhaseGates,
OptimizeSingleQubitGates,
OptimizeBarriers,
RemoveRedundantResets,
)
coupling_map = backend.configuration().coupling_map
basis_gates = backend.configuration().basis_gates
pass_manager = PassManager([
Unroller(basis_gates),
RemoveBarriers(),
Optimize1qGates(),
CXCancellation(),
SabreLayout(coupling_map, max_iterations=100),
SabreSwap(coupling_map, heuristic='basic', fake_run=False),
TrivialLayout(coupling_map),
RemoveDiagonalGatesBeforeMeasure(),
Depth(),
Width(),
Size(),
CommutativeCancellation(),
OptimizeSwapBeforeMeasure(),
Collect2qBlocks(),
ConsolidateBlocks(),
GateDirection(),
PadDynamicalDecoupling(),
RemoveResetInZeroState(),
CheckMap(coupling_map),
SetLayout(),
FullAncillaAllocation(),
EnlargeWithAncilla(),
ApplyLayout(),
BarrierBeforeFinalMeasurements(),
FixedPoint('depth'),
CheckCXDirection(),
CheckGateDirection(),
OptimizeCliffs(),
Optimize1qGatesDecomposition(),
OptimizePhaseGates(),
OptimizeSingleQubitGates(),
OptimizeBarriers(),
RemoveRedundantResets(),
RemoveDiagonalGatesBeforeMeasure(),
RemoveResetInZeroState(),
Depth(),
Width(),
Size(),
CommutativeCancellation(),
OptimizeSwapBeforeMeasure(),
Collect2qBlocks(),
ConsolidateBlocks(),
GateDirection(),
PadDynamicalDecoupling(),
])
return pass_manager.run(qc)
def manual_zne(qc: QuantumCircuit, backend, shots: int, config: Config, scales: List[int] = [1, 3, 5]) -> Dict[str, float]:
logger.info(f"🧪 Running Manual ZNE (Scales: {scales}) with {shots} shots...")
counts_list = []
scale_results = {}
for scale in scales:
scaled_qc = qc.copy()
scale_results[scale] = {}
if scale > 1:
logger.debug(f"Applying noise scaling factor {scale}")
for _ in range(scale - 1):
scaled_qc.barrier()
for q in scaled_qc.qubits:
scaled_qc.id(q)
logger.info(f"[⚙️] Transpiling Scale {scale}...")
tqc = custom_transpile(
scaled_qc,
backend=backend,
optimization_level=config.OPT_LEVEL
)
scale_results[scale] = {
'depth': tqc.depth(),
'size': tqc.size(),
'qubits': tqc.num_qubits,
'gates': estimate_gate_counts(tqc)
}
logger.debug(f"[📊] Scale {scale} Metrics: Depth={tqc.depth()}, Size={tqc.size()}")
sampler = Sampler(backend)
sampler = configure_sampler_options(sampler, config)
sampler.options.resilience_level = 0 # Force Raw for ZNE
job = sampler.run([tqc], shots=shots)
logger.debug(f"[📡] ZNE Scale {scale} Job ID: {job.job_id()}")
try:
job_result = job.result()
counts = safe_get_counts(job_result[0])
if counts:
counts_list.append(counts)
logger.debug(f"[✅] Scale {scale}: {len(counts)} unique measurements")
else:
logger.warning(f"[⚠️] No counts for scale {scale}")
except Exception as e:
logger.error(f"[❌] Scale {scale} failed: {e}")
continue
if not counts_list:
logger.warning("⚠️ No valid counts from any ZNE scale")
return defaultdict(float)
logger.info("📈 Performing linear extrapolation...")
extrapolated = defaultdict(float)
all_keys = set().union(*counts_list)
for key in all_keys:
vals = [c.get(key, 0) for c in counts_list]
if len(vals) > 1:
try:
fit = np.polyfit(scales[:len(vals)], vals, 1)
extrapolated[key] = max(0, fit[1])
logger.debug(f"Extrapolated {key}: {extrapolated[key]}")
except Exception as e:
logger.warning(f"Extrapolation failed for {key}: {e}")
extrapolated[key] = vals[-1] # Fallback
else:
extrapolated[key] = vals[0]
logger.info(f"📊 ZNE Results: {len(extrapolated)} extrapolated values")
return extrapolated
def run_dragon_code():
config = Config()
config.user_menu()
# Initialize engines
mitigation_engine = ErrorMitigationEngine(config)
post_processor = UniversalPostProcessor(config)
# Prompt for IBM Quantum credentials if not set
if not config.TOKEN:
config.TOKEN = input("Enter your IBM Quantum API token: ").strip()
if not config.CRN:
config.CRN = input("Enter your IBM Quantum CRN (or press Enter for 'free'): ").strip() or "free"
# Connect to IBM Quantum
logger.info("🔌 Connecting to IBM Quantum services...")
service = QiskitRuntimeService(
channel="ibm_quantum_platform",
token=config.TOKEN,
instance=config.CRN
)
# Select backend
backend = select_backend(config)
# Decompress target and compute delta
logger.info("🔐 Decompressing public key...")
Q = decompress_pubkey(config.COMPRESSED_PUBKEY_HEX)
start_point = ec_scalar_mult(config.KEYSPACE_START, G)
delta = ec_point_sub(Q, start_point)
logger.info(f" Public Key: {hex(Q.x())[:10]}...{hex(Q.x())[-10:]}")
logger.info(f" Delta: ({hex(delta.x())[:10]}..., {hex(delta.y())[-10:]})")
# Build circuit
if isinstance(config.METHOD, int):
if config.METHOD not in MODE_METADATA:
logger.warning(f"Mode {config.METHOD} does not exist. Defaulting to Mode KING (41).")
mode_id = 41
else:
mode_id = config.METHOD
else:
mode_id = 41
mode_meta = MODE_METADATA[mode_id]
logger.info(f"🛠️ Building circuit for mode {mode_id}: {mode_meta['logo']} {mode_meta['name']}")
qc = build_circuit_selector(mode_id, config.BITS, delta, config)
# Circuit analysis
mitigation_engine.analyze_circuit(qc, backend)
# Transpile with custom pass manager
logger.info("⚙️ Transpiling circuit...")
transpiled = custom_transpile(qc, backend, optimization_level=config.OPT_LEVEL)
logger.info(f" Original depth: {qc.depth()}")
logger.info(f" Transpiled depth: {transpiled.depth()}")
logger.info(f" Original size: {qc.size()}")
logger.info(f" Transpiled size: {transpiled.size()}")
logger.info(f" Qubits used: {transpiled.num_qubits}")
# Execute with mitigation
sampler = Sampler(backend)
sampler = mitigation_engine.configure_sampler_options(sampler)
if config.USE_ZNE and config.ZNE_METHOD == "manual":
logger.info("🧪 Running Manual ZNE...")
counts = manual_zne(transpiled, backend, config.SHOTS, config)
else:
logger.info(f"📡 Submitting job with {config.SHOTS} shots...")
job = sampler.run([transpiled], shots=config.SHOTS)
logger.info(f" Job ID: {job.job_id()}")
logger.info("⏳ Waiting for results...")
result = job.result()
counts = mitigation_engine.safe_get_counts(result[0])
# Display top results
logger.info("\n📊 Top Measurement Results:")
for i, (state, count) in enumerate(sorted(counts.items(), key=lambda x: x[1], reverse=True)[:10]):
logger.info(f" {i+1}. {state}: {count} counts")
# Post-processing
logger.info("🔍 Beginning comprehensive post-processing...")
candidate = post_processor.process_all_measurements(
counts, config.BITS, ORDER, config.KEYSPACE_START, Q.x(), mode_meta
)
if candidate:
logger.info(f"🎉 SUCCESS: Found candidate private key: {hex(candidate)}")
else:
logger.warning("❌ No candidates found in top results")
plot_visuals(counts, config.BITS)
"""
# ==========================================
# 1. PRESETS & CONSTANTS
# ==========================================
PRESET_17 = {
"bits": 17,
"start": 0x10000,
"pub": "033f688bae8321b8e02b7e6c0a55c2515fb25ab97d85fda842449f7bfa04e128c3",
"logo": "🔢",
"description": "Small key for testing and simulation"
}
PRESET_135 = {
"bits": 135,
"start": 0x4000000000000000000000000000000000,
"pub": "02145d2611c823a396ef6712ce0f712f09b9b4f3135e3e0aa3230fb9b6d08d1e16",
"logo": "🔐",
"description": "Standard 135-bit key for real hardware"
}
# --- secp256k1 Constants ---------------------------------------------
P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
A = 0
B = 7
Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
Gy = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8
N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
ORDER = N
CURVE = CurveFp(P, A, B)
G = Point(CURVE, Gx, Gy)
G_POINT = G
#-----------------------------------------------------------------------
# Constants for mode IDs
# KING = 41 # Special mode ID for the KING mode
# --- Logging ---
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(message)s"
)
logger = logging.getLogger(__name__)
# ==========================================
# 2. COMPLETE MATHEMATICAL UTILITIES
# ==========================================
def gcd_verbose(a: int, b: int) -> int:
"""Verbose GCD calculation with logging"""
logger.debug(f"Calculating GCD of {a} and {b}")
while b:
a, b = b, a % b
logger.debug(f"GCD result: {a}")
return a
def extended_euclidean(a: int, b: int) -> Tuple[int, int, int]:
"""Extended Euclidean algorithm for modular inverses"""
if b == 0:
return (a, 1, 0)
g, x1, y1 = extended_euclidean(b, a % b)
x = y1
y = x1 - (a // b) * y1
return (g, x, y)
def modular_inverse_verbose(a: int, m: int) -> Optional[int]:
"""Modular inverse with verbose logging"""
try:
return pow(a, -1, m)
except ValueError:
g, x, y = extended_euclidean(a, m)
if g != 1:
logger.warning(f"No inverse exists for {a} mod {m}")
return None
return x % m
def tonelli_shanks_sqrt(n: int, p: int) -> int:
"""Tonelli-Shanks square root modulo prime"""
if pow(n, (p - 1) // 2, p) != 1:
return 0
if p % 4 == 3:
return pow(n, (p + 1) // 4, p)
s, e = p - 1, 0
while s % 2 == 0:
s //= 2
e += 1
z = 2
while pow(z, (p - 1) // 2, p) != p - 1:
z += 1
x = pow(n, (s + 1) // 2, p)
b, g, r = pow(n, s, p), pow(z, s, p), e
while True:
t, m = b, 0
for m in range(r):
if t == 1:
break
t = pow(t, 2, p)
if m == 0:
return x
gs = pow(g, 2 ** (r - m - 1), p)
g = (gs * gs) % p
x = (x * gs) % p
b = (b * g) % p
r = m
def continued_fraction_approx(num: int, den: int, max_den: int = 1000000) -> Tuple[int, int]:
"""Compute continued fraction approximation with detailed logging."""
# Input validation
if den == 0:
logger.warning("Denominator is zero, returning (0, 1)")
return 0, 1
# Simplify fraction
common_divisor = gcd_verbose(num, den)
if common_divisor > 1:
simplified_num = num // common_divisor
simplified_den = den // common_divisor
logger.debug(f"Simplified {num}/{den} to {simplified_num}/{simplified_den}")
else:
simplified_num, simplified_den = num, den
# Compute continued fraction approximation
approximation = Fraction(simplified_num, simplified_den).limit_denominator(max_den)
logger.debug(f"Best approximation: {approximation.numerator}/{approximation.denominator}")
return approximation.numerator, approximation.denominator
def decompress_pubkey(hex_key: str) -> Point:
"""Decompress SECP256K1 public key"""
hex_key = hex_key.lower().replace("0x", "").strip()
if len(hex_key) not in [66, 130]:
raise ValueError(f"Invalid key length: {len(hex_key)}")
prefix = int(hex_key[:2], 16)
x = int(hex_key[2:], 16)
y_sq = (pow(x, 3, P) + B) % P
y = tonelli_shanks_sqrt(y_sq, P)
if y == 0:
raise ValueError("Invalid public key")
if (prefix == 2 and y % 2 != 0) or (prefix == 3 and y % 2 == 0):
y = P - y
return Point(CURVE, x, y)
def ec_point_add(p1: Optional[Point], p2: Optional[Point]) -> Optional[Point]:
"""Elliptic curve point addition with full validation and optimization."""
# Handle identity cases
if p1 is None:
return p2
if p2 is None:
return p1
# Extract coordinates
x1, y1 = p1.x(), p1.y()
x2, y2 = p2.x(), p2.y()
# Point at infinity check (P + (-P) = O)
if x1 == x2 and (y1 + y2) % P == 0:
return None
# Point doubling case (P + P)
if x1 == x2 and y1 == y2:
numerator = (3 * x1 * x1 + A) % P
denominator = (2 * y1) % P
inv_denominator = modular_inverse_verbose(denominator, P)
if inv_denominator is None:
return None # Division by zero
lam = (numerator * inv_denominator) % P
# Distinct points case (P + Q)
else:
numerator = (y2 - y1) % P
denominator = (x2 - x1) % P
inv_denominator = modular_inverse_verbose(denominator, P)
if inv_denominator is None:
return None # Division by zero
lam = (numerator * inv_denominator) % P
# Compute new point coordinates
x3 = (lam * lam - x1 - x2) % P
y3 = (lam * (x1 - x3) - y1) % P
return Point(CURVE, x3, y3)
# Draper adders
def draper_add_const(qc: QuantumCircuit, ctrl, target: QuantumRegister, value: int,
modulus: int = N, inverse: bool = False):
sign = -1 if inverse else 1
n = len(target)
# Apply QFT to target register
qft_reg(qc, target)
# Apply phase rotations for each qubit
for i in range(n):
angle = sign * (2 * math.pi * value) / (2 ** (n - i))
if ctrl is not None:
qc.cp(angle, ctrl, target[i])
else:
qc.p(angle, target[i])
# Apply inverse QFT
iqft_reg(qc, target)
def add_const_mod_gate(c: int, mod: int, use_matrix: bool = False, max_matrix_size: int = 64) -> UnitaryGate:
n_qubits = math.ceil(math.log2(mod)) if mod > 1 else 1
# Use matrix representation for small moduli
if mod <= max_matrix_size and use_matrix:
try:
# Create unitary matrix
mat = np.zeros((mod, mod), dtype=complex)
for x in range(mod):
mat[(x + c) % mod, x] = 1
# Pad to full dimension if needed
full_dim = 2 ** n_qubits
if full_dim > mod:
full_mat = np.eye(full_dim, dtype=complex)
full_mat[:mod, :mod] = mat
return UnitaryGate(full_mat, label=f"+{c} mod {mod}")
return UnitaryGate(mat, label=f"+{c} mod {mod}")
except Exception as e:
logger.warning(f"Matrix gate creation failed: {e}. Falling back to Draper's method")
# Fallback to Draper's QFT-based method
qc = QuantumCircuit(n_qubits, name=f"+{c} mod {mod}")
qft_reg(qc, qc.qubits)
for i in range(n_qubits):
angle = 2 * math.pi * c / (2 ** (n_qubits - i))
qc.p(angle, i)
qc.append(QFTGate(n_qubits, do_swaps=False).inverse(), range(n_qubits))
return qc.to_gate()
def ec_scalar_mult(k: int, point: Point) -> Optional[Point]:
"""Elliptic curve scalar multiplication with optimization"""
if k == 0 or point is None:
return None
result = None
addend = point
while k:
if k & 1:
result = ec_point_add(result, addend)
addend = ec_point_add(addend, addend)
k >>= 1
return result
# ==========================================
# 3. FAULT TOLERANCE & REPETITION CODES
# ==========================================
def prepare_verified_ancilla(qc: QuantumCircuit, qubit, initial_state: int = 0):
"""Prepare a verified ancilla qubit in a known state"""
qc.reset(qubit)
if initial_state == 1:
qc.x(qubit)
logger.debug(f"Prepared ancilla qubit {qubit} in state {initial_state}")
def encode_repetition(qc: QuantumCircuit, logical_qubit, ancillas: List):
"""Encode 1 logical qubit into 3 physical qubits (Bit Flip Code)"""
qc.cx(logical_qubit, ancillas[0])
qc.cx(logical_qubit, ancillas[1])
logger.debug(f"Encoded logical qubit {logical_qubit} with ancillas {ancillas}")
def decode_repetition(qc: QuantumCircuit, ancillas: List, logical_qubit):
"""Decode 3 physical qubits back to 1 logical qubit using majority vote"""
qc.cx(ancillas[0], logical_qubit)
qc.cx(ancillas[1], logical_qubit)
qc.ccx(ancillas[0], ancillas[1], logical_qubit)
logger.debug(f"Decoded logical qubit {logical_qubit} from ancillas {ancillas}")
# ==========================================
# 4. COMPLETE ORACLE IMPLEMENTATIONS
# ==========================================
def qft_reg(qc: QuantumCircuit, reg: QuantumRegister):
"""Apply QFT to register with logging"""
logger.debug(f"Applying QFT to {len(reg)} qubits")
qc.append(synth_qft_full(len(reg), do_swaps=False).to_gate(), reg)
def iqft_reg(qc: QuantumCircuit, reg: QuantumRegister):
"""Apply inverse QFT to register"""
logger.debug(f"Applying IQFT to {len(reg)} qubits")
qc.append(synth_qft_full(len(reg), do_swaps=False).inverse().to_gate(), reg)
# Matrix/Unitary scalable gate
class GeometricQPE:
"""Enhanced Geometric QPE implementation with robust point handling"""
def __init__(self, n_bits: int):
self.n = n_bits
def _oracle_geometric_phase(self, qc: QuantumCircuit, ctrl, state_reg: QuantumRegister,
point_val: Union[Point, tuple, int]):
"""Apply geometric phase oracle with comprehensive point handling"""
if point_val is None:
logger.debug("Skipping geometric phase oracle (point is None)")
return
# Robust point value extraction
if isinstance(point_val, Point):
vx = point_val.x()
elif isinstance(point_val, tuple) and len(point_val) >= 1:
vx = point_val[0]
elif isinstance(point_val, (int, np.integer)):
vx = point_val
else:
logger.warning(f"Unsupported point type: {type(point_val)}")
return
# Apply phase rotations with proper angle calculation
for i in range(self.n):
try:
angle_x = 2 * math.pi * vx / (2 ** (i + 1))
if ctrl is not None:
qc.cp(angle_x, ctrl, state_reg[i])
else:
qc.p(angle_x, state_reg[i])
except Exception as e:
logger.error(f"Failed to apply phase rotation: {e}")
continue
logger.debug(f"Applied geometric QPE oracle with vx={hex(vx)[:10]}...")
class QPEOracle:
"""Complete QPE Oracle Implementation with adaptive strategies"""
def __init__(self, n_bits: int):
self.n = n_bits
def oracle_phase(self, qc: QuantumCircuit, ctrl, point_reg: QuantumRegister,
delta_point: Union[Point, tuple], k_step: int, order: int = ORDER):
"""Apply QPE phase oracle with proper point handling"""
if delta_point is None:
logger.debug("Skipping QPE phase oracle (delta point is None)")
return
# Get coordinates properly
if isinstance(delta_point, Point):
dx = delta_point.x()
dy = delta_point.y()
elif isinstance(delta_point, tuple) and len(delta_point) >= 2:
dx, dy = delta_point[0], delta_point[1]
else:
logger.warning(f"Unsupported delta point type: {type(delta_point)}")
return
power = 1 << k_step
const_x = (dx * power) % order
if const_x != 0:
# Use more efficient scalar oracle
draper_adder_oracle_scalar(qc, ctrl, point_reg, const_x)
logger.debug(f"Applied QPE phase oracle with power={power}, const_x={hex(const_x)[:10]}...")
def oracle_geometric(self, qc: QuantumCircuit, ctrl, state_reg: QuantumRegister,
point_val: Union[Point, tuple, int]):
"""Apply geometric QPE oracle with comprehensive point handling"""
if point_val is None:
logger.debug("Skipping geometric oracle (point is None)")
return
# Robust point value extraction
if isinstance(point_val, Point):
vx = point_val.x()
elif isinstance(point_val, tuple) and len(point_val) >= 1:
vx = point_val[0]
elif isinstance(point_val, (int, np.integer)):
vx = point_val
else:
logger.warning(f"Unsupported point type: {type(point_val)}")
return
# Apply phase rotations with proper error handling
for i in range(self.n):
try:
angle_x = 2 * math.pi * vx / (2 ** (i + 1))
if ctrl is not None:
qc.cp(angle_x, ctrl, state_reg[i])
else:
qc.p(angle_x, state_reg[i])
except Exception as e:
logger.error(f"Failed to apply geometric phase: {e}")
continue
logger.debug(f"Applied geometric QPE oracle with vx={hex(vx)[:10]}...")
def draper_adder_oracle_1d_serial(qc: QuantumCircuit, ctrl, target: QuantumRegister,
dx: int, dy: int = 0):
"""Enhanced 1D Draper oracle with proper angle calculation"""
n = len(target)
qft_reg(qc, target)
for i in range(n):
try:
# More precise angle calculation
angle = 2 * math.pi * dx / (2 ** (i + 1))
if ctrl is not None:
qc.cp(angle, ctrl, target[i])
else:
qc.p(angle, target[i])
except Exception as e:
logger.error(f"Failed in 1D Draper oracle: {e}")
continue
iqft_reg(qc, target)
logger.debug(f"Applied 1D Draper oracle with dx={hex(dx)[:10]}...")
def draper_adder_oracle_2d(qc: QuantumCircuit, ctrl, target: QuantumRegister,
dx: int, dy: int):
"""Enhanced 2D Draper oracle with proper point handling"""
n = len(target)
qft_reg(qc, target)
for i in range(n):
try:
# More precise angle calculations
angle_x = 2 * math.pi * dx / (2 ** (i + 1))
angle_y = 2 * math.pi * dy / (2 ** (i + 1))
if ctrl is not None:
qc.cp(angle_x, ctrl, target[i])
qc.cp(angle_y, ctrl, target[i])
else:
# Combine angles for uncontrolled case
qc.p(angle_x + angle_y, target[i])
except Exception as e:
logger.error(f"Failed in 2D Draper oracle: {e}")
continue
iqft_reg(qc, target)
logger.debug(f"Applied 2D Draper oracle with dx={hex(dx)[:10]}, dy={hex(dy)[:10]}...")
def draper_adder_oracle_scalar(qc: QuantumCircuit, ctrl, target: QuantumRegister, scalar: int):
n = len(target)
qft_reg(qc, target)
for i in range(n):
angle = 2 * math.pi * scalar / (2 ** (n - i))
if ctrl is not None:
qc.cp(angle, ctrl, target[i])
else:
qc.p(angle, target[i])
iqft_reg(qc, target)
logger.debug(f"Applied scalar Draper oracle with scalar {scalar}")
def ft_draper_modular_adder(qc: QuantumCircuit, ctrl, target_reg: QuantumRegister,
ancilla_reg: QuantumRegister, value: int, modulus: int = N):
n = len(target_reg)
temp_overflow = ancilla_reg[0]
# Apply QFT to target register
qft_reg(qc, target_reg)
# Add the value (controlled if ctrl is provided)
draper_adder_oracle_scalar(qc, ctrl, target_reg, value)
# Subtract modulus to handle potential overflow
draper_adder_oracle_scalar(qc, None, target_reg, -modulus)
# Check for overflow
iqft_reg(qc, target_reg)
qc.cx(target_reg[-1], temp_overflow) # Set overflow flag if MSB is 1
# If overflow occurred, add modulus back
qft_reg(qc, target_reg)
qc.cx(temp_overflow, target_reg[-1]) # Conditionally flip MSB
draper_adder_oracle_scalar(qc, temp_overflow, target_reg, modulus)
qc.cx(temp_overflow, target_reg[-1]) # Restore MSB
iqft_reg(qc, target_reg)
# Reset temporary registers
qc.reset(temp_overflow)
logger.debug(f"Applied fault-tolerant Draper adder with value {value} mod {modulus}")
def ft_draper_modular_adder_omega(qc: QuantumCircuit, value: int, target_reg: QuantumRegister,
modulus: int, ancilla_reg: QuantumRegister, temp_reg: QuantumRegister):
# Simply call the standard implementation
return ft_draper_modular_adder(qc, None, target_reg, ancilla_reg, value, modulus)
def shor_oracle(qc: QuantumCircuit, a_reg: QuantumRegister, b_reg: QuantumRegister,
state_reg: QuantumRegister, points: List[Point], ancilla_reg: QuantumRegister):
"""
Shor-style oracle implementation using proper Point objects.
Args:
qc: Quantum circuit
a_reg: First control register
b_reg: Second control register
state_reg: Target state register
points: List of precomputed Point objects
ancilla_reg: Ancilla qubits for fault tolerance
"""
logger.debug("Building Shor-style oracle")
# Process a_reg controls
for i in range(len(a_reg)):
pt = points[min(i, len(points)-1)]
if pt:
# Use proper Point methods instead of tuple access
val = pt.x() % N
logger.debug(f"Applying a_reg[{i}] with point x-coordinate: {hex(val)[:10]}...")
if val:
ft_draper_modular_adder(qc, a_reg[i], state_reg, ancilla_reg, val)
# Process b_reg controls
for i in range(len(b_reg)):
pt = points[min(i, len(points)-1)]
if pt:
# Use proper Point methods instead of tuple access
val = pt.x() % N
logger.debug(f"Applying b_reg[{i}] with point x-coordinate: {hex(val)[:10]}...")
if val:
ft_draper_modular_adder(qc, b_reg[i], state_reg, ancilla_reg, val)
logger.debug("Applied Shor-style oracle construction")
def ecdlp_oracle_ab(qc: QuantumCircuit, a_reg: QuantumRegister, b_reg: QuantumRegister,
point_reg: QuantumRegister, points: List[Point], ancilla_reg: QuantumRegister):
"""
ECDLP oracle implementation for AB registers using proper Point objects.
Args:
qc: Quantum circuit
a_reg: A control register
b_reg: B control register
point_reg: Target point register
points: List of precomputed Point objects
ancilla_reg: Ancilla qubits for fault tolerance
"""
logger.debug("Building ECDLP AB oracle")
# Validate all points in the list
for pt in points:
if pt and not isinstance(pt, Point):
raise TypeError(f"Expected Point object, got {type(pt)}")
# Process a_reg controls
for i in range(len(a_reg)):
pt = points[min(i, len(points)-1)]
if pt:
# Use proper Point methods instead of tuple access
val = pt.x() % N
logger.debug(f"Applying a_reg[{i}] with point x-coordinate: {hex(val)[:10]}...")
if val:
ft_draper_modular_adder(qc, a_reg[i], point_reg, ancilla_reg, val)
# Process b_reg controls
for i in range(len(b_reg)):
pt = points[min(i, len(points)-1)]
if pt:
# Use proper Point methods instead of tuple access
val = pt.x() % N
logger.debug(f"Applying b_reg[{i}] with point x-coordinate: {hex(val)[:10]}...")
if val:
ft_draper_modular_adder(qc, b_reg[i], point_reg, ancilla_reg, val)
logger.debug("Applied ECDLP oracle")
def windowed_oracle(
qc: QuantumCircuit,
ctrl: QuantumRegister,
state_reg: QuantumRegister,
delta_point: Point,
window_size: int,
k_step: int
) -> None:
"""Apply windowed oracle using delta_point (Point object)."""
power = 1 << k_step
dx = (delta_point.x() * power) % N # Fixed: delta_point.x()
dy = (delta_point.y() * power) % N # Fixed: delta_point.y()
for j in range(window_size):
draper_adder_oracle_1d_serial(qc, ctrl[j], state_reg, dx)
logger.debug(f"Applied windowed oracle with window size {window_size}, dx={hex(dx)[:10]}")
def ec_scalar_mult(k: int, point: Point) -> Optional[Point]:
"""Scalar multiplication on elliptic curve"""
if k == 0 or point is None:
return None
result = None
addend = point
while k:
if k & 1:
result = ec_point_add(result, addend)
addend = ec_point_add(addend, addend)
k >>= 1
return result
def ec_point_negate(point: Optional[Point]) -> Optional[Point]:
"""Negate elliptic curve point"""
if point is None:
return None
return Point(CURVE, point.x(), (-point.y()) % P)
def ec_point_sub(p1: Optional[Point], p2: Optional[Point]) -> Optional[Point]:
"""Point subtraction: P1 - P2"""
return ec_point_add(p1, ec_point_negate(p2))
def ec_point_subtract(p1: Optional[Point], p2: Optional[Point]) -> Optional[Point]:
"""Alias for ec_point_sub"""
return ec_point_sub(p1, p2)
# Fixed eigenvalue_phase_oracle
def eigenvalue_phase_oracle(qc: QuantumCircuit, ctrl, target: QuantumRegister, point: Point, power: int):
"""Updated phase oracle for ECDLP context"""
scalar = (point.x() * power) % N
theta = 2 * math.pi * scalar / N
qc.cp(theta, ctrl, target[0])
def precompute_powers(delta: Point, bits: int) -> List[Optional[Point]]:
"""Precompute powers of delta (2^k * delta) for gate optimization.
Args:
delta: Point object (Q - k*G).
bits: Number of bits (e.g., 135).
Returns:
List of precomputed points (2^k * delta), or None if infinity.
"""
powers = []
curr = delta
for _ in range(bits):
powers.append(curr)
if curr is None:
# If curr is None (point at infinity), all further powers are None
powers.extend([None] * (bits - len(powers)))
break
curr = ec_point_add(curr, curr) # 2^k * delta
return powers
def precompute_points(bits: int) -> List[Point]:
"""Precompute elliptic curve points for the given bit length"""
points = []
current = G
for _ in range(bits):
points.append(current)
current = ec_point_add(current, current)
return points
def compute_offset(Q: Point, start: int) -> Point:
"""Compute delta = Q - start*G"""
start_G = ec_scalar_mult(start, G)
if start_G is None: