harshrawat18 commited on
Commit
dda4bd8
Β·
verified Β·
1 Parent(s): 87e921a

Upload folder using huggingface_hub

Browse files
Dockerfile CHANGED
@@ -29,6 +29,18 @@ RUN pip install --no-cache-dir \
29
  COPY requirements.txt .
30
  RUN pip install --no-cache-dir -r requirements.txt
31
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  # ── Layer 4a: Pre-cache Nomic Embedding model ────────────────
33
  RUN python -c "\
34
  from sentence_transformers import SentenceTransformer; \
 
29
  COPY requirements.txt .
30
  RUN pip install --no-cache-dir -r requirements.txt
31
 
32
+ # ── Layer 3.5: Build VAIKUNTHA Rust Native Extension (Sprint 45) ──────
33
+ # Install Rust toolchain (only needed at build time, not in final image)
34
+ COPY vaikuntha_bn254/ /app/vaikuntha_bn254/
35
+ RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y \
36
+ && . $HOME/.cargo/env \
37
+ && cd /app/vaikuntha_bn254 \
38
+ && maturin build --release \
39
+ && pip install --no-cache-dir target/wheels/*.whl \
40
+ && rustup self uninstall -y
41
+ # NOTE: We uninstall the Rust toolchain after building to keep the
42
+ # final image small. The compiled .so remains installed in site-packages.
43
+
44
  # ── Layer 4a: Pre-cache Nomic Embedding model ────────────────
45
  RUN python -c "\
46
  from sentence_transformers import SentenceTransformer; \
api.py CHANGED
@@ -73,11 +73,28 @@ groq_client = Groq(api_key=GROQ_API_KEY)
73
  @asynccontextmanager
74
  async def lifespan(app: FastAPI):
75
  logger.info("πŸš€ Lifespan started (lazy model loading enabled).")
 
 
 
 
 
 
76
  yield
 
 
 
 
 
 
 
77
 
78
  app = FastAPI(lifespan=lifespan)
79
  app.include_router(whatsapp_router)
80
 
 
 
 
 
81
  # --- RATE LIMITER CONFIG ---
82
  limiter = Limiter(key_func=get_remote_address)
83
  app.state.limiter = limiter
 
73
  @asynccontextmanager
74
  async def lifespan(app: FastAPI):
75
  logger.info("πŸš€ Lifespan started (lazy model loading enabled).")
76
+ try:
77
+ from verification.groth16_verifier import initialize_verification_engine
78
+ initialize_verification_engine()
79
+ logger.info("⚑ VAIKUNTHA verification engine initialized.")
80
+ except Exception as e:
81
+ logger.error(f"⚠️ Failed to initialize VAIKUNTHA verification engine: {e}")
82
  yield
83
+ # ── Shut down the VAIKUNTHA verification thread pool cleanly (Sprint 45) ──
84
+ try:
85
+ from verification.groth16_verifier import _VERIFIER_THREAD_POOL
86
+ _VERIFIER_THREAD_POOL.shutdown(wait=True)
87
+ logger.info("πŸ›‘ VAIKUNTHA verification thread pool shut down.")
88
+ except ImportError:
89
+ pass # verification module not installed β€” nothing to shut down
90
 
91
  app = FastAPI(lifespan=lifespan)
92
  app.include_router(whatsapp_router)
93
 
94
+ # ── PROJECT VAIKUNTHA Phase 4.1 β€” ZK Verification Endpoint (Sprint 45) ───
95
+ from verification.routes import router as verification_router
96
+ app.include_router(verification_router)
97
+
98
  # --- RATE LIMITER CONFIG ---
99
  limiter = Limiter(key_func=get_remote_address)
100
  app.state.limiter = limiter
requirements.txt CHANGED
@@ -46,4 +46,11 @@ numpy>=1.24.0
46
  openfisca-core>=44.0.0
47
 
48
  # --- PDF Processing (Sprint 28) ---
49
- pymupdf
 
 
 
 
 
 
 
 
46
  openfisca-core>=44.0.0
47
 
48
  # --- PDF Processing (Sprint 28) ---
49
+ pymupdf
50
+
51
+ # --- ZK-SNARK Verification Engine (Sprint 45 β€” PROJECT VAIKUNTHA Phase 4.1) ---
52
+ # The vaikuntha_bn254 native extension is installed via:
53
+ # cd vaikuntha_bn254 && maturin develop --release
54
+ # maturin is a BUILD-TIME dependency, not a runtime one.
55
+ # The compiled .so is dynamically linked at import time.
56
+ maturin>=1.7
tests/test_verification.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ═══════════════════════════════════════════════════════════════════════════════
3
+ GovBridge India β€” PROJECT VAIKUNTHA Phase 4.1
4
+ Verification Module Test Suite
5
+ ═══════════════════════════════════════════════════════════════════════════════
6
+
7
+ Tests pure deserialization logic and Pydantic validation without requiring
8
+ the Rust native extension. The Rust FFI is mocked in integration tests.
9
+ """
10
+
11
+ import pytest
12
+ from unittest.mock import patch, MagicMock
13
+
14
+ from verification.deserializer import (
15
+ deserialize_proof,
16
+ validate_public_input,
17
+ G1Point,
18
+ G2Point,
19
+ DeserializedProof,
20
+ BN254_P,
21
+ BN254_R,
22
+ PROOF_SIZE,
23
+ COORD_SIZE,
24
+ )
25
+ from verification.groth16_verifier import VerificationResult
26
+
27
+
28
+ # ════════════════════════════════════════════════════════════════════════════
29
+ # 1. DESERIALIZER TESTS
30
+ # ════════════════════════════════════════════════════════════════════════════
31
+
32
+ class TestProofDeserialization:
33
+ """Test the 256-byte proof payload deserializer."""
34
+
35
+ def _make_valid_payload(self) -> bytes:
36
+ """Create a 256-byte payload with all-zeros (valid field elements)."""
37
+ # A coordinate of all zeros is technically the additive identity,
38
+ # but it passes the field membership check (0 < p).
39
+ return b"\x00" * PROOF_SIZE
40
+
41
+ def test_valid_payload_length(self):
42
+ """256-byte payload should deserialize without error."""
43
+ payload = self._make_valid_payload()
44
+ proof = deserialize_proof(payload)
45
+ assert isinstance(proof, DeserializedProof)
46
+ assert len(proof.raw_bytes) == PROOF_SIZE
47
+
48
+ def test_short_payload_rejected(self):
49
+ """Payloads shorter than 256 bytes must be rejected."""
50
+ with pytest.raises(ValueError, match="exactly 256 bytes"):
51
+ deserialize_proof(b"\x00" * 255)
52
+
53
+ def test_long_payload_rejected(self):
54
+ """Payloads longer than 256 bytes must be rejected."""
55
+ with pytest.raises(ValueError, match="exactly 256 bytes"):
56
+ deserialize_proof(b"\x00" * 257)
57
+
58
+ def test_empty_payload_rejected(self):
59
+ """Empty payload must be rejected."""
60
+ with pytest.raises(ValueError, match="exactly 256 bytes"):
61
+ deserialize_proof(b"")
62
+
63
+ def test_coordinate_extraction_offsets(self):
64
+ """Verify that coordinates are extracted at the correct byte offsets."""
65
+ # Build a payload where each 32-byte slot has a unique marker byte
66
+ payload = bytearray(PROOF_SIZE)
67
+ for i in range(8):
68
+ payload[i * 32] = i + 1 # marker in first byte of each slot
69
+ payload = bytes(payload)
70
+
71
+ proof = deserialize_proof(payload)
72
+
73
+ # Ο€_A.x starts at offset 0
74
+ assert proof.pi_a.x[0] == 1
75
+ # Ο€_A.y starts at offset 32
76
+ assert proof.pi_a.y[0] == 2
77
+ # Ο€_B.x.c0 starts at offset 64
78
+ assert proof.pi_b.x_c0[0] == 3
79
+ # Ο€_B.x.c1 starts at offset 96
80
+ assert proof.pi_b.x_c1[0] == 4
81
+ # Ο€_B.y.c0 starts at offset 128
82
+ assert proof.pi_b.y_c0[0] == 5
83
+ # Ο€_B.y.c1 starts at offset 160
84
+ assert proof.pi_b.y_c1[0] == 6
85
+ # Ο€_C.x starts at offset 192
86
+ assert proof.pi_c.x[0] == 7
87
+ # Ο€_C.y starts at offset 224
88
+ assert proof.pi_c.y[0] == 8
89
+
90
+
91
+ class TestFieldElementValidation:
92
+ """Test that coordinates >= BN254 base field prime p are rejected."""
93
+
94
+ def test_coordinate_at_prime_rejected(self):
95
+ """A coordinate equal to p must be rejected."""
96
+ p_bytes = BN254_P.to_bytes(32, byteorder="big")
97
+ with pytest.raises(ValueError, match="base field prime"):
98
+ G1Point(x=p_bytes, y=b"\x00" * 32)
99
+
100
+ def test_coordinate_above_prime_rejected(self):
101
+ """A coordinate above p must be rejected."""
102
+ above_p = (BN254_P + 1).to_bytes(32, byteorder="big")
103
+ with pytest.raises(ValueError, match="base field prime"):
104
+ G1Point(x=above_p, y=b"\x00" * 32)
105
+
106
+ def test_coordinate_at_max_valid_accepted(self):
107
+ """A coordinate at p-1 must be accepted."""
108
+ max_valid = (BN254_P - 1).to_bytes(32, byteorder="big")
109
+ point = G1Point(x=max_valid, y=b"\x00" * 32)
110
+ assert point.x == max_valid
111
+
112
+ def test_coordinate_zero_accepted(self):
113
+ """A coordinate of zero must be accepted."""
114
+ point = G1Point(x=b"\x00" * 32, y=b"\x00" * 32)
115
+ assert point.x == b"\x00" * 32
116
+
117
+
118
+ class TestPublicInputValidation:
119
+ """Test public input (scalar field element) validation."""
120
+
121
+ def test_valid_input_zero(self):
122
+ """Zero is a valid public input."""
123
+ validate_public_input(b"\x00" * 32) # Should not raise
124
+
125
+ def test_valid_input_one(self):
126
+ """One is a valid public input."""
127
+ one = (1).to_bytes(32, byteorder="big")
128
+ validate_public_input(one) # Should not raise
129
+
130
+ def test_input_at_order_rejected(self):
131
+ """A public input equal to r must be rejected."""
132
+ r_bytes = BN254_R.to_bytes(32, byteorder="big")
133
+ with pytest.raises(ValueError, match="scalar field order"):
134
+ validate_public_input(r_bytes)
135
+
136
+ def test_input_above_order_rejected(self):
137
+ """A public input above r must be rejected."""
138
+ above_r = (BN254_R + 1).to_bytes(32, byteorder="big")
139
+ with pytest.raises(ValueError, match="scalar field order"):
140
+ validate_public_input(above_r)
141
+
142
+ def test_input_wrong_length_rejected(self):
143
+ """Public inputs must be exactly 32 bytes."""
144
+ with pytest.raises(ValueError, match="exactly 32 bytes"):
145
+ validate_public_input(b"\x00" * 31)
146
+
147
+ with pytest.raises(ValueError, match="exactly 32 bytes"):
148
+ validate_public_input(b"\x00" * 33)
149
+
150
+
151
+ # ════════════════════════════════════════════════════════════════════════════
152
+ # 2. VERIFICATION RESULT MODEL TESTS
153
+ # ════════════════════════════════════════════════════════════════════════════
154
+
155
+ class TestVerificationResult:
156
+ """Test the VerificationResult Pydantic model."""
157
+
158
+ def test_valid_result(self):
159
+ """A valid verification result should construct properly."""
160
+ result = VerificationResult(valid=True, verification_time_ms=3.142)
161
+ assert result.valid is True
162
+ assert result.verification_time_ms == 3.142
163
+ assert result.error is None
164
+
165
+ def test_invalid_result_with_error(self):
166
+ """An invalid result with an error message should construct properly."""
167
+ result = VerificationResult(
168
+ valid=False,
169
+ verification_time_ms=0.5,
170
+ error="Ο€_A: point not on curve"
171
+ )
172
+ assert result.valid is False
173
+ assert "not on curve" in result.error # type: ignore[operator]
174
+
175
+ def test_negative_time_rejected(self):
176
+ """Negative verification time must be rejected."""
177
+ with pytest.raises(Exception):
178
+ VerificationResult(valid=True, verification_time_ms=-1.0)
179
+
180
+
181
+ # ════════════════════════════════════════════════════════════════════════════
182
+ # 3. FASTAPI ROUTE TESTS (with mocked Rust extension)
183
+ # ════════════════════════════════════════════════════════════════════════════
184
+
185
+ class TestVerifyProofEndpoint:
186
+ """Test the /api/verify-proof endpoint with mocked Rust backend."""
187
+
188
+ @pytest.fixture
189
+ def client(self):
190
+ """Create a test client with the verification router mounted."""
191
+ from fastapi import FastAPI
192
+ from fastapi.testclient import TestClient
193
+ from verification.routes import router
194
+
195
+ test_app = FastAPI()
196
+ test_app.include_router(router)
197
+ return TestClient(test_app)
198
+
199
+ def _make_valid_request(self) -> dict:
200
+ """Create a valid verify-proof request body."""
201
+ return {
202
+ "proof": "00" * 256,
203
+ "public_inputs": ["00" * 32],
204
+ }
205
+
206
+ def test_valid_request_format_accepted(self, client):
207
+ """A well-formed request should not fail at the Pydantic layer."""
208
+ with patch("verification.groth16_verifier._verify_sync") as mock_verify:
209
+ mock_verify.return_value = VerificationResult(
210
+ valid=True, verification_time_ms=3.0
211
+ )
212
+ response = client.post("/api/verify-proof", json=self._make_valid_request())
213
+ assert response.status_code == 200
214
+ data = response.json()
215
+ assert data["valid"] is True
216
+
217
+ def test_short_proof_rejected(self, client):
218
+ """A proof shorter than 512 hex chars should be rejected (422)."""
219
+ body = {"proof": "00" * 255, "public_inputs": ["00" * 32]}
220
+ response = client.post("/api/verify-proof", json=body)
221
+ assert response.status_code == 422
222
+
223
+ def test_invalid_hex_rejected(self, client):
224
+ """Non-hex characters in the proof should be rejected."""
225
+ body = {"proof": "GG" * 256, "public_inputs": ["00" * 32]}
226
+ response = client.post("/api/verify-proof", json=body)
227
+ assert response.status_code == 422
228
+
229
+ def test_missing_public_inputs_rejected(self, client):
230
+ """Request without public_inputs should be rejected."""
231
+ body = {"proof": "00" * 256}
232
+ response = client.post("/api/verify-proof", json=body)
233
+ assert response.status_code == 422
234
+
235
+ def test_0x_prefix_stripped(self, client):
236
+ """Proof and inputs with 0x prefix should be accepted."""
237
+ with patch("verification.groth16_verifier._verify_sync") as mock_verify:
238
+ mock_verify.return_value = VerificationResult(
239
+ valid=True, verification_time_ms=2.0
240
+ )
241
+ body = {
242
+ "proof": "0x" + "00" * 256,
243
+ "public_inputs": ["0x" + "00" * 32],
244
+ }
245
+ response = client.post("/api/verify-proof", json=body)
246
+ assert response.status_code == 200
vaikuntha_bn254/=1.7 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Collecting maturin
2
+ Downloading maturin-1.14.1-py3-none-manylinux_2_12_x86_64.manylinux2010_x86_64.musllinux_1_1_x86_64.whl.metadata (16 kB)
3
+ Downloading maturin-1.14.1-py3-none-manylinux_2_12_x86_64.manylinux2010_x86_64.musllinux_1_1_x86_64.whl (10.6 MB)
4
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 10.6/10.6 MB 25.6 MB/s 0:00:00
5
+ Installing collected packages: maturin
6
+ Successfully installed maturin-1.14.1
vaikuntha_bn254/Cargo.lock ADDED
@@ -0,0 +1,810 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "ahash"
7
+ version = "0.8.12"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
10
+ dependencies = [
11
+ "cfg-if",
12
+ "once_cell",
13
+ "version_check",
14
+ "zerocopy",
15
+ ]
16
+
17
+ [[package]]
18
+ name = "allocator-api2"
19
+ version = "0.2.21"
20
+ source = "registry+https://github.com/rust-lang/crates.io-index"
21
+ checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
22
+
23
+ [[package]]
24
+ name = "ark-bn254"
25
+ version = "0.5.0"
26
+ source = "registry+https://github.com/rust-lang/crates.io-index"
27
+ checksum = "d69eab57e8d2663efa5c63135b2af4f396d66424f88954c21104125ab6b3e6bc"
28
+ dependencies = [
29
+ "ark-ec",
30
+ "ark-ff",
31
+ "ark-std",
32
+ ]
33
+
34
+ [[package]]
35
+ name = "ark-crypto-primitives"
36
+ version = "0.5.0"
37
+ source = "registry+https://github.com/rust-lang/crates.io-index"
38
+ checksum = "1e0c292754729c8a190e50414fd1a37093c786c709899f29c9f7daccecfa855e"
39
+ dependencies = [
40
+ "ahash",
41
+ "ark-crypto-primitives-macros",
42
+ "ark-ec",
43
+ "ark-ff",
44
+ "ark-relations",
45
+ "ark-serialize",
46
+ "ark-snark",
47
+ "ark-std",
48
+ "blake2",
49
+ "derivative",
50
+ "digest",
51
+ "fnv",
52
+ "merlin",
53
+ "rayon",
54
+ "sha2",
55
+ ]
56
+
57
+ [[package]]
58
+ name = "ark-crypto-primitives-macros"
59
+ version = "0.5.0"
60
+ source = "registry+https://github.com/rust-lang/crates.io-index"
61
+ checksum = "e7e89fe77d1f0f4fe5b96dfc940923d88d17b6a773808124f21e764dfb063c6a"
62
+ dependencies = [
63
+ "proc-macro2",
64
+ "quote",
65
+ "syn 2.0.118",
66
+ ]
67
+
68
+ [[package]]
69
+ name = "ark-ec"
70
+ version = "0.5.0"
71
+ source = "registry+https://github.com/rust-lang/crates.io-index"
72
+ checksum = "43d68f2d516162846c1238e755a7c4d131b892b70cc70c471a8e3ca3ed818fce"
73
+ dependencies = [
74
+ "ahash",
75
+ "ark-ff",
76
+ "ark-poly",
77
+ "ark-serialize",
78
+ "ark-std",
79
+ "educe",
80
+ "fnv",
81
+ "hashbrown",
82
+ "itertools",
83
+ "num-bigint",
84
+ "num-integer",
85
+ "num-traits",
86
+ "rayon",
87
+ "zeroize",
88
+ ]
89
+
90
+ [[package]]
91
+ name = "ark-ff"
92
+ version = "0.5.0"
93
+ source = "registry+https://github.com/rust-lang/crates.io-index"
94
+ checksum = "a177aba0ed1e0fbb62aa9f6d0502e9b46dad8c2eab04c14258a1212d2557ea70"
95
+ dependencies = [
96
+ "ark-ff-asm",
97
+ "ark-ff-macros",
98
+ "ark-serialize",
99
+ "ark-std",
100
+ "arrayvec",
101
+ "digest",
102
+ "educe",
103
+ "itertools",
104
+ "num-bigint",
105
+ "num-traits",
106
+ "paste",
107
+ "rayon",
108
+ "zeroize",
109
+ ]
110
+
111
+ [[package]]
112
+ name = "ark-ff-asm"
113
+ version = "0.5.0"
114
+ source = "registry+https://github.com/rust-lang/crates.io-index"
115
+ checksum = "62945a2f7e6de02a31fe400aa489f0e0f5b2502e69f95f853adb82a96c7a6b60"
116
+ dependencies = [
117
+ "quote",
118
+ "syn 2.0.118",
119
+ ]
120
+
121
+ [[package]]
122
+ name = "ark-ff-macros"
123
+ version = "0.5.0"
124
+ source = "registry+https://github.com/rust-lang/crates.io-index"
125
+ checksum = "09be120733ee33f7693ceaa202ca41accd5653b779563608f1234f78ae07c4b3"
126
+ dependencies = [
127
+ "num-bigint",
128
+ "num-traits",
129
+ "proc-macro2",
130
+ "quote",
131
+ "syn 2.0.118",
132
+ ]
133
+
134
+ [[package]]
135
+ name = "ark-groth16"
136
+ version = "0.5.0"
137
+ source = "registry+https://github.com/rust-lang/crates.io-index"
138
+ checksum = "88f1d0f3a534bb54188b8dcc104307db6c56cdae574ddc3212aec0625740fc7e"
139
+ dependencies = [
140
+ "ark-crypto-primitives",
141
+ "ark-ec",
142
+ "ark-ff",
143
+ "ark-poly",
144
+ "ark-relations",
145
+ "ark-serialize",
146
+ "ark-std",
147
+ "rayon",
148
+ ]
149
+
150
+ [[package]]
151
+ name = "ark-poly"
152
+ version = "0.5.0"
153
+ source = "registry+https://github.com/rust-lang/crates.io-index"
154
+ checksum = "579305839da207f02b89cd1679e50e67b4331e2f9294a57693e5051b7703fe27"
155
+ dependencies = [
156
+ "ahash",
157
+ "ark-ff",
158
+ "ark-serialize",
159
+ "ark-std",
160
+ "educe",
161
+ "fnv",
162
+ "hashbrown",
163
+ "rayon",
164
+ ]
165
+
166
+ [[package]]
167
+ name = "ark-relations"
168
+ version = "0.5.1"
169
+ source = "registry+https://github.com/rust-lang/crates.io-index"
170
+ checksum = "ec46ddc93e7af44bcab5230937635b06fb5744464dd6a7e7b083e80ebd274384"
171
+ dependencies = [
172
+ "ark-ff",
173
+ "ark-std",
174
+ "tracing",
175
+ "tracing-subscriber",
176
+ ]
177
+
178
+ [[package]]
179
+ name = "ark-serialize"
180
+ version = "0.5.0"
181
+ source = "registry+https://github.com/rust-lang/crates.io-index"
182
+ checksum = "3f4d068aaf107ebcd7dfb52bc748f8030e0fc930ac8e360146ca54c1203088f7"
183
+ dependencies = [
184
+ "ark-serialize-derive",
185
+ "ark-std",
186
+ "arrayvec",
187
+ "digest",
188
+ "num-bigint",
189
+ "rayon",
190
+ ]
191
+
192
+ [[package]]
193
+ name = "ark-serialize-derive"
194
+ version = "0.5.0"
195
+ source = "registry+https://github.com/rust-lang/crates.io-index"
196
+ checksum = "213888f660fddcca0d257e88e54ac05bca01885f258ccdf695bafd77031bb69d"
197
+ dependencies = [
198
+ "proc-macro2",
199
+ "quote",
200
+ "syn 2.0.118",
201
+ ]
202
+
203
+ [[package]]
204
+ name = "ark-snark"
205
+ version = "0.5.1"
206
+ source = "registry+https://github.com/rust-lang/crates.io-index"
207
+ checksum = "d368e2848c2d4c129ce7679a7d0d2d612b6a274d3ea6a13bad4445d61b381b88"
208
+ dependencies = [
209
+ "ark-ff",
210
+ "ark-relations",
211
+ "ark-serialize",
212
+ "ark-std",
213
+ ]
214
+
215
+ [[package]]
216
+ name = "ark-std"
217
+ version = "0.5.0"
218
+ source = "registry+https://github.com/rust-lang/crates.io-index"
219
+ checksum = "246a225cc6131e9ee4f24619af0f19d67761fff15d7ccc22e42b80846e69449a"
220
+ dependencies = [
221
+ "num-traits",
222
+ "rand",
223
+ "rayon",
224
+ ]
225
+
226
+ [[package]]
227
+ name = "arrayvec"
228
+ version = "0.7.7"
229
+ source = "registry+https://github.com/rust-lang/crates.io-index"
230
+ checksum = "f02882884d3e1bc524fb12c79f107f6ad0e1cfd498c536ffb494301740995dfe"
231
+
232
+ [[package]]
233
+ name = "autocfg"
234
+ version = "1.5.1"
235
+ source = "registry+https://github.com/rust-lang/crates.io-index"
236
+ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
237
+
238
+ [[package]]
239
+ name = "blake2"
240
+ version = "0.10.6"
241
+ source = "registry+https://github.com/rust-lang/crates.io-index"
242
+ checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
243
+ dependencies = [
244
+ "digest",
245
+ ]
246
+
247
+ [[package]]
248
+ name = "block-buffer"
249
+ version = "0.10.4"
250
+ source = "registry+https://github.com/rust-lang/crates.io-index"
251
+ checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
252
+ dependencies = [
253
+ "generic-array",
254
+ ]
255
+
256
+ [[package]]
257
+ name = "byteorder"
258
+ version = "1.5.0"
259
+ source = "registry+https://github.com/rust-lang/crates.io-index"
260
+ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
261
+
262
+ [[package]]
263
+ name = "cfg-if"
264
+ version = "1.0.4"
265
+ source = "registry+https://github.com/rust-lang/crates.io-index"
266
+ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
267
+
268
+ [[package]]
269
+ name = "cpufeatures"
270
+ version = "0.2.17"
271
+ source = "registry+https://github.com/rust-lang/crates.io-index"
272
+ checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
273
+ dependencies = [
274
+ "libc",
275
+ ]
276
+
277
+ [[package]]
278
+ name = "crossbeam-deque"
279
+ version = "0.8.6"
280
+ source = "registry+https://github.com/rust-lang/crates.io-index"
281
+ checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"
282
+ dependencies = [
283
+ "crossbeam-epoch",
284
+ "crossbeam-utils",
285
+ ]
286
+
287
+ [[package]]
288
+ name = "crossbeam-epoch"
289
+ version = "0.9.18"
290
+ source = "registry+https://github.com/rust-lang/crates.io-index"
291
+ checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
292
+ dependencies = [
293
+ "crossbeam-utils",
294
+ ]
295
+
296
+ [[package]]
297
+ name = "crossbeam-utils"
298
+ version = "0.8.21"
299
+ source = "registry+https://github.com/rust-lang/crates.io-index"
300
+ checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
301
+
302
+ [[package]]
303
+ name = "crypto-common"
304
+ version = "0.1.7"
305
+ source = "registry+https://github.com/rust-lang/crates.io-index"
306
+ checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
307
+ dependencies = [
308
+ "generic-array",
309
+ "typenum",
310
+ ]
311
+
312
+ [[package]]
313
+ name = "derivative"
314
+ version = "2.2.0"
315
+ source = "registry+https://github.com/rust-lang/crates.io-index"
316
+ checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b"
317
+ dependencies = [
318
+ "proc-macro2",
319
+ "quote",
320
+ "syn 1.0.109",
321
+ ]
322
+
323
+ [[package]]
324
+ name = "digest"
325
+ version = "0.10.7"
326
+ source = "registry+https://github.com/rust-lang/crates.io-index"
327
+ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
328
+ dependencies = [
329
+ "block-buffer",
330
+ "crypto-common",
331
+ "subtle",
332
+ ]
333
+
334
+ [[package]]
335
+ name = "educe"
336
+ version = "0.6.0"
337
+ source = "registry+https://github.com/rust-lang/crates.io-index"
338
+ checksum = "1d7bc049e1bd8cdeb31b68bbd586a9464ecf9f3944af3958a7a9d0f8b9799417"
339
+ dependencies = [
340
+ "enum-ordinalize",
341
+ "proc-macro2",
342
+ "quote",
343
+ "syn 2.0.118",
344
+ ]
345
+
346
+ [[package]]
347
+ name = "either"
348
+ version = "1.16.0"
349
+ source = "registry+https://github.com/rust-lang/crates.io-index"
350
+ checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
351
+
352
+ [[package]]
353
+ name = "enum-ordinalize"
354
+ version = "4.3.2"
355
+ source = "registry+https://github.com/rust-lang/crates.io-index"
356
+ checksum = "4a1091a7bb1f8f2c4b28f1fe2cef4980ca2d410a3d727d67ecc3178c9b0800f0"
357
+ dependencies = [
358
+ "enum-ordinalize-derive",
359
+ ]
360
+
361
+ [[package]]
362
+ name = "enum-ordinalize-derive"
363
+ version = "4.3.2"
364
+ source = "registry+https://github.com/rust-lang/crates.io-index"
365
+ checksum = "8ca9601fb2d62598ee17836250842873a413586e5d7ed88b356e38ddbb0ec631"
366
+ dependencies = [
367
+ "proc-macro2",
368
+ "quote",
369
+ "syn 2.0.118",
370
+ ]
371
+
372
+ [[package]]
373
+ name = "fnv"
374
+ version = "1.0.7"
375
+ source = "registry+https://github.com/rust-lang/crates.io-index"
376
+ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
377
+
378
+ [[package]]
379
+ name = "generic-array"
380
+ version = "0.14.7"
381
+ source = "registry+https://github.com/rust-lang/crates.io-index"
382
+ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
383
+ dependencies = [
384
+ "typenum",
385
+ "version_check",
386
+ ]
387
+
388
+ [[package]]
389
+ name = "hashbrown"
390
+ version = "0.15.5"
391
+ source = "registry+https://github.com/rust-lang/crates.io-index"
392
+ checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
393
+ dependencies = [
394
+ "allocator-api2",
395
+ ]
396
+
397
+ [[package]]
398
+ name = "heck"
399
+ version = "0.5.0"
400
+ source = "registry+https://github.com/rust-lang/crates.io-index"
401
+ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
402
+
403
+ [[package]]
404
+ name = "indoc"
405
+ version = "2.0.7"
406
+ source = "registry+https://github.com/rust-lang/crates.io-index"
407
+ checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706"
408
+ dependencies = [
409
+ "rustversion",
410
+ ]
411
+
412
+ [[package]]
413
+ name = "itertools"
414
+ version = "0.13.0"
415
+ source = "registry+https://github.com/rust-lang/crates.io-index"
416
+ checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
417
+ dependencies = [
418
+ "either",
419
+ ]
420
+
421
+ [[package]]
422
+ name = "keccak"
423
+ version = "0.1.6"
424
+ source = "registry+https://github.com/rust-lang/crates.io-index"
425
+ checksum = "cb26cec98cce3a3d96cbb7bced3c4b16e3d13f27ec56dbd62cbc8f39cfb9d653"
426
+ dependencies = [
427
+ "cpufeatures",
428
+ ]
429
+
430
+ [[package]]
431
+ name = "libc"
432
+ version = "0.2.186"
433
+ source = "registry+https://github.com/rust-lang/crates.io-index"
434
+ checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
435
+
436
+ [[package]]
437
+ name = "memoffset"
438
+ version = "0.9.1"
439
+ source = "registry+https://github.com/rust-lang/crates.io-index"
440
+ checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
441
+ dependencies = [
442
+ "autocfg",
443
+ ]
444
+
445
+ [[package]]
446
+ name = "merlin"
447
+ version = "3.0.0"
448
+ source = "registry+https://github.com/rust-lang/crates.io-index"
449
+ checksum = "58c38e2799fc0978b65dfff8023ec7843e2330bb462f19198840b34b6582397d"
450
+ dependencies = [
451
+ "byteorder",
452
+ "keccak",
453
+ "rand_core",
454
+ "zeroize",
455
+ ]
456
+
457
+ [[package]]
458
+ name = "num-bigint"
459
+ version = "0.4.6"
460
+ source = "registry+https://github.com/rust-lang/crates.io-index"
461
+ checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9"
462
+ dependencies = [
463
+ "num-integer",
464
+ "num-traits",
465
+ ]
466
+
467
+ [[package]]
468
+ name = "num-integer"
469
+ version = "0.1.46"
470
+ source = "registry+https://github.com/rust-lang/crates.io-index"
471
+ checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
472
+ dependencies = [
473
+ "num-traits",
474
+ ]
475
+
476
+ [[package]]
477
+ name = "num-traits"
478
+ version = "0.2.19"
479
+ source = "registry+https://github.com/rust-lang/crates.io-index"
480
+ checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
481
+ dependencies = [
482
+ "autocfg",
483
+ ]
484
+
485
+ [[package]]
486
+ name = "once_cell"
487
+ version = "1.21.4"
488
+ source = "registry+https://github.com/rust-lang/crates.io-index"
489
+ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
490
+
491
+ [[package]]
492
+ name = "paste"
493
+ version = "1.0.15"
494
+ source = "registry+https://github.com/rust-lang/crates.io-index"
495
+ checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
496
+
497
+ [[package]]
498
+ name = "pin-project-lite"
499
+ version = "0.2.17"
500
+ source = "registry+https://github.com/rust-lang/crates.io-index"
501
+ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
502
+
503
+ [[package]]
504
+ name = "portable-atomic"
505
+ version = "1.13.1"
506
+ source = "registry+https://github.com/rust-lang/crates.io-index"
507
+ checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
508
+
509
+ [[package]]
510
+ name = "ppv-lite86"
511
+ version = "0.2.21"
512
+ source = "registry+https://github.com/rust-lang/crates.io-index"
513
+ checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
514
+ dependencies = [
515
+ "zerocopy",
516
+ ]
517
+
518
+ [[package]]
519
+ name = "proc-macro2"
520
+ version = "1.0.106"
521
+ source = "registry+https://github.com/rust-lang/crates.io-index"
522
+ checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
523
+ dependencies = [
524
+ "unicode-ident",
525
+ ]
526
+
527
+ [[package]]
528
+ name = "pyo3"
529
+ version = "0.22.6"
530
+ source = "registry+https://github.com/rust-lang/crates.io-index"
531
+ checksum = "f402062616ab18202ae8319da13fa4279883a2b8a9d9f83f20dbade813ce1884"
532
+ dependencies = [
533
+ "cfg-if",
534
+ "indoc",
535
+ "libc",
536
+ "memoffset",
537
+ "once_cell",
538
+ "portable-atomic",
539
+ "pyo3-build-config",
540
+ "pyo3-ffi",
541
+ "pyo3-macros",
542
+ "unindent",
543
+ ]
544
+
545
+ [[package]]
546
+ name = "pyo3-build-config"
547
+ version = "0.22.6"
548
+ source = "registry+https://github.com/rust-lang/crates.io-index"
549
+ checksum = "b14b5775b5ff446dd1056212d778012cbe8a0fbffd368029fd9e25b514479c38"
550
+ dependencies = [
551
+ "once_cell",
552
+ "target-lexicon",
553
+ ]
554
+
555
+ [[package]]
556
+ name = "pyo3-ffi"
557
+ version = "0.22.6"
558
+ source = "registry+https://github.com/rust-lang/crates.io-index"
559
+ checksum = "9ab5bcf04a2cdcbb50c7d6105de943f543f9ed92af55818fd17b660390fc8636"
560
+ dependencies = [
561
+ "libc",
562
+ "pyo3-build-config",
563
+ ]
564
+
565
+ [[package]]
566
+ name = "pyo3-macros"
567
+ version = "0.22.6"
568
+ source = "registry+https://github.com/rust-lang/crates.io-index"
569
+ checksum = "0fd24d897903a9e6d80b968368a34e1525aeb719d568dba8b3d4bfa5dc67d453"
570
+ dependencies = [
571
+ "proc-macro2",
572
+ "pyo3-macros-backend",
573
+ "quote",
574
+ "syn 2.0.118",
575
+ ]
576
+
577
+ [[package]]
578
+ name = "pyo3-macros-backend"
579
+ version = "0.22.6"
580
+ source = "registry+https://github.com/rust-lang/crates.io-index"
581
+ checksum = "36c011a03ba1e50152b4b394b479826cad97e7a21eb52df179cd91ac411cbfbe"
582
+ dependencies = [
583
+ "heck",
584
+ "proc-macro2",
585
+ "pyo3-build-config",
586
+ "quote",
587
+ "syn 2.0.118",
588
+ ]
589
+
590
+ [[package]]
591
+ name = "quote"
592
+ version = "1.0.46"
593
+ source = "registry+https://github.com/rust-lang/crates.io-index"
594
+ checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
595
+ dependencies = [
596
+ "proc-macro2",
597
+ ]
598
+
599
+ [[package]]
600
+ name = "rand"
601
+ version = "0.8.6"
602
+ source = "registry+https://github.com/rust-lang/crates.io-index"
603
+ checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a"
604
+ dependencies = [
605
+ "rand_chacha",
606
+ "rand_core",
607
+ ]
608
+
609
+ [[package]]
610
+ name = "rand_chacha"
611
+ version = "0.3.1"
612
+ source = "registry+https://github.com/rust-lang/crates.io-index"
613
+ checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
614
+ dependencies = [
615
+ "ppv-lite86",
616
+ "rand_core",
617
+ ]
618
+
619
+ [[package]]
620
+ name = "rand_core"
621
+ version = "0.6.4"
622
+ source = "registry+https://github.com/rust-lang/crates.io-index"
623
+ checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
624
+
625
+ [[package]]
626
+ name = "rayon"
627
+ version = "1.12.0"
628
+ source = "registry+https://github.com/rust-lang/crates.io-index"
629
+ checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
630
+ dependencies = [
631
+ "either",
632
+ "rayon-core",
633
+ ]
634
+
635
+ [[package]]
636
+ name = "rayon-core"
637
+ version = "1.13.0"
638
+ source = "registry+https://github.com/rust-lang/crates.io-index"
639
+ checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
640
+ dependencies = [
641
+ "crossbeam-deque",
642
+ "crossbeam-utils",
643
+ ]
644
+
645
+ [[package]]
646
+ name = "rustversion"
647
+ version = "1.0.22"
648
+ source = "registry+https://github.com/rust-lang/crates.io-index"
649
+ checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
650
+
651
+ [[package]]
652
+ name = "sha2"
653
+ version = "0.10.9"
654
+ source = "registry+https://github.com/rust-lang/crates.io-index"
655
+ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
656
+ dependencies = [
657
+ "cfg-if",
658
+ "cpufeatures",
659
+ "digest",
660
+ ]
661
+
662
+ [[package]]
663
+ name = "subtle"
664
+ version = "2.6.1"
665
+ source = "registry+https://github.com/rust-lang/crates.io-index"
666
+ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
667
+
668
+ [[package]]
669
+ name = "syn"
670
+ version = "1.0.109"
671
+ source = "registry+https://github.com/rust-lang/crates.io-index"
672
+ checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
673
+ dependencies = [
674
+ "proc-macro2",
675
+ "quote",
676
+ "unicode-ident",
677
+ ]
678
+
679
+ [[package]]
680
+ name = "syn"
681
+ version = "2.0.118"
682
+ source = "registry+https://github.com/rust-lang/crates.io-index"
683
+ checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
684
+ dependencies = [
685
+ "proc-macro2",
686
+ "quote",
687
+ "unicode-ident",
688
+ ]
689
+
690
+ [[package]]
691
+ name = "target-lexicon"
692
+ version = "0.12.16"
693
+ source = "registry+https://github.com/rust-lang/crates.io-index"
694
+ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
695
+
696
+ [[package]]
697
+ name = "tracing"
698
+ version = "0.1.44"
699
+ source = "registry+https://github.com/rust-lang/crates.io-index"
700
+ checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
701
+ dependencies = [
702
+ "pin-project-lite",
703
+ "tracing-core",
704
+ ]
705
+
706
+ [[package]]
707
+ name = "tracing-core"
708
+ version = "0.1.36"
709
+ source = "registry+https://github.com/rust-lang/crates.io-index"
710
+ checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
711
+ dependencies = [
712
+ "once_cell",
713
+ "valuable",
714
+ ]
715
+
716
+ [[package]]
717
+ name = "tracing-subscriber"
718
+ version = "0.2.25"
719
+ source = "registry+https://github.com/rust-lang/crates.io-index"
720
+ checksum = "0e0d2eaa99c3c2e41547cfa109e910a68ea03823cccad4a0525dcbc9b01e8c71"
721
+ dependencies = [
722
+ "tracing-core",
723
+ ]
724
+
725
+ [[package]]
726
+ name = "typenum"
727
+ version = "1.20.1"
728
+ source = "registry+https://github.com/rust-lang/crates.io-index"
729
+ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
730
+
731
+ [[package]]
732
+ name = "unicode-ident"
733
+ version = "1.0.24"
734
+ source = "registry+https://github.com/rust-lang/crates.io-index"
735
+ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
736
+
737
+ [[package]]
738
+ name = "unindent"
739
+ version = "0.2.4"
740
+ source = "registry+https://github.com/rust-lang/crates.io-index"
741
+ checksum = "7264e107f553ccae879d21fbea1d6724ac785e8c3bfc762137959b5802826ef3"
742
+
743
+ [[package]]
744
+ name = "vaikuntha_bn254"
745
+ version = "0.1.0"
746
+ dependencies = [
747
+ "ark-bn254",
748
+ "ark-ec",
749
+ "ark-ff",
750
+ "ark-groth16",
751
+ "ark-relations",
752
+ "ark-serialize",
753
+ "ark-snark",
754
+ "ark-std",
755
+ "num-bigint",
756
+ "once_cell",
757
+ "pyo3",
758
+ ]
759
+
760
+ [[package]]
761
+ name = "valuable"
762
+ version = "0.1.1"
763
+ source = "registry+https://github.com/rust-lang/crates.io-index"
764
+ checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
765
+
766
+ [[package]]
767
+ name = "version_check"
768
+ version = "0.9.5"
769
+ source = "registry+https://github.com/rust-lang/crates.io-index"
770
+ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
771
+
772
+ [[package]]
773
+ name = "zerocopy"
774
+ version = "0.8.52"
775
+ source = "registry+https://github.com/rust-lang/crates.io-index"
776
+ checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f"
777
+ dependencies = [
778
+ "zerocopy-derive",
779
+ ]
780
+
781
+ [[package]]
782
+ name = "zerocopy-derive"
783
+ version = "0.8.52"
784
+ source = "registry+https://github.com/rust-lang/crates.io-index"
785
+ checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930"
786
+ dependencies = [
787
+ "proc-macro2",
788
+ "quote",
789
+ "syn 2.0.118",
790
+ ]
791
+
792
+ [[package]]
793
+ name = "zeroize"
794
+ version = "1.9.0"
795
+ source = "registry+https://github.com/rust-lang/crates.io-index"
796
+ checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
797
+ dependencies = [
798
+ "zeroize_derive",
799
+ ]
800
+
801
+ [[package]]
802
+ name = "zeroize_derive"
803
+ version = "1.5.0"
804
+ source = "registry+https://github.com/rust-lang/crates.io-index"
805
+ checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
806
+ dependencies = [
807
+ "proc-macro2",
808
+ "quote",
809
+ "syn 2.0.118",
810
+ ]
vaikuntha_bn254/Cargo.toml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ name = "vaikuntha_bn254"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+ description = "GovBridge VAIKUNTHA β€” BN254 Groth16 verifier (PyO3 native extension)"
6
+
7
+ [lib]
8
+ name = "vaikuntha_bn254"
9
+ crate-type = ["cdylib"]
10
+
11
+ [dependencies]
12
+ pyo3 = { version = "0.22", features = ["extension-module"] }
13
+ ark-bn254 = "0.5"
14
+ ark-ec = "0.5"
15
+ ark-ff = "0.5"
16
+ ark-groth16 = "0.5"
17
+ ark-serialize = "0.5"
18
+ ark-std = "0.5"
19
+ ark-relations = "0.5"
20
+ ark-snark = "0.5"
21
+ num-bigint = "0.4"
22
+ once_cell = "1.19"
23
+
24
+ [profile.release]
25
+ opt-level = 3
26
+ lto = "fat"
27
+ codegen-units = 1
28
+ strip = true
vaikuntha_bn254/pyproject.toml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["maturin>=1.7,<2.0"]
3
+ build-backend = "maturin"
4
+
5
+ [project]
6
+ name = "vaikuntha_bn254"
7
+ version = "0.1.0"
8
+ requires-python = ">=3.10"
9
+
10
+ [tool.maturin]
11
+ features = ["pyo3/extension-module"]
vaikuntha_bn254/src/lib.rs ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! ═══════════════════════════════════════════════════════════════════════════
2
+ //! GovBridge India β€” PROJECT VAIKUNTHA Phase 4.1
3
+ //! BN254 Groth16 Verification Engine (Rust/PyO3 Native Extension)
4
+ //! ═══════════════════════════════════════════════════════════════════════════
5
+ //!
6
+ //! This module exposes two functions to Python:
7
+ //!
8
+ //! 1. `validate_point_g1(x: bytes, y: bytes) -> bool`
9
+ //! Deserializes x, y as Fq elements, checks the affine point is on the
10
+ //! BN254 G₁ curve (YΒ² = XΒ³ + 3) AND in the prime-order r subgroup.
11
+ //!
12
+ //! 2. `verify_groth16(proof_bytes: bytes, public_inputs: list[bytes],
13
+ //! vkey_bytes: bytes) -> bool`
14
+ //! Full Groth16 verification: deserializes the proof, accumulates the
15
+ //! public-input linear combination, evaluates the pairing equation.
16
+ //! The GIL is RELEASED for the entire pairing computation.
17
+ //!
18
+ //! ARCHITECTURAL LAWS:
19
+ //! - py.allow_threads() wraps ALL arithmetic heavier than O(1).
20
+ //! - All coordinate inputs are BIG-ENDIAN 32-byte field elements.
21
+ //! - Subgroup checks use scalar multiplication by r (not cofactor tricks).
22
+ //! - Invalid points produce Python ValueError, never panic.
23
+ //! ═══════════════════════════════════════════════════════════════════════════
24
+
25
+ use pyo3::prelude::*;
26
+ use pyo3::exceptions::PyValueError;
27
+ use pyo3::types::PyBytes;
28
+
29
+ use ark_bn254::{Bn254, Fq, Fq2, Fr, G1Affine, G2Affine, G1Projective};
30
+ use ark_ec::{AffineRepr, CurveGroup, Group};
31
+ use ark_ff::{BigInteger256, PrimeField, BigInteger};
32
+ use ark_groth16::{Groth16, Proof, VerifyingKey, PreparedVerifyingKey};
33
+ use ark_snark::SNARK;
34
+ use ark_std::Zero;
35
+ use num_bigint::BigUint;
36
+ use std::sync::RwLock;
37
+
38
+ // Global lock for the PreparedVerifyingKey to prevent cyclotomic CPU burn on every request.
39
+ static GLOBAL_PVK: RwLock<Option<PreparedVerifyingKey<Bn254>>> = RwLock::new(None);
40
+
41
+ // ═══════════════════════════════════════════════════════════════════════════
42
+ // SECTION 1: Field Element Deserialization (Big-Endian β†’ ark-ff)
43
+ // ═══════════════════════════════════════════════════════════════════════════
44
+
45
+ /// Converts a 32-byte big-endian slice to an ark-ff Fq element.
46
+ /// Returns Err if the value >= p (the BN254 base field prime).
47
+ fn bytes_to_fq(data: &[u8]) -> Result<Fq, String> {
48
+ if data.len() != 32 {
49
+ return Err(format!("Fq: expected 32 bytes, got {}", data.len()));
50
+ }
51
+ // ark-ff BigInteger256 expects little-endian u64 limbs
52
+ let val = BigUint::from_bytes_be(data);
53
+ let limbs = val.to_u64_digits();
54
+ let mut arr = [0u64; 4];
55
+ for (i, &limb) in limbs.iter().enumerate().take(4) {
56
+ arr[i] = limb;
57
+ }
58
+ let big = BigInteger256::new(arr);
59
+ Fq::from_bigint(big).ok_or_else(|| "Fq: value >= field modulus p".to_string())
60
+ }
61
+
62
+ /// Converts a 32-byte big-endian slice to an ark-ff Fr element (scalar field).
63
+ fn bytes_to_fr(data: &[u8]) -> Result<Fr, String> {
64
+ if data.len() != 32 {
65
+ return Err(format!("Fr: expected 32 bytes, got {}", data.len()));
66
+ }
67
+ let val = BigUint::from_bytes_be(data);
68
+ let limbs = val.to_u64_digits();
69
+ let mut arr = [0u64; 4];
70
+ for (i, &limb) in limbs.iter().enumerate().take(4) {
71
+ arr[i] = limb;
72
+ }
73
+ let big = BigInteger256::new(arr);
74
+ Fr::from_bigint(big).ok_or_else(|| "Fr: value >= scalar field order r".to_string())
75
+ }
76
+
77
+ // ═══════════════════════════════════════════════════════════════════════════
78
+ // SECTION 2: Point Deserialization with Subgroup Checks
79
+ // ═══════════════════════════════════════════════════════════════════════════
80
+
81
+ /// Deserializes a G₁ affine point from two 32-byte big-endian coordinates.
82
+ /// Performs:
83
+ /// 1. Field membership check (x, y < p)
84
+ /// 2. Curve equation check: yΒ² ≑ xΒ³ + 3 (mod p)
85
+ /// 3. Subgroup check: [r]P == O (point at infinity)
86
+ ///
87
+ /// The subgroup check prevents twisted-curve / small-subgroup attacks where
88
+ /// an attacker provides a point on a curve with the same equation but wrong
89
+ /// embedding degree, or a point in a low-order subgroup of the trace-zero
90
+ /// subgroup.
91
+ fn deserialize_g1(x_bytes: &[u8], y_bytes: &[u8]) -> Result<G1Affine, String> {
92
+ let x = bytes_to_fq(x_bytes)?;
93
+ let y = bytes_to_fq(y_bytes)?;
94
+
95
+ // Construct the affine point β€” ark-ec checks yΒ² = xΒ³ + b automatically
96
+ let point = G1Affine::new_unchecked(x, y);
97
+
98
+ // Explicit curve equation check
99
+ if !point.is_on_curve() {
100
+ return Err("G1: point not on curve (yΒ² β‰  xΒ³ + 3 mod p)".to_string());
101
+ }
102
+
103
+ // Subgroup check: [r]P must be the identity
104
+ if !point.is_in_correct_subgroup_assuming_on_curve() {
105
+ return Err("G1: point not in prime-order subgroup ([r]P β‰  O)".to_string());
106
+ }
107
+
108
+ Ok(point)
109
+ }
110
+
111
+ /// Deserializes a Gβ‚‚ affine point from four 32-byte big-endian coordinates.
112
+ /// Gβ‚‚ lives over Fq2 = Fq[u] / (uΒ² + 1).
113
+ ///
114
+ /// Wire format from ZkProofExporter (see gov_frontend/src/lib/ZkProofExporter.ts):
115
+ /// pi_B.x = (c0, c1) where Fq2 element = c0 + c1Β·u
116
+ /// pi_B.y = (c0, c1) where Fq2 element = c0 + c1Β·u
117
+ ///
118
+ /// CRITICAL: The ZkProofExporter stores G2 x-coordinate as [x.c0, x.c1] at
119
+ /// byte offsets [64..95, 96..127] and y-coordinate as [y.c0, y.c1] at
120
+ /// [128..159, 160..191]. This is the RAW layout β€” NOT the snarkjs-swizzled
121
+ /// [c1, c0] order used in toGroth16Json(). We read the raw 256-byte buffer.
122
+ fn deserialize_g2(
123
+ x_c0_bytes: &[u8],
124
+ x_c1_bytes: &[u8],
125
+ y_c0_bytes: &[u8],
126
+ y_c1_bytes: &[u8],
127
+ ) -> Result<G2Affine, String> {
128
+ let x_c0 = bytes_to_fq(x_c0_bytes)?;
129
+ let x_c1 = bytes_to_fq(x_c1_bytes)?;
130
+ let y_c0 = bytes_to_fq(y_c0_bytes)?;
131
+ let y_c1 = bytes_to_fq(y_c1_bytes)?;
132
+
133
+ let x = Fq2::new(x_c0, x_c1);
134
+ let y = Fq2::new(y_c0, y_c1);
135
+
136
+ let point = G2Affine::new_unchecked(x, y);
137
+
138
+ if !point.is_on_curve() {
139
+ return Err("G2: point not on twisted curve".to_string());
140
+ }
141
+
142
+ if !point.is_in_correct_subgroup_assuming_on_curve() {
143
+ return Err("G2: point not in prime-order subgroup ([r]P β‰  O)".to_string());
144
+ }
145
+
146
+ Ok(point)
147
+ }
148
+
149
+ // ═══════════════════════════════════════════════════════════════════════════
150
+ // SECTION 3: Groth16 Verification Core
151
+ // ═══════════════════════════════════════════════════════════════════════════
152
+
153
+ /// Deserializes the verification key from a packed binary format.
154
+ ///
155
+ /// VKey binary layout (big-endian, each coordinate = 32 bytes):
156
+ /// [ 0.. 63] alpha_g1 (G1: x, y)
157
+ /// [ 64..191] beta_g2 (G2: x.c0, x.c1, y.c0, y.c1)
158
+ /// [192..319] gamma_g2 (G2: x.c0, x.c1, y.c0, y.c1)
159
+ /// [320..447] delta_g2 (G2: x.c0, x.c1, y.c0, y.c1)
160
+ /// [448..] IC points (G1: x, y) Γ— (num_public_inputs + 1)
161
+ fn deserialize_vkey(data: &[u8], num_public_inputs: usize) -> Result<VerifyingKey<Bn254>, String> {
162
+ let expected_len = 448 + (num_public_inputs + 1) * 64;
163
+ if data.len() < expected_len {
164
+ return Err(format!(
165
+ "VKey: expected >= {} bytes for {} public inputs, got {}",
166
+ expected_len, num_public_inputs, data.len()
167
+ ));
168
+ }
169
+
170
+ let alpha_g1 = deserialize_g1(&data[0..32], &data[32..64])?;
171
+ let beta_g2 = deserialize_g2(
172
+ &data[64..96], &data[96..128], &data[128..160], &data[160..192],
173
+ )?;
174
+ let gamma_g2 = deserialize_g2(
175
+ &data[192..224], &data[224..256], &data[256..288], &data[288..320],
176
+ )?;
177
+ let delta_g2 = deserialize_g2(
178
+ &data[320..352], &data[352..384], &data[384..416], &data[416..448],
179
+ )?;
180
+
181
+ let mut gamma_abc_g1 = Vec::with_capacity(num_public_inputs + 1);
182
+ for i in 0..=num_public_inputs {
183
+ let offset = 448 + i * 64;
184
+ let ic_point = deserialize_g1(&data[offset..offset + 32], &data[offset + 32..offset + 64])?;
185
+ gamma_abc_g1.push(ic_point);
186
+ }
187
+
188
+ Ok(VerifyingKey {
189
+ alpha_g1,
190
+ beta_g2,
191
+ gamma_g2,
192
+ delta_g2,
193
+ gamma_abc_g1,
194
+ })
195
+ }
196
+
197
+ /// Core Groth16 verification with unrolled pairing.
198
+ ///
199
+ /// Computes:
200
+ /// L = IC[0] + Ξ£ (public_inputs[i] Γ— IC[i+1])
201
+ ///
202
+ /// Then checks the pairing equation:
203
+ /// e(Ο€_A, Ο€_B) == e(Ξ±, Ξ²) Β· e(L, Ξ³) Β· e(Ο€_C, Ξ΄)
204
+ ///
205
+ /// Which is equivalent to checking:
206
+ /// e(Ο€_A, Ο€_B) Β· e(-L, Ξ³) Β· e(-Ο€_C, Ξ΄) == e(Ξ±, Ξ²)
207
+ fn verify_proof_inner(
208
+ proof: &Proof<Bn254>,
209
+ pvk: &PreparedVerifyingKey<Bn254>,
210
+ public_inputs: &[Fr],
211
+ ) -> Result<bool, String> {
212
+ if public_inputs.len() + 1 != pvk.vk.gamma_abc_g1.len() {
213
+ return Err("Mismatched number of public inputs".to_string());
214
+ }
215
+
216
+ // 1. Accumulate public signals using strict w=5 MSM
217
+ let msm_result = strict_w5_msm(&pvk.vk.gamma_abc_g1[1..], public_inputs);
218
+
219
+ // 2. Add to IC_0 (base point)
220
+ let g_ic = pvk.vk.gamma_abc_g1[0].into_group() + msm_result;
221
+
222
+ // 3. Evaluate multi-pairing
223
+ use ark_ec::pairing::Pairing;
224
+ let a1: <Bn254 as Pairing>::G1Prepared = proof.a.into();
225
+ let b1: <Bn254 as Pairing>::G2Prepared = proof.b.into();
226
+ let a2: <Bn254 as Pairing>::G1Prepared = (-g_ic.into_affine()).into();
227
+ let b2 = pvk.gamma_g2_neg_pc.clone();
228
+ let a3: <Bn254 as Pairing>::G1Prepared = (-proof.c).into();
229
+ let b3 = pvk.delta_g2_neg_pc.clone();
230
+
231
+ let pairing = Bn254::multi_pairing([a1, a2, a3], [b1, b2, b3]);
232
+
233
+ Ok(pairing.0 == pvk.alpha_g1_beta_g2)
234
+ }
235
+
236
+ /// Manually unrolls a w=5 windowed Pippenger MSM to protect the L1 cache.
237
+ /// Each 254-bit scalar is divided into 5-bit windows, accumulating into 31 buckets.
238
+ fn strict_w5_msm(bases: &[G1Affine], scalars: &[Fr]) -> G1Projective {
239
+ const W: usize = 5;
240
+ const NUM_BUCKETS: usize = (1 << W) - 1;
241
+ let mut res = G1Projective::zero();
242
+
243
+ let num_bits = Fr::MODULUS_BIT_SIZE as usize; // 254
244
+ let num_windows = (num_bits + W - 1) / W;
245
+
246
+ for window in (0..num_windows).rev() {
247
+ if window != num_windows - 1 {
248
+ for _ in 0..W {
249
+ res.double_in_place();
250
+ }
251
+ }
252
+
253
+ let mut buckets = vec![G1Projective::zero(); NUM_BUCKETS];
254
+
255
+ for (base, scalar) in bases.iter().zip(scalars.iter()) {
256
+ let bigint = scalar.into_bigint();
257
+ let mut window_val = 0usize;
258
+ for b in 0..W {
259
+ let bit_idx = window * W + b;
260
+ if bit_idx < num_bits {
261
+ if bigint.get_bit(bit_idx) {
262
+ window_val |= 1 << b;
263
+ }
264
+ }
265
+ }
266
+ if window_val > 0 {
267
+ buckets[window_val - 1] += base;
268
+ }
269
+ }
270
+
271
+ let mut running_sum = G1Projective::zero();
272
+ for bucket in buckets.iter().rev() {
273
+ running_sum += bucket;
274
+ res += running_sum;
275
+ }
276
+ }
277
+ res
278
+ }
279
+
280
+ // ═══════════════════════════════════════════════════════════════════════════
281
+ // SECTION 4: PyO3 Python Bindings
282
+ // ═══════════════════════════════════════════════════════════════════════════
283
+
284
+ /// Validates that a G1 point (given as two 32-byte big-endian coordinates)
285
+ /// is on the BN254 curve and in the correct prime-order subgroup.
286
+ ///
287
+ /// Returns True if valid, raises ValueError if invalid.
288
+ #[pyfunction]
289
+ fn validate_point_g1(py: Python<'_>, x: &Bound<'_, PyBytes>, y: &Bound<'_, PyBytes>) -> PyResult<bool> {
290
+ let x_data = x.as_bytes();
291
+ let y_data = y.as_bytes();
292
+
293
+ py.allow_threads(|| {
294
+ deserialize_g1(x_data, y_data)
295
+ .map(|_| true)
296
+ .map_err(|e| PyValueError::new_err(e))
297
+ })
298
+ }
299
+
300
+ /// Initializes the global verification key in host RAM.
301
+ /// Deserializes the bytes and prepares the PVK, locking it in `GLOBAL_PVK`.
302
+ /// This prevents cyclotomic Fp12 operations from burning the CPU per-request.
303
+ #[pyfunction]
304
+ fn initialize_vkey(py: Python<'_>, vkey_bytes: &Bound<'_, PyBytes>, num_public_inputs: usize) -> PyResult<()> {
305
+ let vkey_data = vkey_bytes.as_bytes().to_vec();
306
+ py.allow_threads(move || {
307
+ let vk = deserialize_vkey(&vkey_data, num_public_inputs)
308
+ .map_err(|e| PyValueError::new_err(format!("VKey: {}", e)))?;
309
+ let pvk = Groth16::<Bn254>::process_vk(&vk)
310
+ .map_err(|e| PyValueError::new_err(format!("VKey processing: {}", e)))?;
311
+
312
+ let mut lock = GLOBAL_PVK.write().unwrap();
313
+ *lock = Some(pvk);
314
+ Ok(())
315
+ })
316
+ }
317
+
318
+ /// Full Groth16 proof verification using the globally locked PVK.
319
+ ///
320
+ /// Arguments:
321
+ /// proof_bytes: 256 bytes β€” the raw proof (Ο€_A, Ο€_B, Ο€_C) in big-endian.
322
+ /// public_inputs: List of 32-byte big-endian scalar field elements.
323
+ ///
324
+ /// Returns True if the proof is valid, False if the pairing check fails.
325
+ /// Raises ValueError for deserialization or structural errors.
326
+ ///
327
+ /// THE GIL IS RELEASED for the entire function body via py.allow_threads().
328
+ #[pyfunction]
329
+ fn verify_groth16(
330
+ py: Python<'_>,
331
+ proof_bytes: &Bound<'_, PyBytes>,
332
+ public_inputs: Vec<Bound<'_, PyBytes>>,
333
+ ) -> PyResult<bool> {
334
+ let proof_data = proof_bytes.as_bytes().to_vec();
335
+ let inputs_data: Vec<Vec<u8>> = public_inputs
336
+ .iter()
337
+ .map(|b| b.as_bytes().to_vec())
338
+ .collect();
339
+
340
+ py.allow_threads(move || {
341
+ // ── Acquire global PVK read lock ───────────────────────────────
342
+ let lock = GLOBAL_PVK.read().unwrap();
343
+ let pvk = lock.as_ref().ok_or_else(|| PyValueError::new_err("Verification engine not initialized with vkey"))?;
344
+
345
+ // ���─ Step 1: Deserialize proof (256 bytes) ──────────────────────
346
+ if proof_data.len() != 256 {
347
+ return Err(PyValueError::new_err(format!("Proof must be exactly 256 bytes")));
348
+ }
349
+
350
+ let pi_a = deserialize_g1(&proof_data[0..32], &proof_data[32..64])
351
+ .map_err(|e| PyValueError::new_err(format!("Ο€_A: {}", e)))?;
352
+ let pi_b = deserialize_g2(
353
+ &proof_data[64..96], &proof_data[96..128],
354
+ &proof_data[128..160], &proof_data[160..192],
355
+ ).map_err(|e| PyValueError::new_err(format!("Ο€_B: {}", e)))?;
356
+ let pi_c = deserialize_g1(&proof_data[192..224], &proof_data[224..256])
357
+ .map_err(|e| PyValueError::new_err(format!("Ο€_C: {}", e)))?;
358
+
359
+ let proof = Proof { a: pi_a, b: pi_b, c: pi_c };
360
+
361
+ // ── Step 2: Deserialize public inputs ──────────────────────────
362
+ let mut fr_inputs = Vec::with_capacity(inputs_data.len());
363
+ for (i, input) in inputs_data.iter().enumerate() {
364
+ let fr = bytes_to_fr(input)
365
+ .map_err(|e| PyValueError::new_err(format!("public_input[{}]: {}", i, e)))?;
366
+ fr_inputs.push(fr);
367
+ }
368
+
369
+ // ── Step 3: Verify the pairing equation ────────────────────────
370
+ verify_proof_inner(&proof, pvk, &fr_inputs)
371
+ .map_err(|e| PyValueError::new_err(e))
372
+ })
373
+ }
374
+
375
+ /// Python module definition.
376
+ #[pymodule]
377
+ fn vaikuntha_bn254(m: &Bound<'_, PyModule>) -> PyResult<()> {
378
+ m.add_function(wrap_pyfunction!(validate_point_g1, m)?)?;
379
+ m.add_function(wrap_pyfunction!(initialize_vkey, m)?)?;
380
+ m.add_function(wrap_pyfunction!(verify_groth16, m)?)?;
381
+ Ok(())
382
+ }
verification/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ GovBridge India β€” PROJECT VAIKUNTHA Phase 4.1
3
+ Verification Package
4
+ """
verification/deserializer.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ═══════════════════════════════════════════════════════════════════════════════
3
+ GovBridge India β€” PROJECT VAIKUNTHA Phase 4.1
4
+ Groth16 Proof Deserializer & Cryptographic Validator
5
+ ═══════════════════════════════════════════════════════════════════════════════
6
+
7
+ Unpacks the 256-byte big-endian proof payload emitted by the frontend
8
+ ZkProofExporter (gov_frontend/src/lib/ZkProofExporter.ts) and validates
9
+ every elliptic curve point for curve membership and subgroup containment.
10
+
11
+ Wire Format (256 bytes, big-endian):
12
+ Offset | Size | Field
13
+ --------|------|-----------------------------------
14
+ [0..31] | 32 | Ο€_A.x (G1, Fq)
15
+ [32..63]| 32 | Ο€_A.y (G1, Fq)
16
+ [64..95]| 32 | Ο€_B.x.c0 (G2, Fq component)
17
+ [96..127]| 32 | Ο€_B.x.c1 (G2, Fq component)
18
+ [128..159]| 32 | Ο€_B.y.c0 (G2, Fq component)
19
+ [160..191]| 32 | Ο€_B.y.c1 (G2, Fq component)
20
+ [192..223]| 32 | Ο€_C.x (G1, Fq)
21
+ [224..255]| 32 | Ο€_C.y (G1, Fq)
22
+
23
+ ARCHITECTURAL LAWS:
24
+ - NO floating-point arithmetic. All values are exact integer field elements.
25
+ - All Pydantic models use `bytes` fields with strict length validation.
26
+ - Cryptographic validation is delegated to the Rust extension
27
+ (vaikuntha_bn254) which releases the GIL during computation.
28
+ ═══════════════════════════════════════════════════════════════════════════════
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import logging
34
+ from typing import Final
35
+
36
+ from pydantic import BaseModel, Field, field_validator, model_validator
37
+
38
+ logger = logging.getLogger("govbridge.verification.deserializer")
39
+
40
+ # ═══════════════════════════════════════════════════════════════════════════════
41
+ # SECTION 1: BN254 Curve Constants
42
+ # ═══════════════════════════════════════════════════════════════════════════════
43
+
44
+ # BN254 base field prime p
45
+ # p = 21888242871839275222246405745257275088696311157297823662689037894645226208583
46
+ BN254_P: Final[int] = 0x30644E72E131A029B85045B68181585D97816A916871CA8D3C208C16D87CFD47
47
+
48
+ # BN254 scalar field order r (same value as in vector_prover.cpp P_BYTES)
49
+ # r = 21888242871839275222246405745257275088548364400416034343698204186575808495617
50
+ BN254_R: Final[int] = 0x30644E72E131A029B85045B68181585D2833E84879B9709143E1F593F0000001
51
+
52
+ # Proof payload size in bytes
53
+ PROOF_SIZE: Final[int] = 256
54
+
55
+ # Coordinate size in bytes (32 bytes = 256 bits for BN254 field elements)
56
+ COORD_SIZE: Final[int] = 32
57
+
58
+
59
+ # ═══════════════════════════════════════════════════════════════════════════════
60
+ # SECTION 2: Pydantic Type-Safe Models
61
+ # ═══════════════════════════════════════════════════════════════════════════════
62
+
63
+ class G1Point(BaseModel):
64
+ """
65
+ A point on the BN254 G₁ curve in affine coordinates.
66
+ Both coordinates are 32-byte big-endian field elements.
67
+ """
68
+ x: bytes = Field(..., min_length=COORD_SIZE, max_length=COORD_SIZE)
69
+ y: bytes = Field(..., min_length=COORD_SIZE, max_length=COORD_SIZE)
70
+
71
+ @field_validator("x", "y")
72
+ @classmethod
73
+ def validate_field_element(cls, v: bytes) -> bytes:
74
+ """Validate that the coordinate is a valid Fq element (< p)."""
75
+ val = int.from_bytes(v, byteorder="big")
76
+ if val >= BN254_P:
77
+ raise ValueError(
78
+ f"Coordinate value {val:#066x} >= BN254 base field prime p"
79
+ )
80
+ return v
81
+
82
+ model_config = {"frozen": True}
83
+
84
+
85
+ class G2Point(BaseModel):
86
+ """
87
+ A point on the BN254 Gβ‚‚ twisted curve in affine coordinates.
88
+ Gβ‚‚ lives over Fq2 = Fq[u] / (uΒ² + 1).
89
+ Each Fq2 element has two Fq components (c0, c1).
90
+ """
91
+ x_c0: bytes = Field(..., min_length=COORD_SIZE, max_length=COORD_SIZE)
92
+ x_c1: bytes = Field(..., min_length=COORD_SIZE, max_length=COORD_SIZE)
93
+ y_c0: bytes = Field(..., min_length=COORD_SIZE, max_length=COORD_SIZE)
94
+ y_c1: bytes = Field(..., min_length=COORD_SIZE, max_length=COORD_SIZE)
95
+
96
+ @field_validator("x_c0", "x_c1", "y_c0", "y_c1")
97
+ @classmethod
98
+ def validate_field_element(cls, v: bytes) -> bytes:
99
+ """Validate that the coordinate is a valid Fq element (< p)."""
100
+ val = int.from_bytes(v, byteorder="big")
101
+ if val >= BN254_P:
102
+ raise ValueError(
103
+ f"Coordinate value {val:#066x} >= BN254 base field prime p"
104
+ )
105
+ return v
106
+
107
+ model_config = {"frozen": True}
108
+
109
+
110
+ class DeserializedProof(BaseModel):
111
+ """
112
+ A fully deserialized and field-validated Groth16 proof.
113
+ All coordinates have been checked for field membership (< p).
114
+ Curve and subgroup checks are performed separately by the Rust engine.
115
+ """
116
+ pi_a: G1Point
117
+ pi_b: G2Point
118
+ pi_c: G1Point
119
+ raw_bytes: bytes = Field(
120
+ ..., min_length=PROOF_SIZE, max_length=PROOF_SIZE,
121
+ description="Original 256-byte proof payload (retained for Rust FFI)"
122
+ )
123
+
124
+ model_config = {"frozen": True}
125
+
126
+
127
+ # ═══════════════════════════════════════════════════════════════════════════════
128
+ # SECTION 3: Deserialization Engine
129
+ # ═══════════════════════════════════════════════════════════════════════════════
130
+
131
+ def deserialize_proof(payload: bytes) -> DeserializedProof:
132
+ """
133
+ Deserialize a 256-byte big-endian Groth16 proof payload.
134
+
135
+ Performs:
136
+ 1. Length validation (exactly 256 bytes)
137
+ 2. Field membership checks for all 8 coordinates (< p)
138
+ 3. Structural packing into type-safe Pydantic models
139
+
140
+ Does NOT perform curve equation or subgroup checks β€” those are
141
+ delegated to the Rust extension (vaikuntha_bn254.verify_groth16)
142
+ which handles them in constant time with GIL released.
143
+
144
+ Args:
145
+ payload: Exactly 256 bytes of big-endian proof data.
146
+
147
+ Returns:
148
+ DeserializedProof with pi_a (G1), pi_b (G2), pi_c (G1).
149
+
150
+ Raises:
151
+ ValueError: If payload length is wrong or any coordinate >= p.
152
+ """
153
+ if len(payload) != PROOF_SIZE:
154
+ raise ValueError(
155
+ f"Proof payload must be exactly {PROOF_SIZE} bytes, got {len(payload)}"
156
+ )
157
+
158
+ logger.debug("Deserializing 256-byte Groth16 proof payload")
159
+
160
+ # ── Extract G₁ point Ο€_A (offset 0..63) ───────────────────────────────
161
+ pi_a = G1Point(
162
+ x=payload[0:32],
163
+ y=payload[32:64],
164
+ )
165
+
166
+ # ── Extract Gβ‚‚ point Ο€_B (offset 64..191) ─────────────────────────────
167
+ pi_b = G2Point(
168
+ x_c0=payload[64:96],
169
+ x_c1=payload[96:128],
170
+ y_c0=payload[128:160],
171
+ y_c1=payload[160:192],
172
+ )
173
+
174
+ # ── Extract G₁ point Ο€_C (offset 192..255) ────────────────────────────
175
+ pi_c = G1Point(
176
+ x=payload[192:224],
177
+ y=payload[224:256],
178
+ )
179
+
180
+ proof = DeserializedProof(
181
+ pi_a=pi_a,
182
+ pi_b=pi_b,
183
+ pi_c=pi_c,
184
+ raw_bytes=payload,
185
+ )
186
+
187
+ logger.info(
188
+ "Proof deserialized: Ο€_A.x=%s... Ο€_B.x.c0=%s... Ο€_C.x=%s...",
189
+ payload[0:4].hex(),
190
+ payload[64:68].hex(),
191
+ payload[192:196].hex(),
192
+ )
193
+
194
+ return proof
195
+
196
+
197
+ def validate_public_input(signal: bytes) -> None:
198
+ """
199
+ Validate a single public input (32-byte big-endian scalar field element).
200
+
201
+ The value must be < r (the BN254 scalar field order).
202
+
203
+ Args:
204
+ signal: 32 bytes, big-endian.
205
+
206
+ Raises:
207
+ ValueError: If length != 32 or value >= r.
208
+ """
209
+ if len(signal) != COORD_SIZE:
210
+ raise ValueError(
211
+ f"Public input must be exactly {COORD_SIZE} bytes, got {len(signal)}"
212
+ )
213
+ val = int.from_bytes(signal, byteorder="big")
214
+ if val >= BN254_R:
215
+ raise ValueError(
216
+ f"Public input {val:#066x} >= BN254 scalar field order r"
217
+ )
verification/groth16_verifier.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ═══════════════════════════════════════════════════════════════════════════════
3
+ GovBridge India β€” PROJECT VAIKUNTHA Phase 4.1
4
+ Groth16 Verification Orchestrator
5
+ ═══════════════════════════════════════════════════════════════════════════════
6
+
7
+ Orchestrates the full verification pipeline:
8
+ 1. Accepts deserialized proof + public inputs
9
+ 2. Loads the verification key from disk (cached in-process)
10
+ 3. Delegates the Optimal Ate pairing computation to the Rust native
11
+ extension (vaikuntha_bn254) via PyO3 FFI
12
+ 4. Returns a typed VerificationResult
13
+
14
+ The Rust extension releases the Python GIL during the entire pairing
15
+ evaluation (~3ms on x86-64), ensuring the FastAPI event loop and all
16
+ concurrent request handlers remain fully unblocked.
17
+
18
+ PERFORMANCE CHARACTERISTICS:
19
+ - Deserialization + field checks: ~0.05ms (Python, GIL held)
20
+ - Subgroup + pairing evaluation: ~3ms (Rust, GIL released)
21
+ - Total end-to-end: ~3.5ms per verification
22
+ - Theoretical ceiling: ~280 verifications/sec (single core)
23
+ - With thread pool (4 workers): ~1,120 verifications/sec
24
+
25
+ SECURITY MODEL:
26
+ - All points are validated for curve membership AND subgroup containment
27
+ inside the Rust boundary BEFORE any pairing computation occurs.
28
+ - Invalid proofs produce cryptographically precise error messages (no
29
+ information leakage about the verification key internals).
30
+ - The verification key is loaded once and cached immutably.
31
+ ═══════════════════════════════════════════════════════════════════════════════
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import asyncio
37
+ import functools
38
+ import hashlib
39
+ import logging
40
+ import time
41
+ from concurrent.futures import ThreadPoolExecutor
42
+ from pathlib import Path
43
+ from typing import Final, Optional
44
+
45
+ from pydantic import BaseModel, Field
46
+
47
+ from verification.deserializer import (
48
+ DeserializedProof,
49
+ deserialize_proof,
50
+ validate_public_input,
51
+ PROOF_SIZE,
52
+ COORD_SIZE,
53
+ )
54
+
55
+ logger = logging.getLogger("govbridge.verification.groth16_verifier")
56
+
57
+ # ═══════════════════════════════════════════════════════════════════════════════
58
+ # SECTION 1: Configuration
59
+ # ═══════════════════════════════════════════════════════════════════════════════
60
+
61
+ # Path to the serialized verification key (deployed alongside the backend)
62
+ VKEY_PATH: Final[Path] = Path(__file__).parent / "vkey.bin"
63
+
64
+ # Thread pool for offloading Rust FFI calls (GIL is released inside Rust,
65
+ # but we still need a thread to call into Rust without blocking the event loop)
66
+ _VERIFIER_THREAD_POOL: Final[ThreadPoolExecutor] = ThreadPoolExecutor(
67
+ max_workers=4,
68
+ thread_name_prefix="vaikuntha-verifier",
69
+ )
70
+
71
+ # Cached verification key bytes (loaded once, immutable)
72
+ _vkey_cache: Optional[bytes] = None
73
+
74
+ # SHA-256 of the trusted verification key. Set this value after the trusted
75
+ # setup ceremony to enable integrity pinning. If None, integrity checking is
76
+ # disabled (development mode only β€” MUST be set before production deployment).
77
+ VKEY_EXPECTED_SHA256: Final[Optional[str]] = None # e.g., "a1b2c3d4e5f6..."
78
+
79
+
80
+ # ═══════════════════════════════════════════════════════════════════════════════
81
+ # SECTION 2: Verification Key Management
82
+ # ═══════════════════════════════════════════════════════════════════════════════
83
+
84
+ def initialize_verification_engine(num_public_inputs: int = 1) -> None:
85
+ """
86
+ Initializes the verification engine. Validates the trusted setup vkey,
87
+ checks its SHA-256 integrity, and locks it into the Rust extension's global memory.
88
+ MUST be called at FastAPI lifespan boot.
89
+
90
+ Raises:
91
+ FileNotFoundError: If vkey.bin is missing.
92
+ RuntimeError: If the file is suspiciously small or corrupted.
93
+ """
94
+ global _vkey_cache
95
+ if _vkey_cache is not None:
96
+ return
97
+
98
+ if not VKEY_PATH.exists():
99
+ raise FileNotFoundError(
100
+ f"Verification key not found at {VKEY_PATH}. "
101
+ "Run the trusted setup ceremony first."
102
+ )
103
+
104
+ raw = VKEY_PATH.read_bytes()
105
+
106
+ if len(raw) < 512:
107
+ raise RuntimeError(
108
+ f"Verification key at {VKEY_PATH} is only {len(raw)} bytes. "
109
+ "Expected >= 512 bytes (4 curve points + at least 1 IC point)."
110
+ )
111
+
112
+ # ── Integrity check: verify SHA-256 against trusted reference ────────
113
+ if VKEY_EXPECTED_SHA256 is not None:
114
+ actual = hashlib.sha256(raw).hexdigest()
115
+ if actual != VKEY_EXPECTED_SHA256:
116
+ raise RuntimeError(
117
+ f"Verification key integrity check FAILED. "
118
+ f"Expected SHA-256: {VKEY_EXPECTED_SHA256}, got: {actual}. "
119
+ f"The vkey.bin file may have been tampered with."
120
+ )
121
+ logger.info("VKey integrity check passed (SHA-256: %s...)", actual[:16])
122
+
123
+ _vkey_cache = raw
124
+ logger.info("Verification key loaded: %d bytes from %s", len(raw), VKEY_PATH)
125
+
126
+ try:
127
+ import vaikuntha_bn254 # type: ignore[import-not-found]
128
+ vaikuntha_bn254.initialize_vkey(raw, num_public_inputs)
129
+ logger.info("PVK successfully locked into Rust global memory.")
130
+ except ImportError:
131
+ logger.warning("vaikuntha_bn254 not installed, skipping Rust initialization.")
132
+
133
+
134
+ # ═══════════════════════════════════════════════════════════════════════════════
135
+ # SECTION 3: Result Types
136
+ # ═══════════════════════════════════════════════════════════════════════════════
137
+
138
+ class VerificationResult(BaseModel):
139
+ """Typed result of a Groth16 proof verification."""
140
+ valid: bool = Field(..., description="True if the proof is cryptographically valid")
141
+ verification_time_ms: float = Field(
142
+ ..., ge=0, description="Wall-clock time for the verification in milliseconds"
143
+ )
144
+ error: Optional[str] = Field(
145
+ default=None, description="Human-readable error message if verification failed"
146
+ )
147
+
148
+ model_config = {"frozen": True}
149
+
150
+
151
+ # ═══════════════════════════════════════════════════════════════════════════════
152
+ # SECTION 4: Synchronous Verification (runs in thread pool)
153
+ # ═══════════════════════════════════════════════════════════════════════════════
154
+
155
+ def _verify_sync(proof_bytes: bytes, public_input_bytes: list[bytes]) -> VerificationResult:
156
+ """
157
+ Synchronous verification β€” called from the thread pool.
158
+
159
+ This function:
160
+ 1. Calls the Rust extension (GIL released during pairing)
161
+ 2. Returns a typed result
162
+
163
+ MUST NOT be called from the async event loop directly.
164
+ """
165
+ start = time.perf_counter()
166
+
167
+ try:
168
+ # Import here to allow graceful degradation if wheel not installed
169
+ import vaikuntha_bn254 # type: ignore[import-not-found]
170
+
171
+ result: bool = vaikuntha_bn254.verify_groth16(
172
+ proof_bytes,
173
+ public_input_bytes,
174
+ )
175
+
176
+ elapsed_ms = (time.perf_counter() - start) * 1000.0
177
+ logger.info(
178
+ "Groth16 verification %s in %.2fms",
179
+ "PASSED" if result else "FAILED",
180
+ elapsed_ms,
181
+ )
182
+
183
+ return VerificationResult(
184
+ valid=result,
185
+ verification_time_ms=round(elapsed_ms, 3),
186
+ )
187
+
188
+ except ImportError:
189
+ elapsed_ms = (time.perf_counter() - start) * 1000.0
190
+ error_msg = (
191
+ "vaikuntha_bn254 native extension not installed. "
192
+ "Build with: cd gov_backend/vaikuntha_bn254 && maturin develop --release"
193
+ )
194
+ logger.error(error_msg)
195
+ return VerificationResult(
196
+ valid=False,
197
+ verification_time_ms=round(elapsed_ms, 3),
198
+ error=error_msg,
199
+ )
200
+
201
+ except ValueError as e:
202
+ # Deserialization or cryptographic validation failure
203
+ elapsed_ms = (time.perf_counter() - start) * 1000.0
204
+ logger.warning("Proof rejected: %s (%.2fms)", str(e), elapsed_ms)
205
+ return VerificationResult(
206
+ valid=False,
207
+ verification_time_ms=round(elapsed_ms, 3),
208
+ error=str(e),
209
+ )
210
+
211
+ except Exception as e:
212
+ elapsed_ms = (time.perf_counter() - start) * 1000.0
213
+ logger.exception("Unexpected verification error")
214
+ return VerificationResult(
215
+ valid=False,
216
+ verification_time_ms=round(elapsed_ms, 3),
217
+ error=f"Internal verification error: {type(e).__name__}: {e}",
218
+ )
219
+
220
+
221
+ # ═══��═══════════════════════════════════════════════════════════════════════════
222
+ # SECTION 5: Async Verification (event-loop safe)
223
+ # ═══════════════════════════════════════════════════════════════════════════════
224
+
225
+ async def verify_groth16_async(
226
+ proof_bytes: bytes,
227
+ public_input_bytes: list[bytes],
228
+ ) -> VerificationResult:
229
+ """
230
+ Async-safe Groth16 verification.
231
+
232
+ Offloads the Rust FFI call to a dedicated thread pool so the uvicorn
233
+ event loop is NEVER blocked.
234
+
235
+ Pipeline:
236
+ 1. [Event Loop] Validate inputs (fast, ~0.05ms)
237
+ 2. [Thread Pool] Rust pairing computation (GIL released, ~3ms)
238
+ 3. [Event Loop] Return result
239
+
240
+ Args:
241
+ proof_bytes: Exactly 256 bytes of raw proof data.
242
+ public_input_bytes: List of 32-byte big-endian scalar field elements.
243
+
244
+ Returns:
245
+ VerificationResult with valid=True/False and timing data.
246
+ """
247
+ # Pre-validate on the event loop (cheap operations, no GIL contention)
248
+ if len(proof_bytes) != PROOF_SIZE:
249
+ return VerificationResult(
250
+ valid=False,
251
+ verification_time_ms=0.0,
252
+ error=f"Proof must be exactly {PROOF_SIZE} bytes, got {len(proof_bytes)}",
253
+ )
254
+
255
+ for i, signal in enumerate(public_input_bytes):
256
+ try:
257
+ validate_public_input(signal)
258
+ except ValueError as e:
259
+ return VerificationResult(
260
+ valid=False,
261
+ verification_time_ms=0.0,
262
+ error=f"public_input[{i}]: {e}",
263
+ )
264
+
265
+ # Offload the heavy Rust computation to the thread pool
266
+ loop = asyncio.get_running_loop()
267
+ result = await loop.run_in_executor(
268
+ _VERIFIER_THREAD_POOL,
269
+ functools.partial(_verify_sync, proof_bytes, public_input_bytes),
270
+ )
271
+
272
+ return result
verification/routes.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ═══════════════════════════════════════════════════════════════════════════════
3
+ GovBridge India β€” PROJECT VAIKUNTHA Phase 4.1
4
+ POST /api/verify-proof β€” Groth16 Zero-Knowledge Proof Verification Endpoint
5
+ ═══════════════════════════════════════════════════════════════════════════════
6
+
7
+ Accepts a raw 256-byte proof + public signals, orchestrates the full
8
+ deserialization β†’ validation β†’ Rust pairing verification pipeline.
9
+
10
+ Request format:
11
+ POST /api/verify-proof
12
+ Content-Type: application/json
13
+
14
+ {
15
+ "proof": "<512-char hex string encoding 256 bytes>",
16
+ "public_inputs": ["<64-char hex string>", ...]
17
+ }
18
+
19
+ Response format:
20
+ {
21
+ "valid": true/false,
22
+ "verification_time_ms": 3.142,
23
+ "error": null | "human-readable error"
24
+ }
25
+
26
+ RATE LIMITING: 20/minute per IP (crypto verification is CPU-intensive).
27
+ ═══════════════════════════════════════════════════════════════════════════════
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import logging
33
+ import re
34
+ from typing import List
35
+
36
+ from fastapi import APIRouter, Request
37
+ from pydantic import BaseModel, Field, field_validator
38
+ from typing import Any, List
39
+ from slowapi import Limiter
40
+ from slowapi.util import get_remote_address
41
+
42
+ from verification.groth16_verifier import verify_groth16_async, VerificationResult
43
+
44
+ # ── Rate Limiter (accesses app.state.limiter configured in api.py) ────────
45
+ limiter = Limiter(key_func=get_remote_address)
46
+
47
+ logger = logging.getLogger("govbridge.verification.routes")
48
+
49
+ router = APIRouter(prefix="/api", tags=["verification"])
50
+
51
+
52
+ # ═══════════════════════════════════════════════════════════════════════════════
53
+ # SECTION 1: Request / Response Models
54
+ # ═══════════════════════════════════════════════════════════════════════════════
55
+
56
+ class VerifyProofRequest(BaseModel):
57
+ """
58
+ Incoming proof verification request.
59
+
60
+ The proof is transmitted as a hex-encoded string (512 hex chars = 256 bytes).
61
+ Public inputs are hex-encoded scalar field elements (64 hex chars = 32 bytes each).
62
+ """
63
+ proof: str = Field(
64
+ ...,
65
+ min_length=512,
66
+ max_length=512,
67
+ description="Hex-encoded 256-byte Groth16 proof (Ο€_A || Ο€_B || Ο€_C)"
68
+ )
69
+ public_inputs: List[str] = Field(
70
+ ...,
71
+ min_length=1,
72
+ max_length=32,
73
+ description="Hex-encoded 32-byte public input scalars"
74
+ )
75
+
76
+ @field_validator("proof", mode="before")
77
+ @classmethod
78
+ def validate_proof_hex(cls, v: Any) -> Any:
79
+ """Ensure the proof is a valid hex string of exactly 512 characters."""
80
+ if not isinstance(v, str): return v
81
+ v = v.lower().strip()
82
+ if v.startswith("0x"):
83
+ v = v[2:]
84
+ if len(v) != 512:
85
+ raise ValueError(
86
+ f"Proof hex must be exactly 512 characters (256 bytes), got {len(v)}"
87
+ )
88
+ if not re.fullmatch(r"[0-9a-f]+", v):
89
+ raise ValueError("Proof hex contains non-hexadecimal characters")
90
+ return v
91
+
92
+ @field_validator("public_inputs", mode="before")
93
+ @classmethod
94
+ def validate_public_inputs_hex(cls, v: Any) -> Any:
95
+ """Validate each public input is a 64-char hex string."""
96
+ if not isinstance(v, list): return v
97
+ result = []
98
+ for i, inp in enumerate(v):
99
+ if not isinstance(inp, str):
100
+ result.append(inp)
101
+ continue
102
+ inp = inp.lower().strip()
103
+ if inp.startswith("0x"):
104
+ inp = inp[2:]
105
+ if len(inp) != 64:
106
+ raise ValueError(
107
+ f"public_inputs[{i}]: must be exactly 64 hex chars (32 bytes), got {len(inp)}"
108
+ )
109
+ if not re.fullmatch(r"[0-9a-f]+", inp):
110
+ raise ValueError(
111
+ f"public_inputs[{i}]: contains non-hexadecimal characters"
112
+ )
113
+ result.append(inp)
114
+ return result
115
+
116
+
117
+ class VerifyProofResponse(BaseModel):
118
+ """Proof verification response."""
119
+ valid: bool
120
+ verification_time_ms: float
121
+ error: str | None = None
122
+
123
+
124
+ # ═════════════════════════════════════════════════��═════════════════════════════
125
+ # SECTION 2: Endpoint Definition
126
+ # ═══════════════════════════════════════════════════════════════════════════════
127
+
128
+ @router.post(
129
+ "/verify-proof",
130
+ response_model=VerifyProofResponse,
131
+ summary="Verify a Groth16 ZK-SNARK proof",
132
+ description=(
133
+ "Accepts a 256-byte BN254 Groth16 proof and public inputs. "
134
+ "Returns whether the proof is cryptographically valid. "
135
+ "The pairing computation is offloaded to a Rust native extension "
136
+ "that releases the Python GIL."
137
+ ),
138
+ )
139
+ @limiter.limit("20/minute")
140
+ async def verify_proof(
141
+ request: Request,
142
+ body: VerifyProofRequest,
143
+ ) -> VerifyProofResponse:
144
+ """
145
+ POST /api/verify-proof
146
+
147
+ Pipeline:
148
+ 1. Pydantic validates hex format and lengths
149
+ 2. Convert hex strings to raw bytes
150
+ 3. Delegate to verify_groth16_async (thread-pool β†’ Rust FFI)
151
+ 4. Return typed response
152
+
153
+ The entire pipeline is non-blocking. The Rust pairing computation
154
+ (~3ms) runs in a dedicated thread pool with the GIL released.
155
+ """
156
+ logger.info(
157
+ "Verification request: proof=%s... inputs=%d",
158
+ body.proof[:16],
159
+ len(body.public_inputs),
160
+ )
161
+
162
+ # Convert hex to raw bytes
163
+ proof_bytes = bytes.fromhex(body.proof)
164
+ public_input_bytes = [bytes.fromhex(inp) for inp in body.public_inputs]
165
+
166
+ # Execute async verification (offloaded to Rust thread pool)
167
+ result: VerificationResult = await verify_groth16_async(
168
+ proof_bytes=proof_bytes,
169
+ public_input_bytes=public_input_bytes,
170
+ )
171
+
172
+ # Sanitize error messages for production: expose detail only in debug mode
173
+ safe_error = (
174
+ "Proof verification failed" if result.error and not getattr(request.app, 'debug', False)
175
+ else result.error
176
+ )
177
+
178
+ return VerifyProofResponse(
179
+ valid=result.valid,
180
+ verification_time_ms=result.verification_time_ms,
181
+ error=safe_error,
182
+ )
verification/vkey.bin ADDED
Binary file (576 Bytes). View file
 
whatsapp/__pycache__/__init__.cpython-312.pyc CHANGED
Binary files a/whatsapp/__pycache__/__init__.cpython-312.pyc and b/whatsapp/__pycache__/__init__.cpython-312.pyc differ
 
whatsapp/__pycache__/webhook.cpython-312.pyc CHANGED
Binary files a/whatsapp/__pycache__/webhook.cpython-312.pyc and b/whatsapp/__pycache__/webhook.cpython-312.pyc differ