-
Notifications
You must be signed in to change notification settings - Fork 0
/
sindri.py
813 lines (705 loc) · 31.2 KB
/
sindri.py
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
"""
## Usage
```python
# Download some sample data
# git clone https://github.com/Sindri-Labs/sindri-resources.git
# pip install sindri
from sindri import Sindri
# Initialize
sindri = Sindri("<YOUR_API_KEY>", verbose_level=2)
# Upload a Circuit
circuit_upload_path: str = "sindri-resources/circuit_database/circom/multiplier2"
circuit_id: str = sindri.create_circuit(circuit_upload_path)
# Generate a Proof
proof_input_file_path = "sindri-resources/circuit_database/circom/multiplier2/input.json"
with open(proof_input_file_path, "r") as f:
proof_id: str = sindri.prove_circuit(circuit_id, f.read())
```
"""
import io
import json
import os
import pathlib
import platform
import tarfile
import time
from pprint import pformat
from urllib.parse import urlparse
import requests # type: ignore
__version__ = "v0.0.0"
class Sindri:
"""A utility class for interacting with the [Sindri API](https://www.sindri.app)."""
class APIError(Exception):
"""Custom Exception for Sindri API Errors"""
pass
DEFAULT_SINDRI_API_URL = "https://sindri.app/api/v1/"
VERBOSE_LEVELS: list[int] = [0, 1, 2]
def __init__(self, api_key: str, verbose_level: int = 0, **kwargs):
"""Initialize an instance of the Sindri SDK.
Args:
- `api_key`: Your Sindri API Key.
- `verbose_level`: Must be either `0`, `1`, or `2`.
- `0`: Do not print anything to stdout.
- `1`: Print only necesessary information from Circuit/Proof objects.
- `2`: Print everything.
Returns:
- `sindri`: An instance of the class configured with your Sindri API Key.
Raises:
- `Sindri.APIError`:
- Your API Key is improperly formatted.
"""
# Obtain version from module
self.version = __version__
self.headers_json: dict = {} # set in set_api_key()
# Do not print anything during initial setup.
self.set_verbose_level(0)
self.polling_interval_sec: int = 1 # polling interval for circuit compilation & proving
self.max_polling_iterations: int = 172800 # 2 days with polling interval 1 second
self.perform_verify: bool = False
self._api_url = self._get_api_url(**kwargs)
self.set_api_key(api_key)
# With initial setup complete, set desired verbose level.
self.set_verbose_level(verbose_level)
if self.verbose_level > 0:
self._print_sindri_logo()
print(f"Sindri API Url: {self._api_url}")
print(f"Sindri API Key: {self.api_key}\n")
def _get_api_url(self, **kwargs) -> str:
"""Examine `**kwargs` for `base_url` and `api_url`, in that order.
If `base_url` is found and valid, return that. If not valid, raise an error.
If `base_url` is not found then check for `api_url`.
If `api_url` is found and valid, return that. If not valid, raise an error.
If neither keyword is found in `**kwargs`, return the default API URL.
"""
def is_url(url: str) -> bool:
"""Validate a provided str is a url."""
try:
result = urlparse(url)
return all([result.scheme, result.netloc])
except ValueError:
return False
# Order of precedence for obtaining the API URL:
# 1. `base_url` is in kwargs
url = kwargs.get("base_url", None)
if url is not None:
error_msg: str = "Invalid 'base_url' provided."
if not isinstance(url, str):
raise Sindri.APIError(error_msg)
# Remove all trailing slashes "/"
url = url.rstrip("/")
# Validate str is a url
if not is_url(url):
raise Sindri.APIError(error_msg)
# We assume a provided "base_url" has no path on the end
path = urlparse(url).path
if path != "":
raise Sindri.APIError(error_msg)
return os.path.join(url, "api", "v1", "")
# 2. `api_url` is in kwargs
url = kwargs.get("api_url", None)
if url is not None:
print("\nWARNING: 'api_url' is deprecated. Please use 'base_url' instead.\n")
error_msg = "Invalid 'api_url' provided."
if not isinstance(url, str):
raise Sindri.APIError(error_msg)
# Remove all trailing slashes "/"
url = url.rstrip("/")
# Validate str is a url
if not is_url(url):
raise Sindri.APIError(error_msg)
# We assume a provided "api_url" has "/api" as the path on the end
path = urlparse(url).path
if path != "/api":
raise Sindri.APIError(error_msg)
return os.path.join(url, "v1", "")
# 3. Use default
return self.DEFAULT_SINDRI_API_URL
def _get_circuit(self, circuit_id: str, include_verification_key: bool = False) -> dict:
"""Hit the circuit_detail API endpoint and validate the response. Do not print anything.
This may raise `Sindri.APIError` if the response is invalid."""
response_status_code, response_json = self._hit_api(
"GET",
f"circuit/{circuit_id}/detail",
data={"include_verification_key": include_verification_key},
)
if response_status_code != 200:
raise Sindri.APIError(
f"Unable to fetch circuit_id={circuit_id}."
f" status={response_status_code} response={response_json}"
)
if not isinstance(response_json, dict):
raise Sindri.APIError("Received unexpected type for circuit detail response.")
return response_json
def _get_proof(
self,
proof_id: str,
include_proof: bool = False,
include_public: bool = False,
include_smart_contract_calldata: bool = False,
include_verification_key: bool = False,
) -> dict:
"""Hit the proof_detail API endpoint and validate the response. Do not print anything.
This may raise `Sindri.APIError` if the response is invalid."""
response_status_code, response_json = self._hit_api(
"GET",
f"proof/{proof_id}/detail",
data={
"include_proof": include_proof,
"include_public": include_public,
"include_smart_contract_calldata": include_smart_contract_calldata,
"include_verification_key": include_verification_key,
},
)
if response_status_code != 200:
raise Sindri.APIError(
f"Unable to fetch proof_id={proof_id}."
f" status={response_status_code} response={response_json}"
)
if not isinstance(response_json, dict):
raise Sindri.APIError("Received unexpected type for proof detail response.")
return response_json
def _get_verbose_1_circuit_detail(self, circuit_detail: dict) -> dict:
"""Return a slim circuit detail object for printing."""
return {
"circuit_id": circuit_detail.get("circuit_id", None),
"circuit_name": circuit_detail.get("circuit_name", None),
"circuit_type": circuit_detail.get("circuit_type", None),
"compute_time": circuit_detail.get("compute_time", None),
"date_created": circuit_detail.get("date_created", None),
"status": circuit_detail.get("status", None),
}
def _get_verbose_1_proof_detail(self, proof_detail: dict) -> dict:
"""Return a slim proof detail object for printing."""
return {
"circuit_id": proof_detail.get("circuit_id", None),
"circuit_name": proof_detail.get("circuit_name", None),
"circuit_type": proof_detail.get("circuit_type", None),
"compute_time": proof_detail.get("compute_time", None),
"date_created": proof_detail.get("date_created", None),
"proof_id": proof_detail.get("proof_id", None),
"status": proof_detail.get("status", None),
}
def _hit_api(self, method: str, path: str, data=None, files=None) -> tuple[int, dict | list]:
"""
Hit the Sindri API.
Returns
- int: response status code
- dict: response json
Raises an Exception if
- response is None
- cannot connect to the API
- response cannot be JSON decoded
- invalid API Key
"""
# Initialize data if not provided
if data is None:
data = {}
# Construct the full path to the API endpoint.
full_path = os.path.join(self._api_url, path)
try:
if method == "POST":
response = requests.post(
full_path, headers=self.headers_json, data=data, files=files
)
elif method == "GET":
response = requests.get(full_path, headers=self.headers_json, params=data)
elif method == "DELETE":
response = requests.delete(full_path, headers=self.headers_json, data=data)
else:
raise Sindri.APIError("Invalid request method")
except requests.exceptions.ConnectionError:
# Raise a clean exception and suppress the original exception's traceback.
raise Sindri.APIError(
f"Unable to connect to the Sindri API. path={full_path}"
) from None
if response is None:
raise Sindri.APIError(
f"No response received. method={method}, path={full_path},"
f" data={data} headers={self.headers_json}, files={files}"
)
if response.status_code == 401:
raise Sindri.APIError(f"401 - Invalid API Key. path={full_path}")
elif response.status_code == 404:
raise Sindri.APIError(f"404 - Not found. path={full_path}")
else:
# Decode JSON response
try:
response_json = response.json()
except json.decoder.JSONDecodeError:
raise Sindri.APIError(
f"Unexpected Error. Unable to decode response as JSON."
f" status={response.status_code} response={response.text}"
) from None
return response.status_code, response_json
def _print_sindri_logo(self):
# https://ascii-generator.site/ 32 columns
print(
f"""Sindri API Python SDK - {self.version}
.+******************+.
=********************=
.:. -==================-
=****
=****-
.::-*+==================-
=********************=
.+******************+.
=**+:
:*****
.:::::::::::::::::::::++==-
.***********************+
.***********************-"""
)
def _set_json_request_headers(self) -> None:
"""Set JSON request headers (set `self.headers_json`). Use `self.api_key` for `Bearer`.
Additionally set the `Sindri-Client` header.
"""
self.headers_json = {
"Accept": "application/json",
"Authorization": f"Bearer {self.api_key}",
"Sindri-Client": f"sindri-py-sdk/{self.version} ({platform.platform()}) python_version:{platform.python_version()}", # noqa: E501
}
def create_circuit(
self, circuit_upload_path: str, tags: list[str] | None = None, wait: bool = True
) -> str:
"""Create a circuit. For information, refer to the
[API docs](https://sindri.app/docs/reference/api/circuit-create/).
Args:
- `circuit_upload_path`: The path to either
- A directory containing your circuit files
- A compressed file (`.tar.gz` or `.zip`) of your circuit directory
- `tags`: A list of tags to assign the circuit. Defaults to `["latest"]` if not
sepecified.
- `wait`:
- If `True`, block until the circuit is finished compiling.
- If `False`, submit the circuit and return immediately.
Returns:
- `circuit_id`: The UUID4 identifier associated with this circuit. This is generated by
Sindri.
Raises:
- `Sindri.APIError`:
- Your API Key is invalid.
- There is an error connecting to the Sindri API.
- There is an error with your circuit upload.
- The circuit has a compilation error (if `wait=True`).
"""
# Return value
circuit_id = "" # set later
# 1. Create a circuit, obtain a circuit_id.
if self.verbose_level > 0:
print("Circuit: Create")
if self.verbose_level > 1:
print(f" upload_path: {circuit_upload_path}")
# Ensure circuit_upload_path exists
if not os.path.exists(circuit_upload_path):
raise Sindri.APIError(f"circuit_upload_path does not exist: {circuit_upload_path}")
# Prepare files for upload
if os.path.isfile(circuit_upload_path):
# Assume the path is already a tarfile
files = {"files": open(circuit_upload_path, "rb")}
elif os.path.isdir(circuit_upload_path):
# Create a tar archive and upload via byte stream
circuit_upload_path = os.path.abspath(circuit_upload_path)
file_name = f"{pathlib.Path(circuit_upload_path).stem}.tar.gz"
fh = io.BytesIO()
with tarfile.open(fileobj=fh, mode="w:gz") as tar:
tar.add(circuit_upload_path, arcname=file_name)
files = {"files": fh.getvalue()} # type: ignore
# Hit circuit/create API endpoint
response_status_code, response_json = self._hit_api(
"POST",
"circuit/create",
data={"tags": tags},
files=files,
)
if response_status_code != 201:
raise Sindri.APIError(
f"Unable to create a new circuit."
f" status={response_status_code} response={response_json}"
)
if not isinstance(response_json, dict):
raise Sindri.APIError("Received unexpected type for circuit detail response.")
# Obtain circuit_id from response
circuit_id = response_json.get("circuit_id", "")
if self.verbose_level > 0:
print(f" circuit_id: {circuit_id}")
if wait:
# 2. Poll circuit detail until it has a status of Ready/Failed
if self.verbose_level > 0:
print("Circuit: Poll until Ready/Failed")
for _ in range(self.max_polling_iterations):
circuit = self._get_circuit(circuit_id, include_verification_key=False)
circuit_status = circuit.get("status", "")
if circuit_status == "Failed":
raise Sindri.APIError(
f"Circuit compilation failed." f" error={circuit.get('error', '')}"
)
if circuit_status == "Ready":
break
time.sleep(self.polling_interval_sec)
else:
raise Sindri.APIError("Circuit compile polling timed out.")
if self.verbose_level > 0:
self.get_circuit(circuit_id, include_verification_key=True)
# Circuit compilation success!
return circuit_id
def delete_circuit(self, circuit_id: str) -> None:
"""Mark the specified circuit and any of its related proofs as deleted. For information,
refer to the [API docs](https://sindri.app/docs/reference/api/circuit-delete/).
Args:
- `circuit_id`: The circuit identifier of the circuit.
Returns:
- `None`
Raises:
- `Sindri.APIError`:
- Your API Key is invalid.
- There is an error connecting to the Sindri API.
- The specified circuit does not exist.
"""
response_status_code, response_json = self._hit_api(
"DELETE", f"circuit/{circuit_id}/delete"
)
if response_status_code != 200:
raise Sindri.APIError(
f"Unable to delete circuit_id={circuit_id}."
f" status={response_status_code} response={response_json}"
)
def delete_proof(self, proof_id: str) -> None:
"""Mark the specified proof as deleted. For information, refer to the
[API docs](https://sindri.app/docs/reference/api/proof-delete/).
Args:
- `proof_id`: The UUID4 identifier associated with this proof.
Returns:
- `None`
Raises:
- `Sindri.APIError`:
- Your API Key is invalid.
- There is an error connecting to the Sindri API.
- The specified proof does not exist.
"""
response_status_code, response_json = self._hit_api("DELETE", f"proof/{proof_id}/delete")
if response_status_code != 200:
raise Sindri.APIError(
f"Unable to delete proof_id={proof_id}."
f" status={response_status_code} response={response_json}"
)
def get_all_circuit_proofs(self, circuit_id: str) -> list[dict]:
"""Return a list of proof infos for the provided circuit_id. For information, refer to the
[API docs](https://sindri.app/docs/reference/api/circuit-proofs/).
Args:
- `circuit_id`: The circuit identifier of the circuit.
Returns:
- `proofs`: A list of proof infos.
Raises:
- `Sindri.APIError`:
- Your API Key is invalid.
- There is an error connecting to the Sindri API.
- The specified circuit does not exist.
"""
if self.verbose_level > 0:
print(f"Proof: Get all proofs for circuit_id: {circuit_id}")
response_status_code, response_json = self._hit_api(
"GET",
f"circuit/{circuit_id}/proofs",
)
if response_status_code != 200:
raise Sindri.APIError(
f"Unable to fetch proofs for circuit_id={circuit_id}."
f" status={response_status_code} response={response_json}"
)
if not isinstance(response_json, list):
raise Sindri.APIError("Received unexpected type for proof list response.")
if self.verbose_level > 0:
proof_detail_list = response_json.copy()
if self.verbose_level == 1:
proof_detail_list = []
for proof_detail in response_json:
proof_detail_list.append(self._get_verbose_1_proof_detail(proof_detail))
print(f"{pformat(proof_detail_list, indent=4)}\n")
return response_json
def get_all_circuits(self) -> list[dict]:
"""Return a list of all circuit infos. For information, refer to the
[API docs](https://sindri.app/docs/reference/api/circuit-list/).
Args:
- `None`
Returns:
- `circuits`: A list of circuit infos.
Raises:
- `Sindri.APIError`:
- Your API Key is invalid.
- There is an error connecting to the Sindri API.
"""
if self.verbose_level > 0:
print("Circuit: Get all circuits")
response_status_code, response_json = self._hit_api(
"GET",
"circuit/list",
)
if response_status_code != 200:
raise Sindri.APIError(
f"Unable to fetch circuits."
f" status={response_status_code} response={response_json}"
)
if not isinstance(response_json, list):
raise Sindri.APIError("Received unexpected type for circuit list response.")
if self.verbose_level > 0:
circuit_detail_list = response_json.copy()
if self.verbose_level == 1:
circuit_detail_list = []
for circuit_detail in response_json:
circuit_detail_list.append(self._get_verbose_1_circuit_detail(circuit_detail))
print(f"{pformat(circuit_detail_list, indent=4)}\n")
return response_json
def get_circuit(self, circuit_id: str, include_verification_key: bool = True) -> dict:
"""Get info for an existing circuit. For information, refer to the
[API docs](https://sindri.app/docs/reference/api/circuit-detail/).
Args:
- `circuit_id`: The circuit identifier of the circuit.
- `include_verification_key`: Indicates whether to include the verification key in the
response.
Returns:
- `circuit`: The info for a circuit.
Raises:
- `Sindri.APIError`:
- Your API Key is invalid.
- There is an error connecting to the Sindri API.
- The specified circuit does not exist.
"""
if self.verbose_level > 0:
print(f"Circuit: Get circuit detail for circuit_id: {circuit_id}")
circuit = self._get_circuit(circuit_id, include_verification_key=include_verification_key)
if self.verbose_level > 0:
circuit_detail = circuit.copy()
if self.verbose_level == 1:
circuit_detail = self._get_verbose_1_circuit_detail(circuit_detail)
print(f"{pformat(circuit_detail, indent=4)}\n")
return circuit
def get_smart_contract_verifier(self, circuit_id: str) -> str:
"""Get the smart contract verifier for an existing circuit.
NOTE: This method wraps an experimental Sindri API endpoint is subject to change at
any time.
Args:
- `circuit_id`: The circuit identifier of the circuit.
Returns:
- `smart_contract_verifier_code`: The smart contract verifier code for the circuit.
Raises:
- `Sindri.APIError`:
- Your API Key is invalid.
- There is an error connecting to the Sindri API.
- The specified circuit does not exist.
- The circuit's type does not support this feature.
- The circuit was compiled before this feature was released.
"""
if self.verbose_level > 0:
print(f"Circuit: Get circuit smart contract verifier for circuit_id: {circuit_id}")
response_status_code, response_json = self._hit_api(
"GET", f"circuit/{circuit_id}/smart_contract_verifier"
)
if response_status_code != 200:
raise Sindri.APIError(
f"Unable to fetch smart contract verifier code for circuit_id={circuit_id}."
f" status={response_status_code} response={response_json}"
)
# Extract smart_contract_verifier_code from response and check types
if not isinstance(response_json, dict):
raise Sindri.APIError(
"Received unexpected type for circuit smart contract verifier response."
)
try:
smart_contract_verifier_code: str = response_json["contract_code"]
except KeyError:
raise Sindri.APIError(
"Received unexpected type for circuit smart contract verifier response."
)
if not isinstance(smart_contract_verifier_code, str):
raise Sindri.APIError(
"Received unexpected type for circuit smart contract verifier response."
)
if self.verbose_level == 2:
print(smart_contract_verifier_code)
return smart_contract_verifier_code
def get_proof(
self,
proof_id: str,
include_proof: bool = True,
include_public: bool = True,
include_smart_contract_calldata: bool = False,
include_verification_key: bool = False,
) -> dict:
"""Get info for an existing proof. For information, refer to the
[API docs](https://sindri.app/docs/reference/api/proof-detail/).
Args:
- `proof_id`: The UUID4 identifier associated with this proof.
- `include_proof`: Indicates whether to include the proof in the response.
- `include_public`: Indicates whether to include the public inputs in the response.
- `include_smart_contract_calldata`: Indicates whether to include the proof and public
formatted as smart contract calldata in the response.
- `include_verification_key`: Indicates whether to include the verification key in the
response.
Returns:
- `proof`: The info for a proof.
Raises:
- `Sindri.APIError`:
- Your API Key is invalid.
- There is an error connecting to the Sindri API.
- The specified proof does not exist.
- `include_smart_contract_calldata=True` and the proof's circuit type does not support
generating calldata for its circuit's smart contract verifier or the proof was
generated before this feature was released.
"""
if self.verbose_level > 0:
print(f"Proof: Get proof detail for proof_id: {proof_id}")
proof = self._get_proof(
proof_id,
include_proof=include_proof,
include_public=include_public,
include_smart_contract_calldata=include_smart_contract_calldata,
include_verification_key=include_verification_key,
)
if self.verbose_level > 0:
proof_detail = proof.copy()
if self.verbose_level == 1:
proof_detail = self._get_verbose_1_proof_detail(proof_detail)
print(f"{pformat(proof_detail, indent=4)}\n")
return proof
def get_user_team_details(self) -> dict:
"""Get details about the user or team associated with the configured API Key.
Args:
- `None`
Returns:
- `team`: The info for the user/team.
Raises:
- `Sindri.APIError`:
- Your API Key is invalid.
- There is an error connecting to the Sindri API.
"""
if self.verbose_level > 0:
print("User/Team: Get user/team details for the provided API Key.")
response_status_code, response_json = self._hit_api("GET", "team/me")
if response_status_code != 200:
raise Sindri.APIError(
f"Unable to fetch team details."
f" status={response_status_code} response={response_json}"
)
if not isinstance(response_json, dict):
raise Sindri.APIError("Received unexpected type for team detail response.")
if self.verbose_level > 0:
print(f"{pformat(response_json, indent=4)}\n")
return response_json
def prove_circuit(
self,
circuit_id: str,
proof_input: str,
prover_implementation: str | None = None,
perform_verify: bool = False,
wait: bool = True,
) -> str:
"""Prove a circuit with specified inputs. For information, refer to the
[API docs](https://sindri.app/docs/reference/api/proof-create/).
Args:
- `circuit_id`: The circuit identifier of the circuit.
- `proof_input`: A string representing proof input which may be formatted as JSON for any
framework. Noir circuits optionally accept TOML formatted proof input.
- `prover_implementation`: For Sindri internal usage. The default value, `None`, chooses
the best supported prover implementation based on a variety of factors including the
available hardware, proving scheme, circuit size, and framework.
- `perform_verify`: A boolean indicating whether to perform an internal verification check
during the proof creation.
- `wait`:
- If `True`, block until the proof is finished generating.
- If `False`, submit the proof and return immediately.
Returns:
- `proof_id`: The UUID4 identifier associated with this proof. This is generated by Sindri.
Raises:
- `Sindri.APIError`:
- Your API Key is invalid.
- There is an error connecting to the Sindri API.
- The specified circuit does not exist.
- The proof input is improperly formatted.
- The proof generation fails. (if `wait=True`).
"""
# Return values
proof_id = ""
# 1. Submit a proof, obtain a proof_id.
if self.verbose_level > 0:
print("Prove circuit")
# Hit the circuit/<circuit_id>/prove endpoint
response_status_code, response_json = self._hit_api(
"POST",
f"circuit/{circuit_id}/prove",
data={
"proof_input": proof_input,
"perform_verify": perform_verify,
"prover_implementation": prover_implementation,
},
)
if response_status_code != 201:
raise Sindri.APIError(
f"Unable to prove circuit."
f" status={response_status_code} response={response_json}"
)
if not isinstance(response_json, dict):
raise Sindri.APIError("Received unexpected type for proof detail response.")
# Obtain proof_id from response
proof_id = response_json.get("proof_id", "")
if self.verbose_level > 0:
print(f" proof_id: {proof_id}")
if wait:
# 2. Poll proof detail until it has a status of Ready/Failed
if self.verbose_level > 0:
print("Proof: Poll until Ready/Failed")
for _ in range(self.max_polling_iterations):
proof = self._get_proof(
proof_id,
include_proof=False,
include_public=False,
include_smart_contract_calldata=False,
include_verification_key=False,
)
proof_status = proof.get("status", "")
if proof_status == "Failed":
raise Sindri.APIError(f"Prove circuit failed. error={proof.get('error', '')}")
if proof_status == "Ready":
break
time.sleep(self.polling_interval_sec)
else:
raise Sindri.APIError("Prove circuit polling timed out.")
if self.verbose_level > 0:
self.get_proof(proof_id)
# Prove circuit success!
return proof_id
def set_api_key(self, api_key: str) -> None:
"""Set the API Key for the Sindri instance.
Args:
- `api_key`: Your Sindri API Key.
Returns:
- `None`
Raises:
- `Sindri.APIError`:
- Your API Key is improperly formatted.
"""
if not isinstance(api_key, str):
raise Sindri.APIError("Invalid API Key")
if api_key == "":
raise Sindri.APIError("Invalid API Key")
self.api_key = api_key
self._set_json_request_headers()
if self.verbose_level > 0:
print(f"Sindri API Key: {self.api_key}")
def set_verbose_level(self, verbose_level: int) -> None:
"""Set the verbosity level for stdout printing.
Args:
- `verbose_level`: Must be either `0`, `1`, or `2`.
- `0`: Do not print anything to stdout.
- `1`: Print only necesessary information from Circuit/Proof objects.
- `2`: Print everything.
Returns:
- `None`
Raises:
- `Sindri.APIError`:
- `verbose_level` is invalid.
"""
if verbose_level not in Sindri.VERBOSE_LEVELS:
raise Sindri.APIError(
f"Invalid verbose_level. Must be an int in {Sindri.VERBOSE_LEVELS}."
)
self.verbose_level = verbose_level